From f9b01a161c432f231a2404e5e2069e0b3933af8d Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Mon, 26 Apr 2021 13:10:40 -0400 Subject: [PATCH 001/254] chore(revert): revert preventing normalization (#99) --- setup.py | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/setup.py b/setup.py index 213d0bd9..a6ee9706 100644 --- a/setup.py +++ b/setup.py @@ -17,20 +17,6 @@ import setuptools -# Disable version normalization performed by setuptools.setup() -try: - # Try the approach of using sic(), added in setuptools 46.1.0 - from setuptools import sic -except ImportError: - # Try the approach of replacing packaging.version.Version - sic = lambda v: v - try: - # setuptools >=39.0.0 uses packaging from setuptools.extern - from setuptools.extern import packaging - except ImportError: - # setuptools <39.0.0 uses packaging from pkg_resources.extern - from pkg_resources.extern import packaging - packaging.version.Version = packaging.version.LegacyVersion # Package metadata. @@ -73,7 +59,7 @@ setuptools.setup( name=name, - version=sic(version), + version=version, description=description, long_description=readme, author="Google LLC", From 9929046e904d95c0b9ada333768b5cad4ea92e3f Mon Sep 17 00:00:00 2001 From: "google-cloud-policy-bot[bot]" <80869356+google-cloud-policy-bot[bot]@users.noreply.github.com> Date: Wed, 12 May 2021 13:18:05 +0000 Subject: [PATCH 002/254] chore: add SECURITY.md (#102) chore: add SECURITY.md --- SECURITY.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 SECURITY.md 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. From 03fc160494ae7eaa4e75fae2f5a2d0a116f1e795 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sun, 16 May 2021 13:26:01 +0000 Subject: [PATCH 003/254] chore: new owl bot post processor docker image (#112) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa --- .github/.OwlBot.lock.yaml | 2 +- .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 16 +--------------- noxfile.py | 14 ++------------ 4 files changed, 5 insertions(+), 29 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 60384b30..864c1765 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: - digest: sha256:cfc0e802701262c211703c468874d767f65dabe6a1a71d0e07bfc8a3d5175f32 image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa 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/CONTRIBUTING.rst b/CONTRIBUTING.rst index 64cb52b3..3938ab27 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/noxfile.py b/noxfile.py index 4d37cd3a..70417e8c 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") From 1776edc7c07b235b9d725478be38cf3526b09e15 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Mon, 17 May 2021 15:37:14 -0400 Subject: [PATCH 004/254] chore: add library type to .repo-metadata.json (#106) * chore: add library type to .repo-metadata.json * Update library type to GAPIC_AUTO --- .repo-metadata.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index b87aaa1f..8e7854be 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -6,8 +6,9 @@ "issue_tracker": "https://issuetracker.google.com/savedsearches/559753", "release_level": "ga", "language": "python", + "library_type": "GAPIC_AUTO", "repo": "googleapis/python-language", "distribution_name": "google-cloud-language", "api_id": "language.googleapis.com", "requires_billing": true -} \ No newline at end of file +} From 0dcb15eb46b60bd816a6919464be1331c2c8de41 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 20 May 2021 17:36:02 +0000 Subject: [PATCH 005/254] chore: upgrade gapic-generator-python to 0.46.3 (#111) PiperOrigin-RevId: 373649163 Source-Link: https://github.com/googleapis/googleapis/commit/7e1b14e6c7a9ab96d2db7e4a131981f162446d34 Source-Link: https://github.com/googleapis/googleapis-gen/commit/0a3c7d272d697796db75857bac73905c68e498c3 fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list feat: support self-signed JWT flow for service accounts chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py --- google/cloud/language/__init__.py | 16 +- google/cloud/language_v1/__init__.py | 9 +- google/cloud/language_v1/gapic_metadata.json | 83 +++ google/cloud/language_v1/services/__init__.py | 1 - .../services/language_service/__init__.py | 2 - .../services/language_service/async_client.py | 53 +- .../services/language_service/client.py | 75 ++- .../language_service/transports/__init__.py | 2 - .../language_service/transports/base.py | 152 ++++-- .../language_service/transports/grpc.py | 22 +- .../transports/grpc_asyncio.py | 23 +- google/cloud/language_v1/types/__init__.py | 2 - .../language_v1/types/language_service.py | 115 +---- google/cloud/language_v1beta2/__init__.py | 9 +- .../language_v1beta2/gapic_metadata.json | 83 +++ .../language_v1beta2/services/__init__.py | 1 - .../services/language_service/__init__.py | 2 - .../services/language_service/async_client.py | 53 +- .../services/language_service/client.py | 75 ++- .../language_service/transports/__init__.py | 2 - .../language_service/transports/base.py | 152 ++++-- .../language_service/transports/grpc.py | 22 +- .../transports/grpc_asyncio.py | 23 +- .../cloud/language_v1beta2/types/__init__.py | 2 - .../types/language_service.py | 117 +---- owlbot.py | 7 + scripts/fixup_language_v1_keywords.py | 17 +- scripts/fixup_language_v1beta2_keywords.py | 17 +- tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/language_v1/__init__.py | 1 - .../language_v1/test_language_service.py | 483 ++++++++++++------ tests/unit/gapic/language_v1beta2/__init__.py | 1 - .../language_v1beta2/test_language_service.py | 483 ++++++++++++------ 35 files changed, 1302 insertions(+), 848 deletions(-) create mode 100644 google/cloud/language_v1/gapic_metadata.json create mode 100644 google/cloud/language_v1beta2/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/google/cloud/language/__init__.py b/google/cloud/language/__init__.py index 4426b53c..ef7f887d 100644 --- a/google/cloud/language/__init__.py +++ b/google/cloud/language/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,12 +14,13 @@ # limitations under the License. # -from google.cloud.language_v1.services.language_service.async_client import ( - LanguageServiceAsyncClient, -) from google.cloud.language_v1.services.language_service.client import ( LanguageServiceClient, ) +from google.cloud.language_v1.services.language_service.async_client import ( + LanguageServiceAsyncClient, +) + from google.cloud.language_v1.types.language_service import AnalyzeEntitiesRequest from google.cloud.language_v1.types.language_service import AnalyzeEntitiesResponse from google.cloud.language_v1.types.language_service import ( @@ -40,7 +40,6 @@ from google.cloud.language_v1.types.language_service import ClassifyTextResponse from google.cloud.language_v1.types.language_service import DependencyEdge from google.cloud.language_v1.types.language_service import Document -from google.cloud.language_v1.types.language_service import EncodingType from google.cloud.language_v1.types.language_service import Entity from google.cloud.language_v1.types.language_service import EntityMention from google.cloud.language_v1.types.language_service import PartOfSpeech @@ -48,8 +47,11 @@ from google.cloud.language_v1.types.language_service import Sentiment from google.cloud.language_v1.types.language_service import TextSpan from google.cloud.language_v1.types.language_service import Token +from google.cloud.language_v1.types.language_service import EncodingType __all__ = ( + "LanguageServiceClient", + "LanguageServiceAsyncClient", "AnalyzeEntitiesRequest", "AnalyzeEntitiesResponse", "AnalyzeEntitySentimentRequest", @@ -65,14 +67,12 @@ "ClassifyTextResponse", "DependencyEdge", "Document", - "EncodingType", "Entity", "EntityMention", - "LanguageServiceAsyncClient", - "LanguageServiceClient", "PartOfSpeech", "Sentence", "Sentiment", "TextSpan", "Token", + "EncodingType", ) diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py index ba3826be..ad83a6fa 100644 --- a/google/cloud/language_v1/__init__.py +++ b/google/cloud/language_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.language_service import LanguageServiceClient +from .services.language_service import LanguageServiceAsyncClient + from .types.language_service import AnalyzeEntitiesRequest from .types.language_service import AnalyzeEntitiesResponse from .types.language_service import AnalyzeEntitySentimentRequest @@ -31,7 +32,6 @@ from .types.language_service import ClassifyTextResponse from .types.language_service import DependencyEdge from .types.language_service import Document -from .types.language_service import EncodingType from .types.language_service import Entity from .types.language_service import EntityMention from .types.language_service import PartOfSpeech @@ -39,9 +39,10 @@ from .types.language_service import Sentiment from .types.language_service import TextSpan from .types.language_service import Token - +from .types.language_service import EncodingType __all__ = ( + "LanguageServiceAsyncClient", "AnalyzeEntitiesRequest", "AnalyzeEntitiesResponse", "AnalyzeEntitySentimentRequest", @@ -60,10 +61,10 @@ "EncodingType", "Entity", "EntityMention", + "LanguageServiceClient", "PartOfSpeech", "Sentence", "Sentiment", "TextSpan", "Token", - "LanguageServiceClient", ) diff --git a/google/cloud/language_v1/gapic_metadata.json b/google/cloud/language_v1/gapic_metadata.json new file mode 100644 index 00000000..64d3c3e4 --- /dev/null +++ b/google/cloud/language_v1/gapic_metadata.json @@ -0,0 +1,83 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.language_v1", + "protoPackage": "google.cloud.language.v1", + "schema": "1.0", + "services": { + "LanguageService": { + "clients": { + "grpc": { + "libraryClient": "LanguageServiceClient", + "rpcs": { + "AnalyzeEntities": { + "methods": [ + "analyze_entities" + ] + }, + "AnalyzeEntitySentiment": { + "methods": [ + "analyze_entity_sentiment" + ] + }, + "AnalyzeSentiment": { + "methods": [ + "analyze_sentiment" + ] + }, + "AnalyzeSyntax": { + "methods": [ + "analyze_syntax" + ] + }, + "AnnotateText": { + "methods": [ + "annotate_text" + ] + }, + "ClassifyText": { + "methods": [ + "classify_text" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LanguageServiceAsyncClient", + "rpcs": { + "AnalyzeEntities": { + "methods": [ + "analyze_entities" + ] + }, + "AnalyzeEntitySentiment": { + "methods": [ + "analyze_entity_sentiment" + ] + }, + "AnalyzeSentiment": { + "methods": [ + "analyze_sentiment" + ] + }, + "AnalyzeSyntax": { + "methods": [ + "analyze_syntax" + ] + }, + "AnnotateText": { + "methods": [ + "annotate_text" + ] + }, + "ClassifyText": { + "methods": [ + "classify_text" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/language_v1/services/__init__.py b/google/cloud/language_v1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/language_v1/services/__init__.py +++ b/google/cloud/language_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/language_v1/services/language_service/__init__.py b/google/cloud/language_v1/services/language_service/__init__.py index d2aff222..46ba988d 100644 --- a/google/cloud/language_v1/services/language_service/__init__.py +++ b/google/cloud/language_v1/services/language_service/__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 LanguageServiceClient from .async_client import LanguageServiceAsyncClient diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 2fd88f1e..eb800802 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/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.language_v1.types import language_service - from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport from .client import LanguageServiceClient @@ -51,24 +48,20 @@ class LanguageServiceAsyncClient: parse_common_billing_account_path = staticmethod( LanguageServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(LanguageServiceClient.common_folder_path) parse_common_folder_path = staticmethod( LanguageServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( LanguageServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( LanguageServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(LanguageServiceClient.common_project_path) parse_common_project_path = staticmethod( LanguageServiceClient.parse_common_project_path ) - common_location_path = staticmethod(LanguageServiceClient.common_location_path) parse_common_location_path = staticmethod( LanguageServiceClient.parse_common_location_path @@ -76,7 +69,8 @@ class LanguageServiceAsyncClient: @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. @@ -91,7 +85,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 @@ -108,7 +102,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> LanguageServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: LanguageServiceTransport: The transport used by the client instance. @@ -122,12 +116,12 @@ def transport(self) -> LanguageServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, LanguageServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the language service client. + """Instantiates the language service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +153,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = LanguageServiceClient( credentials=credentials, transport=transport, @@ -195,7 +188,6 @@ async def analyze_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -222,7 +214,6 @@ async def analyze_sentiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -237,7 +228,8 @@ async def analyze_sentiment( 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 +273,6 @@ async def analyze_entities( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not 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 analyze_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -321,7 +311,8 @@ async def analyze_entities( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -366,7 +357,6 @@ async def analyze_entity_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -393,7 +383,6 @@ async def analyze_entity_sentiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -408,7 +397,8 @@ async def analyze_entity_sentiment( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -451,7 +441,6 @@ async def analyze_syntax( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -476,7 +465,6 @@ async def analyze_syntax( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -491,7 +479,8 @@ async def analyze_syntax( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -525,7 +514,6 @@ async def classify_text( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -552,7 +540,6 @@ async def classify_text( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document @@ -565,7 +552,8 @@ async def classify_text( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -616,7 +604,6 @@ async def annotate_text( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -643,7 +630,6 @@ async def annotate_text( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if features is not None: @@ -660,7 +646,8 @@ async def annotate_text( 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/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 0856292b..a86da109 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/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.language_v1.types import language_service - from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LanguageServiceGrpcTransport from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport @@ -54,7 +51,7 @@ class LanguageServiceClientMeta(type): _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[LanguageServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -79,7 +76,8 @@ class LanguageServiceClient(metaclass=LanguageServiceClientMeta): @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: @@ -113,7 +111,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. @@ -130,7 +129,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 @@ -149,16 +148,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> LanguageServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - LanguageServiceTransport: The transport used by the client instance. + LanguageServiceTransport: 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, ) @@ -171,7 +171,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 @@ -182,7 +182,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 @@ -193,7 +193,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 @@ -204,7 +204,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, ) @@ -218,12 +218,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, LanguageServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the language service client. + """Instantiates the language service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -278,9 +278,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: @@ -292,12 +293,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. @@ -312,8 +315,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: @@ -356,7 +359,6 @@ def analyze_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not 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 analyze_sentiment( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeSentimentRequest): request = language_service.AnalyzeSentimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -434,7 +434,6 @@ def analyze_entities( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -461,10 +460,8 @@ def analyze_entities( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeEntitiesRequest): request = language_service.AnalyzeEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -511,7 +508,6 @@ def analyze_entity_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -540,10 +536,8 @@ def analyze_entity_sentiment( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeEntitySentimentRequest): request = language_service.AnalyzeEntitySentimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -588,7 +582,6 @@ def analyze_syntax( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -615,10 +608,8 @@ def analyze_syntax( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeSyntaxRequest): request = language_service.AnalyzeSyntaxRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -654,7 +645,6 @@ def classify_text( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -683,10 +673,8 @@ def classify_text( # there are no flattened fields. if not isinstance(request, language_service.ClassifyTextRequest): request = language_service.ClassifyTextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document @@ -737,7 +725,6 @@ def annotate_text( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -766,10 +753,8 @@ def annotate_text( # there are no flattened fields. if not isinstance(request, language_service.AnnotateTextRequest): request = language_service.AnnotateTextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if features is not None: diff --git a/google/cloud/language_v1/services/language_service/transports/__init__.py b/google/cloud/language_v1/services/language_service/transports/__init__.py index f7e7e555..be3ebc9a 100644 --- a/google/cloud/language_v1/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1/services/language_service/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/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 1add68ea..4f538035 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/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.language_v1.types import language_service - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-language",).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 LanguageServiceTransport(abc.ABC): """Abstract transport class for LanguageService.""" @@ -44,21 +54,24 @@ class LanguageServiceTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "language.googleapis.com" + def __init__( self, *, - host: str = "language.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, ), @@ -128,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, ), @@ -142,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, ), @@ -156,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, ), @@ -170,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, ), @@ -184,7 +249,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, ), @@ -196,11 +262,11 @@ def _prep_wrapped_messages(self, client_info): @property def analyze_sentiment( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeSentimentRequest], - typing.Union[ + Union[ language_service.AnalyzeSentimentResponse, - typing.Awaitable[language_service.AnalyzeSentimentResponse], + Awaitable[language_service.AnalyzeSentimentResponse], ], ]: raise NotImplementedError() @@ -208,11 +274,11 @@ def analyze_sentiment( @property def analyze_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeEntitiesRequest], - typing.Union[ + Union[ language_service.AnalyzeEntitiesResponse, - typing.Awaitable[language_service.AnalyzeEntitiesResponse], + Awaitable[language_service.AnalyzeEntitiesResponse], ], ]: raise NotImplementedError() @@ -220,11 +286,11 @@ def analyze_entities( @property def analyze_entity_sentiment( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeEntitySentimentRequest], - typing.Union[ + Union[ language_service.AnalyzeEntitySentimentResponse, - typing.Awaitable[language_service.AnalyzeEntitySentimentResponse], + Awaitable[language_service.AnalyzeEntitySentimentResponse], ], ]: raise NotImplementedError() @@ -232,11 +298,11 @@ def analyze_entity_sentiment( @property def analyze_syntax( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeSyntaxRequest], - typing.Union[ + Union[ language_service.AnalyzeSyntaxResponse, - typing.Awaitable[language_service.AnalyzeSyntaxResponse], + Awaitable[language_service.AnalyzeSyntaxResponse], ], ]: raise NotImplementedError() @@ -244,11 +310,11 @@ def analyze_syntax( @property def classify_text( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.ClassifyTextRequest], - typing.Union[ + Union[ language_service.ClassifyTextResponse, - typing.Awaitable[language_service.ClassifyTextResponse], + Awaitable[language_service.ClassifyTextResponse], ], ]: raise NotImplementedError() @@ -256,11 +322,11 @@ def classify_text( @property def annotate_text( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnnotateTextRequest], - typing.Union[ + Union[ language_service.AnnotateTextResponse, - typing.Awaitable[language_service.AnnotateTextResponse], + Awaitable[language_service.AnnotateTextResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index fe382136..209156ba 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/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.language_v1.types import language_service - from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO @@ -51,7 +48,7 @@ def __init__( self, *, host: str = "language.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -65,7 +62,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 @@ -175,7 +173,7 @@ def __init__( def create_channel( cls, host: str = "language.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, @@ -206,13 +204,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/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index a262a657..1647c0e5 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/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.language_v1.types import language_service - from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .grpc import LanguageServiceGrpcTransport @@ -54,7 +51,7 @@ class LanguageServiceGrpcAsyncIOTransport(LanguageServiceTransport): def create_channel( cls, host: str = "language.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, @@ -81,13 +78,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, ) @@ -95,7 +94,7 @@ def __init__( self, *, host: str = "language.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, @@ -109,7 +108,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 @@ -167,7 +167,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/language_v1/types/__init__.py b/google/cloud/language_v1/types/__init__.py index 025cbb98..adb04117 100644 --- a/google/cloud/language_v1/types/__init__.py +++ b/google/cloud/language_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 .language_service import ( AnalyzeEntitiesRequest, AnalyzeEntitiesResponse, diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 10f0cb9e..1138d63e 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.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 @@ -96,17 +94,13 @@ class Type(proto.Enum): HTML = 2 type_ = proto.Field(proto.ENUM, number=1, enum=Type,) - - content = proto.Field(proto.STRING, number=2, oneof="source") - - gcs_content_uri = proto.Field(proto.STRING, number=3, oneof="source") - - language = proto.Field(proto.STRING, number=4) + content = proto.Field(proto.STRING, number=2, oneof="source",) + gcs_content_uri = proto.Field(proto.STRING, number=3, oneof="source",) + language = proto.Field(proto.STRING, number=4,) class Sentence(proto.Message): r"""Represents a sentence in the input document. - Attributes: text (google.cloud.language_v1.types.TextSpan): The sentence text. @@ -118,7 +112,6 @@ class Sentence(proto.Message): """ text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - sentiment = proto.Field(proto.MESSAGE, number=2, message="Sentiment",) @@ -179,22 +172,16 @@ class Type(proto.Enum): NUMBER = 12 PRICE = 13 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=3) - - salience = proto.Field(proto.FLOAT, number=4) - + metadata = proto.MapField(proto.STRING, proto.STRING, number=3,) + salience = proto.Field(proto.FLOAT, number=4,) mentions = proto.RepeatedField(proto.MESSAGE, number=5, message="EntityMention",) - sentiment = proto.Field(proto.MESSAGE, number=6, message="Sentiment",) class Token(proto.Message): r"""Represents the smallest syntactic building block of the text. - Attributes: text (google.cloud.language_v1.types.TextSpan): The token text. @@ -208,12 +195,9 @@ class Token(proto.Message): """ text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - part_of_speech = proto.Field(proto.MESSAGE, number=2, message="PartOfSpeech",) - dependency_edge = proto.Field(proto.MESSAGE, number=3, message="DependencyEdge",) - - lemma = proto.Field(proto.STRING, number=4) + lemma = proto.Field(proto.STRING, number=4,) class Sentiment(proto.Message): @@ -230,9 +214,8 @@ class Sentiment(proto.Message): sentiment) and 1.0 (positive sentiment). """ - magnitude = proto.Field(proto.FLOAT, number=2) - - score = proto.Field(proto.FLOAT, number=3) + magnitude = proto.Field(proto.FLOAT, number=2,) + score = proto.Field(proto.FLOAT, number=3,) class PartOfSpeech(proto.Message): @@ -405,27 +388,16 @@ class Voice(proto.Enum): PASSIVE = 3 tag = proto.Field(proto.ENUM, number=1, enum=Tag,) - aspect = proto.Field(proto.ENUM, number=2, enum=Aspect,) - case = proto.Field(proto.ENUM, number=3, enum=Case,) - form = proto.Field(proto.ENUM, number=4, enum=Form,) - gender = proto.Field(proto.ENUM, number=5, enum=Gender,) - mood = proto.Field(proto.ENUM, number=6, enum=Mood,) - number = proto.Field(proto.ENUM, number=7, enum=Number,) - person = proto.Field(proto.ENUM, number=8, enum=Person,) - proper = proto.Field(proto.ENUM, number=9, enum=Proper,) - reciprocity = proto.Field(proto.ENUM, number=10, enum=Reciprocity,) - tense = proto.Field(proto.ENUM, number=11, enum=Tense,) - voice = proto.Field(proto.ENUM, number=12, enum=Voice,) @@ -532,8 +504,7 @@ class Label(proto.Enum): MES = 81 NCOMP = 82 - head_token_index = proto.Field(proto.INT32, number=1) - + head_token_index = proto.Field(proto.INT32, number=1,) label = proto.Field(proto.ENUM, number=2, enum=Label,) @@ -561,15 +532,12 @@ class Type(proto.Enum): COMMON = 2 text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - sentiment = proto.Field(proto.MESSAGE, number=3, message="Sentiment",) class TextSpan(proto.Message): r"""Represents an output piece of text. - Attributes: content (str): The content of the output text. @@ -580,14 +548,12 @@ class TextSpan(proto.Message): specified in the API request. """ - content = proto.Field(proto.STRING, number=1) - - begin_offset = proto.Field(proto.INT32, number=2) + content = proto.Field(proto.STRING, number=1,) + begin_offset = proto.Field(proto.INT32, number=2,) class ClassificationCategory(proto.Message): r"""Represents a category returned from the text classifier. - Attributes: name (str): The name of the category representing the document, from the @@ -599,14 +565,12 @@ class ClassificationCategory(proto.Message): that this category represents the given text. """ - name = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + name = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) class AnalyzeSentimentRequest(proto.Message): r"""The sentiment analysis request message. - Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -616,13 +580,11 @@ class AnalyzeSentimentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeSentimentResponse(proto.Message): r"""The sentiment analysis response message. - Attributes: document_sentiment (google.cloud.language_v1.types.Sentiment): The overall sentiment of the input document. @@ -638,15 +600,12 @@ class AnalyzeSentimentResponse(proto.Message): """ document_sentiment = proto.Field(proto.MESSAGE, number=1, message="Sentiment",) - - language = proto.Field(proto.STRING, number=2) - + language = proto.Field(proto.STRING, number=2,) sentences = proto.RepeatedField(proto.MESSAGE, number=3, message="Sentence",) class AnalyzeEntitySentimentRequest(proto.Message): r"""The entity-level sentiment analysis request message. - Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -656,13 +615,11 @@ class AnalyzeEntitySentimentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeEntitySentimentResponse(proto.Message): r"""The entity-level sentiment analysis response message. - Attributes: entities (Sequence[google.cloud.language_v1.types.Entity]): The recognized entities in the input document @@ -676,13 +633,11 @@ class AnalyzeEntitySentimentResponse(proto.Message): """ entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - - language = proto.Field(proto.STRING, number=2) + language = proto.Field(proto.STRING, number=2,) class AnalyzeEntitiesRequest(proto.Message): r"""The entity analysis request message. - Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -692,13 +647,11 @@ class AnalyzeEntitiesRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeEntitiesResponse(proto.Message): r"""The entity analysis response message. - Attributes: entities (Sequence[google.cloud.language_v1.types.Entity]): The recognized entities in the input @@ -712,13 +665,11 @@ class AnalyzeEntitiesResponse(proto.Message): """ entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - - language = proto.Field(proto.STRING, number=2) + language = proto.Field(proto.STRING, number=2,) class AnalyzeSyntaxRequest(proto.Message): r"""The syntax analysis request message. - Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -728,13 +679,11 @@ class AnalyzeSyntaxRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeSyntaxResponse(proto.Message): r"""The syntax analysis response message. - Attributes: sentences (Sequence[google.cloud.language_v1.types.Sentence]): Sentences in the input document. @@ -750,15 +699,12 @@ class AnalyzeSyntaxResponse(proto.Message): """ sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - - language = proto.Field(proto.STRING, number=3) + language = proto.Field(proto.STRING, number=3,) class ClassifyTextRequest(proto.Message): r"""The document classification request message. - Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -769,7 +715,6 @@ class ClassifyTextRequest(proto.Message): class ClassifyTextResponse(proto.Message): r"""The document classification response message. - Attributes: categories (Sequence[google.cloud.language_v1.types.ClassificationCategory]): Categories representing the input document. @@ -814,26 +759,19 @@ class Features(proto.Message): Classify the full document into categories. """ - extract_syntax = proto.Field(proto.BOOL, number=1) - - extract_entities = proto.Field(proto.BOOL, number=2) - - extract_document_sentiment = proto.Field(proto.BOOL, number=3) - - extract_entity_sentiment = proto.Field(proto.BOOL, number=4) - - classify_text = proto.Field(proto.BOOL, number=6) + extract_syntax = proto.Field(proto.BOOL, number=1,) + extract_entities = proto.Field(proto.BOOL, number=2,) + extract_document_sentiment = proto.Field(proto.BOOL, number=3,) + extract_entity_sentiment = proto.Field(proto.BOOL, number=4,) + classify_text = proto.Field(proto.BOOL, number=6,) document = proto.Field(proto.MESSAGE, number=1, message="Document",) - features = proto.Field(proto.MESSAGE, number=2, message=Features,) - encoding_type = proto.Field(proto.ENUM, number=3, enum="EncodingType",) class AnnotateTextResponse(proto.Message): r"""The text annotations response message. - Attributes: sentences (Sequence[google.cloud.language_v1.types.Sentence]): Sentences in the input document. Populated if the user @@ -862,15 +800,10 @@ class AnnotateTextResponse(proto.Message): """ sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - entities = proto.RepeatedField(proto.MESSAGE, number=3, message="Entity",) - document_sentiment = proto.Field(proto.MESSAGE, number=4, message="Sentiment",) - - language = proto.Field(proto.STRING, number=5) - + language = proto.Field(proto.STRING, number=5,) categories = proto.RepeatedField( proto.MESSAGE, number=6, message="ClassificationCategory", ) diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py index ba3826be..ad83a6fa 100644 --- a/google/cloud/language_v1beta2/__init__.py +++ b/google/cloud/language_v1beta2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.language_service import LanguageServiceClient +from .services.language_service import LanguageServiceAsyncClient + from .types.language_service import AnalyzeEntitiesRequest from .types.language_service import AnalyzeEntitiesResponse from .types.language_service import AnalyzeEntitySentimentRequest @@ -31,7 +32,6 @@ from .types.language_service import ClassifyTextResponse from .types.language_service import DependencyEdge from .types.language_service import Document -from .types.language_service import EncodingType from .types.language_service import Entity from .types.language_service import EntityMention from .types.language_service import PartOfSpeech @@ -39,9 +39,10 @@ from .types.language_service import Sentiment from .types.language_service import TextSpan from .types.language_service import Token - +from .types.language_service import EncodingType __all__ = ( + "LanguageServiceAsyncClient", "AnalyzeEntitiesRequest", "AnalyzeEntitiesResponse", "AnalyzeEntitySentimentRequest", @@ -60,10 +61,10 @@ "EncodingType", "Entity", "EntityMention", + "LanguageServiceClient", "PartOfSpeech", "Sentence", "Sentiment", "TextSpan", "Token", - "LanguageServiceClient", ) diff --git a/google/cloud/language_v1beta2/gapic_metadata.json b/google/cloud/language_v1beta2/gapic_metadata.json new file mode 100644 index 00000000..dbb6d13e --- /dev/null +++ b/google/cloud/language_v1beta2/gapic_metadata.json @@ -0,0 +1,83 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.language_v1beta2", + "protoPackage": "google.cloud.language.v1beta2", + "schema": "1.0", + "services": { + "LanguageService": { + "clients": { + "grpc": { + "libraryClient": "LanguageServiceClient", + "rpcs": { + "AnalyzeEntities": { + "methods": [ + "analyze_entities" + ] + }, + "AnalyzeEntitySentiment": { + "methods": [ + "analyze_entity_sentiment" + ] + }, + "AnalyzeSentiment": { + "methods": [ + "analyze_sentiment" + ] + }, + "AnalyzeSyntax": { + "methods": [ + "analyze_syntax" + ] + }, + "AnnotateText": { + "methods": [ + "annotate_text" + ] + }, + "ClassifyText": { + "methods": [ + "classify_text" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LanguageServiceAsyncClient", + "rpcs": { + "AnalyzeEntities": { + "methods": [ + "analyze_entities" + ] + }, + "AnalyzeEntitySentiment": { + "methods": [ + "analyze_entity_sentiment" + ] + }, + "AnalyzeSentiment": { + "methods": [ + "analyze_sentiment" + ] + }, + "AnalyzeSyntax": { + "methods": [ + "analyze_syntax" + ] + }, + "AnnotateText": { + "methods": [ + "annotate_text" + ] + }, + "ClassifyText": { + "methods": [ + "classify_text" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/language_v1beta2/services/__init__.py b/google/cloud/language_v1beta2/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/language_v1beta2/services/__init__.py +++ b/google/cloud/language_v1beta2/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/language_v1beta2/services/language_service/__init__.py b/google/cloud/language_v1beta2/services/language_service/__init__.py index d2aff222..46ba988d 100644 --- a/google/cloud/language_v1beta2/services/language_service/__init__.py +++ b/google/cloud/language_v1beta2/services/language_service/__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 LanguageServiceClient from .async_client import LanguageServiceAsyncClient diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index bbb4be81..711bc55c 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/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.language_v1beta2.types import language_service - from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport from .client import LanguageServiceClient @@ -51,24 +48,20 @@ class LanguageServiceAsyncClient: parse_common_billing_account_path = staticmethod( LanguageServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(LanguageServiceClient.common_folder_path) parse_common_folder_path = staticmethod( LanguageServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( LanguageServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( LanguageServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(LanguageServiceClient.common_project_path) parse_common_project_path = staticmethod( LanguageServiceClient.parse_common_project_path ) - common_location_path = staticmethod(LanguageServiceClient.common_location_path) parse_common_location_path = staticmethod( LanguageServiceClient.parse_common_location_path @@ -76,7 +69,8 @@ class LanguageServiceAsyncClient: @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. @@ -91,7 +85,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 @@ -108,7 +102,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> LanguageServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: LanguageServiceTransport: The transport used by the client instance. @@ -122,12 +116,12 @@ def transport(self) -> LanguageServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, LanguageServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the language service client. + """Instantiates the language service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +153,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = LanguageServiceClient( credentials=credentials, transport=transport, @@ -196,7 +189,6 @@ async def analyze_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -223,7 +215,6 @@ async def analyze_sentiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -238,7 +229,8 @@ async def analyze_sentiment( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -282,7 +274,6 @@ async def analyze_entities( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +298,6 @@ async def analyze_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -322,7 +312,8 @@ async def analyze_entities( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -367,7 +358,6 @@ async def analyze_entity_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -394,7 +384,6 @@ async def analyze_entity_sentiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -409,7 +398,8 @@ async def analyze_entity_sentiment( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -452,7 +442,6 @@ async def analyze_syntax( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -477,7 +466,6 @@ async def analyze_syntax( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -492,7 +480,8 @@ async def analyze_syntax( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -526,7 +515,6 @@ async def classify_text( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -553,7 +541,6 @@ async def classify_text( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document @@ -566,7 +553,8 @@ async def classify_text( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -617,7 +605,6 @@ async def annotate_text( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -644,7 +631,6 @@ async def annotate_text( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if features is not None: @@ -661,7 +647,8 @@ async def annotate_text( 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/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 9eba35d5..080e5909 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/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.language_v1beta2.types import language_service - from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LanguageServiceGrpcTransport from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport @@ -54,7 +51,7 @@ class LanguageServiceClientMeta(type): _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[LanguageServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -79,7 +76,8 @@ class LanguageServiceClient(metaclass=LanguageServiceClientMeta): @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: @@ -113,7 +111,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. @@ -130,7 +129,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 @@ -149,16 +148,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> LanguageServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - LanguageServiceTransport: The transport used by the client instance. + LanguageServiceTransport: 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, ) @@ -171,7 +171,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 @@ -182,7 +182,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 @@ -193,7 +193,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 @@ -204,7 +204,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, ) @@ -218,12 +218,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, LanguageServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the language service client. + """Instantiates the language service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -278,9 +278,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: @@ -292,12 +293,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. @@ -312,8 +315,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: @@ -357,7 +360,6 @@ def analyze_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -386,10 +388,8 @@ def analyze_sentiment( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeSentimentRequest): request = language_service.AnalyzeSentimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -435,7 +435,6 @@ def analyze_entities( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -462,10 +461,8 @@ def analyze_entities( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeEntitiesRequest): request = language_service.AnalyzeEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -512,7 +509,6 @@ def analyze_entity_sentiment( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -541,10 +537,8 @@ def analyze_entity_sentiment( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeEntitySentimentRequest): request = language_service.AnalyzeEntitySentimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -589,7 +583,6 @@ def analyze_syntax( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -616,10 +609,8 @@ def analyze_syntax( # there are no flattened fields. if not isinstance(request, language_service.AnalyzeSyntaxRequest): request = language_service.AnalyzeSyntaxRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if encoding_type is not None: @@ -655,7 +646,6 @@ def classify_text( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -684,10 +674,8 @@ def classify_text( # there are no flattened fields. if not isinstance(request, language_service.ClassifyTextRequest): request = language_service.ClassifyTextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document @@ -738,7 +726,6 @@ def annotate_text( This corresponds to the ``encoding_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -767,10 +754,8 @@ def annotate_text( # there are no flattened fields. if not isinstance(request, language_service.AnnotateTextRequest): request = language_service.AnnotateTextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if features is not None: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py index f7e7e555..be3ebc9a 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1beta2/services/language_service/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/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 65a1685c..66de5600 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/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.language_v1beta2.types import language_service - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-language",).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 LanguageServiceTransport(abc.ABC): """Abstract transport class for LanguageService.""" @@ -44,21 +54,24 @@ class LanguageServiceTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "language.googleapis.com" + def __init__( self, *, - host: str = "language.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, ), @@ -128,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, ), @@ -142,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, ), @@ -156,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, ), @@ -170,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, ), @@ -184,7 +249,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, ), @@ -196,11 +262,11 @@ def _prep_wrapped_messages(self, client_info): @property def analyze_sentiment( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeSentimentRequest], - typing.Union[ + Union[ language_service.AnalyzeSentimentResponse, - typing.Awaitable[language_service.AnalyzeSentimentResponse], + Awaitable[language_service.AnalyzeSentimentResponse], ], ]: raise NotImplementedError() @@ -208,11 +274,11 @@ def analyze_sentiment( @property def analyze_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeEntitiesRequest], - typing.Union[ + Union[ language_service.AnalyzeEntitiesResponse, - typing.Awaitable[language_service.AnalyzeEntitiesResponse], + Awaitable[language_service.AnalyzeEntitiesResponse], ], ]: raise NotImplementedError() @@ -220,11 +286,11 @@ def analyze_entities( @property def analyze_entity_sentiment( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeEntitySentimentRequest], - typing.Union[ + Union[ language_service.AnalyzeEntitySentimentResponse, - typing.Awaitable[language_service.AnalyzeEntitySentimentResponse], + Awaitable[language_service.AnalyzeEntitySentimentResponse], ], ]: raise NotImplementedError() @@ -232,11 +298,11 @@ def analyze_entity_sentiment( @property def analyze_syntax( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnalyzeSyntaxRequest], - typing.Union[ + Union[ language_service.AnalyzeSyntaxResponse, - typing.Awaitable[language_service.AnalyzeSyntaxResponse], + Awaitable[language_service.AnalyzeSyntaxResponse], ], ]: raise NotImplementedError() @@ -244,11 +310,11 @@ def analyze_syntax( @property def classify_text( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.ClassifyTextRequest], - typing.Union[ + Union[ language_service.ClassifyTextResponse, - typing.Awaitable[language_service.ClassifyTextResponse], + Awaitable[language_service.ClassifyTextResponse], ], ]: raise NotImplementedError() @@ -256,11 +322,11 @@ def classify_text( @property def annotate_text( self, - ) -> typing.Callable[ + ) -> Callable[ [language_service.AnnotateTextRequest], - typing.Union[ + Union[ language_service.AnnotateTextResponse, - typing.Awaitable[language_service.AnnotateTextResponse], + Awaitable[language_service.AnnotateTextResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 22f74961..9083013f 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/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.language_v1beta2.types import language_service - from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO @@ -51,7 +48,7 @@ def __init__( self, *, host: str = "language.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -65,7 +62,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 @@ -175,7 +173,7 @@ def __init__( def create_channel( cls, host: str = "language.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, @@ -206,13 +204,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/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 6bccccd9..6b44fe14 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/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.language_v1beta2.types import language_service - from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .grpc import LanguageServiceGrpcTransport @@ -54,7 +51,7 @@ class LanguageServiceGrpcAsyncIOTransport(LanguageServiceTransport): def create_channel( cls, host: str = "language.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, @@ -81,13 +78,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, ) @@ -95,7 +94,7 @@ def __init__( self, *, host: str = "language.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, @@ -109,7 +108,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 @@ -167,7 +167,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/language_v1beta2/types/__init__.py b/google/cloud/language_v1beta2/types/__init__.py index 025cbb98..adb04117 100644 --- a/google/cloud/language_v1beta2/types/__init__.py +++ b/google/cloud/language_v1beta2/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 .language_service import ( AnalyzeEntitiesRequest, AnalyzeEntitiesResponse, diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index adc1113f..631b8fad 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.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 @@ -96,17 +94,13 @@ class Type(proto.Enum): HTML = 2 type_ = proto.Field(proto.ENUM, number=1, enum=Type,) - - content = proto.Field(proto.STRING, number=2, oneof="source") - - gcs_content_uri = proto.Field(proto.STRING, number=3, oneof="source") - - language = proto.Field(proto.STRING, number=4) + content = proto.Field(proto.STRING, number=2, oneof="source",) + gcs_content_uri = proto.Field(proto.STRING, number=3, oneof="source",) + language = proto.Field(proto.STRING, number=4,) class Sentence(proto.Message): r"""Represents a sentence in the input document. - Attributes: text (google.cloud.language_v1beta2.types.TextSpan): The sentence text. @@ -118,7 +112,6 @@ class Sentence(proto.Message): """ text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - sentiment = proto.Field(proto.MESSAGE, number=2, message="Sentiment",) @@ -179,22 +172,16 @@ class Type(proto.Enum): NUMBER = 12 PRICE = 13 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=3) - - salience = proto.Field(proto.FLOAT, number=4) - + metadata = proto.MapField(proto.STRING, proto.STRING, number=3,) + salience = proto.Field(proto.FLOAT, number=4,) mentions = proto.RepeatedField(proto.MESSAGE, number=5, message="EntityMention",) - sentiment = proto.Field(proto.MESSAGE, number=6, message="Sentiment",) class Token(proto.Message): r"""Represents the smallest syntactic building block of the text. - Attributes: text (google.cloud.language_v1beta2.types.TextSpan): The token text. @@ -208,12 +195,9 @@ class Token(proto.Message): """ text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - part_of_speech = proto.Field(proto.MESSAGE, number=2, message="PartOfSpeech",) - dependency_edge = proto.Field(proto.MESSAGE, number=3, message="DependencyEdge",) - - lemma = proto.Field(proto.STRING, number=4) + lemma = proto.Field(proto.STRING, number=4,) class Sentiment(proto.Message): @@ -231,14 +215,12 @@ class Sentiment(proto.Message): sentiment) and 1.0 (positive sentiment). """ - magnitude = proto.Field(proto.FLOAT, number=2) - - score = proto.Field(proto.FLOAT, number=3) + magnitude = proto.Field(proto.FLOAT, number=2,) + score = proto.Field(proto.FLOAT, number=3,) class PartOfSpeech(proto.Message): r"""Represents part of speech information for a token. - Attributes: tag (google.cloud.language_v1beta2.types.PartOfSpeech.Tag): The part of speech tag. @@ -404,33 +386,21 @@ class Voice(proto.Enum): PASSIVE = 3 tag = proto.Field(proto.ENUM, number=1, enum=Tag,) - aspect = proto.Field(proto.ENUM, number=2, enum=Aspect,) - case = proto.Field(proto.ENUM, number=3, enum=Case,) - form = proto.Field(proto.ENUM, number=4, enum=Form,) - gender = proto.Field(proto.ENUM, number=5, enum=Gender,) - mood = proto.Field(proto.ENUM, number=6, enum=Mood,) - number = proto.Field(proto.ENUM, number=7, enum=Number,) - person = proto.Field(proto.ENUM, number=8, enum=Person,) - proper = proto.Field(proto.ENUM, number=9, enum=Proper,) - reciprocity = proto.Field(proto.ENUM, number=10, enum=Reciprocity,) - tense = proto.Field(proto.ENUM, number=11, enum=Tense,) - voice = proto.Field(proto.ENUM, number=12, enum=Voice,) class DependencyEdge(proto.Message): r"""Represents dependency parse tree information for a token. - Attributes: head_token_index (int): Represents the head of this token in the dependency tree. @@ -529,8 +499,7 @@ class Label(proto.Enum): MES = 81 NCOMP = 82 - head_token_index = proto.Field(proto.INT32, number=1) - + head_token_index = proto.Field(proto.INT32, number=1,) label = proto.Field(proto.ENUM, number=2, enum=Label,) @@ -558,15 +527,12 @@ class Type(proto.Enum): COMMON = 2 text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - sentiment = proto.Field(proto.MESSAGE, number=3, message="Sentiment",) class TextSpan(proto.Message): r"""Represents an output piece of text. - Attributes: content (str): The content of the output text. @@ -577,14 +543,12 @@ class TextSpan(proto.Message): specified in the API request. """ - content = proto.Field(proto.STRING, number=1) - - begin_offset = proto.Field(proto.INT32, number=2) + content = proto.Field(proto.STRING, number=1,) + begin_offset = proto.Field(proto.INT32, number=2,) class ClassificationCategory(proto.Message): r"""Represents a category returned from the text classifier. - Attributes: name (str): The name of the category representing the document, from the @@ -596,14 +560,12 @@ class ClassificationCategory(proto.Message): that this category represents the given text. """ - name = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + name = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) class AnalyzeSentimentRequest(proto.Message): r"""The sentiment analysis request message. - Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -614,13 +576,11 @@ class AnalyzeSentimentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeSentimentResponse(proto.Message): r"""The sentiment analysis response message. - Attributes: document_sentiment (google.cloud.language_v1beta2.types.Sentiment): The overall sentiment of the input document. @@ -636,15 +596,12 @@ class AnalyzeSentimentResponse(proto.Message): """ document_sentiment = proto.Field(proto.MESSAGE, number=1, message="Sentiment",) - - language = proto.Field(proto.STRING, number=2) - + language = proto.Field(proto.STRING, number=2,) sentences = proto.RepeatedField(proto.MESSAGE, number=3, message="Sentence",) class AnalyzeEntitySentimentRequest(proto.Message): r"""The entity-level sentiment analysis request message. - Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -654,13 +611,11 @@ class AnalyzeEntitySentimentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeEntitySentimentResponse(proto.Message): r"""The entity-level sentiment analysis response message. - Attributes: entities (Sequence[google.cloud.language_v1beta2.types.Entity]): The recognized entities in the input document @@ -674,13 +629,11 @@ class AnalyzeEntitySentimentResponse(proto.Message): """ entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - - language = proto.Field(proto.STRING, number=2) + language = proto.Field(proto.STRING, number=2,) class AnalyzeEntitiesRequest(proto.Message): r"""The entity analysis request message. - Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -690,13 +643,11 @@ class AnalyzeEntitiesRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeEntitiesResponse(proto.Message): r"""The entity analysis response message. - Attributes: entities (Sequence[google.cloud.language_v1beta2.types.Entity]): The recognized entities in the input @@ -710,13 +661,11 @@ class AnalyzeEntitiesResponse(proto.Message): """ entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - - language = proto.Field(proto.STRING, number=2) + language = proto.Field(proto.STRING, number=2,) class AnalyzeSyntaxRequest(proto.Message): r"""The syntax analysis request message. - Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -726,13 +675,11 @@ class AnalyzeSyntaxRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) class AnalyzeSyntaxResponse(proto.Message): r"""The syntax analysis response message. - Attributes: sentences (Sequence[google.cloud.language_v1beta2.types.Sentence]): Sentences in the input document. @@ -748,15 +695,12 @@ class AnalyzeSyntaxResponse(proto.Message): """ sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - - language = proto.Field(proto.STRING, number=3) + language = proto.Field(proto.STRING, number=3,) class ClassifyTextRequest(proto.Message): r"""The document classification request message. - Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -767,7 +711,6 @@ class ClassifyTextRequest(proto.Message): class ClassifyTextResponse(proto.Message): r"""The document classification response message. - Attributes: categories (Sequence[google.cloud.language_v1beta2.types.ClassificationCategory]): Categories representing the input document. @@ -815,26 +758,19 @@ class Features(proto.Message): taxonomy `__. """ - extract_syntax = proto.Field(proto.BOOL, number=1) - - extract_entities = proto.Field(proto.BOOL, number=2) - - extract_document_sentiment = proto.Field(proto.BOOL, number=3) - - extract_entity_sentiment = proto.Field(proto.BOOL, number=4) - - classify_text = proto.Field(proto.BOOL, number=6) + extract_syntax = proto.Field(proto.BOOL, number=1,) + extract_entities = proto.Field(proto.BOOL, number=2,) + extract_document_sentiment = proto.Field(proto.BOOL, number=3,) + extract_entity_sentiment = proto.Field(proto.BOOL, number=4,) + classify_text = proto.Field(proto.BOOL, number=6,) document = proto.Field(proto.MESSAGE, number=1, message="Document",) - features = proto.Field(proto.MESSAGE, number=2, message=Features,) - encoding_type = proto.Field(proto.ENUM, number=3, enum="EncodingType",) class AnnotateTextResponse(proto.Message): r"""The text annotations response message. - Attributes: sentences (Sequence[google.cloud.language_v1beta2.types.Sentence]): Sentences in the input document. Populated if the user @@ -863,15 +799,10 @@ class AnnotateTextResponse(proto.Message): """ sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - entities = proto.RepeatedField(proto.MESSAGE, number=3, message="Entity",) - document_sentiment = proto.Field(proto.MESSAGE, number=4, message="Sentiment",) - - language = proto.Field(proto.STRING, number=5) - + language = proto.Field(proto.STRING, number=5,) categories = proto.RepeatedField( proto.MESSAGE, number=6, message="ClassificationCategory", ) diff --git a/owlbot.py b/owlbot.py index 191c6a3a..11b0c990 100644 --- a/owlbot.py +++ b/owlbot.py @@ -22,6 +22,13 @@ default_version = "v1" for library in s.get_staging_dirs(default_version): + # Work around generator issue https://github.com/googleapis/gapic-generator-python/issues/902 + s.replace(library / f"google/cloud/language_{library.name}/types/language_service.py", + r"""Represents the input to API methods. + Attributes:""", + r"""Represents the input to API methods.\n + Attributes:""") + s.move(library, excludes=["docs/index.rst", "README.rst", "setup.py"]) s.remove_staging_dirs() diff --git a/scripts/fixup_language_v1_keywords.py b/scripts/fixup_language_v1_keywords.py index 3d84959b..99d05077 100644 --- a/scripts/fixup_language_v1_keywords.py +++ b/scripts/fixup_language_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,13 +39,12 @@ def partition( class languageCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_entities': ('document', 'encoding_type', ), - 'analyze_entity_sentiment': ('document', 'encoding_type', ), - 'analyze_sentiment': ('document', 'encoding_type', ), - 'analyze_syntax': ('document', 'encoding_type', ), - 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', ), - + 'analyze_entities': ('document', 'encoding_type', ), + 'analyze_entity_sentiment': ('document', 'encoding_type', ), + 'analyze_sentiment': ('document', 'encoding_type', ), + 'analyze_syntax': ('document', 'encoding_type', ), + 'annotate_text': ('document', 'features', 'encoding_type', ), + 'classify_text': ('document', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -78,7 +75,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_language_v1beta2_keywords.py b/scripts/fixup_language_v1beta2_keywords.py index 3d84959b..99d05077 100644 --- a/scripts/fixup_language_v1beta2_keywords.py +++ b/scripts/fixup_language_v1beta2_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,13 +39,12 @@ def partition( class languageCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_entities': ('document', 'encoding_type', ), - 'analyze_entity_sentiment': ('document', 'encoding_type', ), - 'analyze_sentiment': ('document', 'encoding_type', ), - 'analyze_syntax': ('document', 'encoding_type', ), - 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', ), - + 'analyze_entities': ('document', 'encoding_type', ), + 'analyze_entity_sentiment': ('document', 'encoding_type', ), + 'analyze_sentiment': ('document', 'encoding_type', ), + 'analyze_syntax': ('document', 'encoding_type', ), + 'annotate_text': ('document', 'features', 'encoding_type', ), + 'classify_text': ('document', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -78,7 +75,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/language_v1/__init__.py b/tests/unit/gapic/language_v1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/language_v1/__init__.py +++ b/tests/unit/gapic/language_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/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index dbcd0244..a41f245d 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.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,21 +23,51 @@ 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.language_v1.services.language_service import ( LanguageServiceAsyncClient, ) from google.cloud.language_v1.services.language_service import LanguageServiceClient from google.cloud.language_v1.services.language_service import transports +from google.cloud.language_v1.services.language_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.language_v1.services.language_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.language_v1.types import language_service from google.oauth2 import service_account +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(): @@ -89,7 +118,7 @@ def test__get_default_mtls_endpoint(): "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] ) def test_language_service_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: @@ -106,7 +135,7 @@ def test_language_service_client_from_service_account_info(client_class): "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] ) def test_language_service_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: @@ -159,7 +188,7 @@ def test_language_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(LanguageServiceClient, "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_analyze_sentiment( transport: str = "grpc", request_type=language_service.AnalyzeSentimentRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -472,19 +501,15 @@ def test_analyze_sentiment( call.return_value = language_service.AnalyzeSentimentResponse( language="language_value", ) - response = client.analyze_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" @@ -496,7 +521,7 @@ def test_analyze_sentiment_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 = LanguageServiceClient( - 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 +531,6 @@ def test_analyze_sentiment_empty_call(): client.analyze_sentiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() @@ -516,7 +540,7 @@ async def test_analyze_sentiment_async( request_type=language_service.AnalyzeSentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -531,18 +555,15 @@ async def test_analyze_sentiment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeSentimentResponse(language="language_value",) ) - response = await client.analyze_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" @@ -552,7 +573,7 @@ async def test_analyze_sentiment_async_from_dict(): def test_analyze_sentiment_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -560,7 +581,6 @@ def test_analyze_sentiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeSentimentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_sentiment( @@ -574,16 +594,14 @@ def test_analyze_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -599,7 +617,9 @@ def test_analyze_sentiment_flattened_error(): @pytest.mark.asyncio async def test_analyze_sentiment_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -624,17 +644,17 @@ async def test_analyze_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -652,7 +672,7 @@ def test_analyze_entities( transport: str = "grpc", request_type=language_service.AnalyzeEntitiesRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -665,19 +685,15 @@ def test_analyze_entities( call.return_value = language_service.AnalyzeEntitiesResponse( language="language_value", ) - response = client.analyze_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" @@ -689,7 +705,7 @@ def test_analyze_entities_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -697,7 +713,6 @@ def test_analyze_entities_empty_call(): client.analyze_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() @@ -707,7 +722,7 @@ async def test_analyze_entities_async( request_type=language_service.AnalyzeEntitiesRequest, ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -720,18 +735,15 @@ async def test_analyze_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeEntitiesResponse(language="language_value",) ) - response = await client.analyze_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" @@ -741,13 +753,12 @@ async def test_analyze_entities_async_from_dict(): def test_analyze_entities_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeEntitiesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_entities( @@ -761,16 +772,14 @@ def test_analyze_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_entities_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -786,7 +795,9 @@ def test_analyze_entities_flattened_error(): @pytest.mark.asyncio async def test_analyze_entities_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: @@ -809,17 +820,17 @@ async def test_analyze_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_entities_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -837,7 +848,7 @@ def test_analyze_entity_sentiment( transport: str = "grpc", request_type=language_service.AnalyzeEntitySentimentRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -852,19 +863,15 @@ def test_analyze_entity_sentiment( call.return_value = language_service.AnalyzeEntitySentimentResponse( language="language_value", ) - response = client.analyze_entity_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" @@ -876,7 +883,7 @@ def test_analyze_entity_sentiment_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -886,7 +893,6 @@ def test_analyze_entity_sentiment_empty_call(): client.analyze_entity_sentiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() @@ -896,7 +902,7 @@ async def test_analyze_entity_sentiment_async( request_type=language_service.AnalyzeEntitySentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -911,18 +917,15 @@ async def test_analyze_entity_sentiment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeEntitySentimentResponse(language="language_value",) ) - response = await client.analyze_entity_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" @@ -932,7 +935,7 @@ async def test_analyze_entity_sentiment_async_from_dict(): def test_analyze_entity_sentiment_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -940,7 +943,6 @@ def test_analyze_entity_sentiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeEntitySentimentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_entity_sentiment( @@ -954,16 +956,14 @@ def test_analyze_entity_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_entity_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -979,7 +979,9 @@ def test_analyze_entity_sentiment_flattened_error(): @pytest.mark.asyncio async def test_analyze_entity_sentiment_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1004,17 +1006,17 @@ async def test_analyze_entity_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_entity_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1032,7 +1034,7 @@ def test_analyze_syntax( transport: str = "grpc", request_type=language_service.AnalyzeSyntaxRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1045,19 +1047,15 @@ def test_analyze_syntax( call.return_value = language_service.AnalyzeSyntaxResponse( language="language_value", ) - response = client.analyze_syntax(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" @@ -1069,7 +1067,7 @@ def test_analyze_syntax_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1077,7 +1075,6 @@ def test_analyze_syntax_empty_call(): client.analyze_syntax() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() @@ -1086,7 +1083,7 @@ async def test_analyze_syntax_async( transport: str = "grpc_asyncio", request_type=language_service.AnalyzeSyntaxRequest ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1099,18 +1096,15 @@ async def test_analyze_syntax_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeSyntaxResponse(language="language_value",) ) - response = await client.analyze_syntax(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" @@ -1120,13 +1114,12 @@ async def test_analyze_syntax_async_from_dict(): def test_analyze_syntax_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeSyntaxResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_syntax( @@ -1140,16 +1133,14 @@ def test_analyze_syntax_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_syntax_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1165,7 +1156,9 @@ def test_analyze_syntax_flattened_error(): @pytest.mark.asyncio async def test_analyze_syntax_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: @@ -1188,17 +1181,17 @@ async def test_analyze_syntax_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_syntax_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1216,7 +1209,7 @@ def test_classify_text( transport: str = "grpc", request_type=language_service.ClassifyTextRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1227,17 +1220,14 @@ def test_classify_text( with mock.patch.object(type(client.transport.classify_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.ClassifyTextResponse() - response = client.classify_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) @@ -1249,7 +1239,7 @@ def test_classify_text_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1257,7 +1247,6 @@ def test_classify_text_empty_call(): client.classify_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() @@ -1266,7 +1255,7 @@ async def test_classify_text_async( transport: str = "grpc_asyncio", request_type=language_service.ClassifyTextRequest ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1279,13 +1268,11 @@ async def test_classify_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.ClassifyTextResponse() ) - response = await client.classify_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() # Establish that the response is the type that we expect. @@ -1298,13 +1285,12 @@ async def test_classify_text_async_from_dict(): def test_classify_text_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.classify_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.ClassifyTextResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.classify_text( @@ -1317,14 +1303,13 @@ def test_classify_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) def test_classify_text_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1339,7 +1324,9 @@ def test_classify_text_flattened_error(): @pytest.mark.asyncio async def test_classify_text_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.classify_text), "__call__") as call: @@ -1361,7 +1348,6 @@ async def test_classify_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) @@ -1369,7 +1355,9 @@ async def test_classify_text_flattened_async(): @pytest.mark.asyncio async def test_classify_text_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1386,7 +1374,7 @@ def test_annotate_text( transport: str = "grpc", request_type=language_service.AnnotateTextRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1399,19 +1387,15 @@ def test_annotate_text( call.return_value = language_service.AnnotateTextResponse( language="language_value", ) - response = client.annotate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" @@ -1423,7 +1407,7 @@ def test_annotate_text_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1431,7 +1415,6 @@ def test_annotate_text_empty_call(): client.annotate_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() @@ -1440,7 +1423,7 @@ async def test_annotate_text_async( transport: str = "grpc_asyncio", request_type=language_service.AnnotateTextRequest ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1453,18 +1436,15 @@ async def test_annotate_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnnotateTextResponse(language="language_value",) ) - response = await client.annotate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" @@ -1474,13 +1454,12 @@ async def test_annotate_text_async_from_dict(): def test_annotate_text_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnnotateTextResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.annotate_text( @@ -1495,20 +1474,17 @@ def test_annotate_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( extract_syntax=True ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_annotate_text_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1525,7 +1501,9 @@ def test_annotate_text_flattened_error(): @pytest.mark.asyncio async def test_annotate_text_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: @@ -1549,21 +1527,20 @@ async def test_annotate_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( extract_syntax=True ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_annotate_text_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1581,16 +1558,16 @@ async def test_annotate_text_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LanguageServiceClient( - 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.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LanguageServiceClient( @@ -1600,7 +1577,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LanguageServiceClient( @@ -1611,7 +1588,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = LanguageServiceClient(transport=transport) assert client.transport is transport @@ -1620,13 +1597,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.LanguageServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1641,23 +1618,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 = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.LanguageServiceGrpcTransport,) def test_language_service_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.LanguageServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1669,7 +1646,7 @@ def test_language_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.LanguageServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1687,15 +1664,40 @@ def test_language_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_language_service_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.language_v1.services.language_service.transports.LanguageServiceTransport._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.LanguageServiceTransport( + 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-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_language_service_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.language_v1.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LanguageServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1711,19 +1713,36 @@ def test_language_service_base_transport_with_credentials_file(): def test_language_service_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.language_v1.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LanguageServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_language_service_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) + LanguageServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_language_service_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) LanguageServiceClient() adc.assert_called_once_with( scopes=( @@ -1734,14 +1753,44 @@ def test_language_service_auth_adc(): ) -def test_language_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_language_service_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.LanguageServiceGrpcTransport( - 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-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_language_service_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-language", @@ -1751,6 +1800,121 @@ def test_language_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LanguageServiceGrpcTransport, grpc_helpers), + (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_language_service_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( + "language.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="language.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.LanguageServiceGrpcTransport, grpc_helpers), + (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_language_service_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( + "language.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LanguageServiceGrpcTransport, grpc_helpers), + (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_language_service_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( + "language.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", [ @@ -1759,7 +1923,7 @@ def test_language_service_transport_auth_adc(): ], ) def test_language_service_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: @@ -1801,7 +1965,7 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c def test_language_service_host_no_port(): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com" ), @@ -1811,7 +1975,7 @@ def test_language_service_host_no_port(): def test_language_service_host_with_port(): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com:8000" ), @@ -1867,9 +2031,9 @@ def test_language_service_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", @@ -1951,7 +2115,6 @@ def test_language_service_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, ) @@ -1972,7 +2135,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = LanguageServiceClient.common_folder_path(folder) assert expected == actual @@ -1991,7 +2153,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = LanguageServiceClient.common_organization_path(organization) assert expected == actual @@ -2010,7 +2171,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = LanguageServiceClient.common_project_path(project) assert expected == actual @@ -2030,7 +2190,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, ) @@ -2057,7 +2216,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.LanguageServiceTransport, "_prep_wrapped_messages" ) as prep: client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2066,6 +2225,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = LanguageServiceClient.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/language_v1beta2/__init__.py b/tests/unit/gapic/language_v1beta2/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/language_v1beta2/__init__.py +++ b/tests/unit/gapic/language_v1beta2/__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/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index ab2cc3d6..17d28b09 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.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,13 +23,13 @@ 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.language_v1beta2.services.language_service import ( LanguageServiceAsyncClient, @@ -39,8 +38,38 @@ LanguageServiceClient, ) from google.cloud.language_v1beta2.services.language_service import transports +from google.cloud.language_v1beta2.services.language_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.language_v1beta2.services.language_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.language_v1beta2.types import language_service from google.oauth2 import service_account +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(): @@ -91,7 +120,7 @@ def test__get_default_mtls_endpoint(): "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] ) def test_language_service_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: @@ -108,7 +137,7 @@ def test_language_service_client_from_service_account_info(client_class): "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] ) def test_language_service_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: @@ -161,7 +190,7 @@ def test_language_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(LanguageServiceClient, "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() @@ -459,7 +488,7 @@ def test_analyze_sentiment( transport: str = "grpc", request_type=language_service.AnalyzeSentimentRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -474,19 +503,15 @@ def test_analyze_sentiment( call.return_value = language_service.AnalyzeSentimentResponse( language="language_value", ) - response = client.analyze_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" @@ -498,7 +523,7 @@ def test_analyze_sentiment_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 = LanguageServiceClient( - 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 +533,6 @@ def test_analyze_sentiment_empty_call(): client.analyze_sentiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() @@ -518,7 +542,7 @@ async def test_analyze_sentiment_async( request_type=language_service.AnalyzeSentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -533,18 +557,15 @@ async def test_analyze_sentiment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeSentimentResponse(language="language_value",) ) - response = await client.analyze_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" @@ -554,7 +575,7 @@ async def test_analyze_sentiment_async_from_dict(): def test_analyze_sentiment_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -562,7 +583,6 @@ def test_analyze_sentiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeSentimentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_sentiment( @@ -576,16 +596,14 @@ def test_analyze_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -601,7 +619,9 @@ def test_analyze_sentiment_flattened_error(): @pytest.mark.asyncio async def test_analyze_sentiment_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -626,17 +646,17 @@ async def test_analyze_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -654,7 +674,7 @@ def test_analyze_entities( transport: str = "grpc", request_type=language_service.AnalyzeEntitiesRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -667,19 +687,15 @@ def test_analyze_entities( call.return_value = language_service.AnalyzeEntitiesResponse( language="language_value", ) - response = client.analyze_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" @@ -691,7 +707,7 @@ def test_analyze_entities_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -699,7 +715,6 @@ def test_analyze_entities_empty_call(): client.analyze_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() @@ -709,7 +724,7 @@ async def test_analyze_entities_async( request_type=language_service.AnalyzeEntitiesRequest, ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -722,18 +737,15 @@ async def test_analyze_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeEntitiesResponse(language="language_value",) ) - response = await client.analyze_entities(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" @@ -743,13 +755,12 @@ async def test_analyze_entities_async_from_dict(): def test_analyze_entities_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeEntitiesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_entities( @@ -763,16 +774,14 @@ def test_analyze_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_entities_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -788,7 +797,9 @@ def test_analyze_entities_flattened_error(): @pytest.mark.asyncio async def test_analyze_entities_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: @@ -811,17 +822,17 @@ async def test_analyze_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_entities_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -839,7 +850,7 @@ def test_analyze_entity_sentiment( transport: str = "grpc", request_type=language_service.AnalyzeEntitySentimentRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -854,19 +865,15 @@ def test_analyze_entity_sentiment( call.return_value = language_service.AnalyzeEntitySentimentResponse( language="language_value", ) - response = client.analyze_entity_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" @@ -878,7 +885,7 @@ def test_analyze_entity_sentiment_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -888,7 +895,6 @@ def test_analyze_entity_sentiment_empty_call(): client.analyze_entity_sentiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() @@ -898,7 +904,7 @@ async def test_analyze_entity_sentiment_async( request_type=language_service.AnalyzeEntitySentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -913,18 +919,15 @@ async def test_analyze_entity_sentiment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeEntitySentimentResponse(language="language_value",) ) - response = await client.analyze_entity_sentiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" @@ -934,7 +937,7 @@ async def test_analyze_entity_sentiment_async_from_dict(): def test_analyze_entity_sentiment_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -942,7 +945,6 @@ def test_analyze_entity_sentiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeEntitySentimentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_entity_sentiment( @@ -956,16 +958,14 @@ def test_analyze_entity_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_entity_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -981,7 +981,9 @@ def test_analyze_entity_sentiment_flattened_error(): @pytest.mark.asyncio async def test_analyze_entity_sentiment_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1006,17 +1008,17 @@ async def test_analyze_entity_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_entity_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1034,7 +1036,7 @@ def test_analyze_syntax( transport: str = "grpc", request_type=language_service.AnalyzeSyntaxRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1047,19 +1049,15 @@ def test_analyze_syntax( call.return_value = language_service.AnalyzeSyntaxResponse( language="language_value", ) - response = client.analyze_syntax(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" @@ -1071,7 +1069,7 @@ def test_analyze_syntax_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1079,7 +1077,6 @@ def test_analyze_syntax_empty_call(): client.analyze_syntax() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() @@ -1088,7 +1085,7 @@ async def test_analyze_syntax_async( transport: str = "grpc_asyncio", request_type=language_service.AnalyzeSyntaxRequest ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1101,18 +1098,15 @@ async def test_analyze_syntax_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnalyzeSyntaxResponse(language="language_value",) ) - response = await client.analyze_syntax(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" @@ -1122,13 +1116,12 @@ async def test_analyze_syntax_async_from_dict(): def test_analyze_syntax_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnalyzeSyntaxResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_syntax( @@ -1142,16 +1135,14 @@ def test_analyze_syntax_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_analyze_syntax_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1167,7 +1158,9 @@ def test_analyze_syntax_flattened_error(): @pytest.mark.asyncio async def test_analyze_syntax_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: @@ -1190,17 +1183,17 @@ async def test_analyze_syntax_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_analyze_syntax_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1218,7 +1211,7 @@ def test_classify_text( transport: str = "grpc", request_type=language_service.ClassifyTextRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1229,17 +1222,14 @@ def test_classify_text( with mock.patch.object(type(client.transport.classify_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.ClassifyTextResponse() - response = client.classify_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) @@ -1251,7 +1241,7 @@ def test_classify_text_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1259,7 +1249,6 @@ def test_classify_text_empty_call(): client.classify_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() @@ -1268,7 +1257,7 @@ async def test_classify_text_async( transport: str = "grpc_asyncio", request_type=language_service.ClassifyTextRequest ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1281,13 +1270,11 @@ async def test_classify_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.ClassifyTextResponse() ) - response = await client.classify_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() # Establish that the response is the type that we expect. @@ -1300,13 +1287,12 @@ async def test_classify_text_async_from_dict(): def test_classify_text_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.classify_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.ClassifyTextResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.classify_text( @@ -1319,14 +1305,13 @@ def test_classify_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) def test_classify_text_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1341,7 +1326,9 @@ def test_classify_text_flattened_error(): @pytest.mark.asyncio async def test_classify_text_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.classify_text), "__call__") as call: @@ -1363,7 +1350,6 @@ async def test_classify_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) @@ -1371,7 +1357,9 @@ async def test_classify_text_flattened_async(): @pytest.mark.asyncio async def test_classify_text_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1388,7 +1376,7 @@ def test_annotate_text( transport: str = "grpc", request_type=language_service.AnnotateTextRequest ): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1401,19 +1389,15 @@ def test_annotate_text( call.return_value = language_service.AnnotateTextResponse( language="language_value", ) - response = client.annotate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" @@ -1425,7 +1409,7 @@ def test_annotate_text_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 = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1433,7 +1417,6 @@ def test_annotate_text_empty_call(): client.annotate_text() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() @@ -1442,7 +1425,7 @@ async def test_annotate_text_async( transport: str = "grpc_asyncio", request_type=language_service.AnnotateTextRequest ): client = LanguageServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1455,18 +1438,15 @@ async def test_annotate_text_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( language_service.AnnotateTextResponse(language="language_value",) ) - response = await client.annotate_text(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() # Establish that the response is the type that we expect. assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" @@ -1476,13 +1456,12 @@ async def test_annotate_text_async_from_dict(): def test_annotate_text_flattened(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = language_service.AnnotateTextResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.annotate_text( @@ -1497,20 +1476,17 @@ def test_annotate_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( extract_syntax=True ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 def test_annotate_text_flattened_error(): - client = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1527,7 +1503,9 @@ def test_annotate_text_flattened_error(): @pytest.mark.asyncio async def test_annotate_text_flattened_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: @@ -1551,21 +1529,20 @@ async def test_annotate_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( extract_syntax=True ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 @pytest.mark.asyncio async def test_annotate_text_flattened_error_async(): - client = LanguageServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1583,16 +1560,16 @@ async def test_annotate_text_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LanguageServiceClient( - 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.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LanguageServiceClient( @@ -1602,7 +1579,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LanguageServiceClient( @@ -1613,7 +1590,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = LanguageServiceClient(transport=transport) assert client.transport is transport @@ -1622,13 +1599,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.LanguageServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.LanguageServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1643,23 +1620,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 = LanguageServiceClient(credentials=credentials.AnonymousCredentials(),) + client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.LanguageServiceGrpcTransport,) def test_language_service_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.LanguageServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1671,7 +1648,7 @@ def test_language_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.LanguageServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1689,15 +1666,40 @@ def test_language_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_language_service_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.language_v1beta2.services.language_service.transports.LanguageServiceTransport._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.LanguageServiceTransport( + 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-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_language_service_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.language_v1beta2.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LanguageServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1713,19 +1715,36 @@ def test_language_service_base_transport_with_credentials_file(): def test_language_service_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.language_v1beta2.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LanguageServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_language_service_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) + LanguageServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_language_service_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) LanguageServiceClient() adc.assert_called_once_with( scopes=( @@ -1736,14 +1755,44 @@ def test_language_service_auth_adc(): ) -def test_language_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_language_service_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.LanguageServiceGrpcTransport( - 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-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_language_service_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-language", @@ -1753,6 +1802,121 @@ def test_language_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LanguageServiceGrpcTransport, grpc_helpers), + (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_language_service_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( + "language.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="language.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.LanguageServiceGrpcTransport, grpc_helpers), + (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_language_service_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( + "language.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.LanguageServiceGrpcTransport, grpc_helpers), + (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_language_service_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( + "language.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", [ @@ -1761,7 +1925,7 @@ def test_language_service_transport_auth_adc(): ], ) def test_language_service_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: @@ -1803,7 +1967,7 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c def test_language_service_host_no_port(): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com" ), @@ -1813,7 +1977,7 @@ def test_language_service_host_no_port(): def test_language_service_host_with_port(): client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com:8000" ), @@ -1869,9 +2033,9 @@ def test_language_service_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", @@ -1953,7 +2117,6 @@ def test_language_service_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, ) @@ -1974,7 +2137,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = LanguageServiceClient.common_folder_path(folder) assert expected == actual @@ -1993,7 +2155,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = LanguageServiceClient.common_organization_path(organization) assert expected == actual @@ -2012,7 +2173,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = LanguageServiceClient.common_project_path(project) assert expected == actual @@ -2032,7 +2192,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, ) @@ -2059,7 +2218,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.LanguageServiceTransport, "_prep_wrapped_messages" ) as prep: client = LanguageServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2068,6 +2227,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = LanguageServiceClient.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) From c5fc118972c6cf2aed7682f3ccbc95e4be3f7fa1 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 20 May 2021 19:38:02 +0200 Subject: [PATCH 006/254] chore(deps): update dependency google-auth-httplib2 to v0.1.0 (#80) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-auth-httplib2](https://togithub.com/GoogleCloudPlatform/google-auth-library-python-httplib2) | `==0.0.4` -> `==0.1.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-auth-httplib2/0.1.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-auth-httplib2/0.1.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-auth-httplib2/0.1.0/compatibility-slim/0.0.4)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-auth-httplib2/0.1.0/confidence-slim/0.0.4)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
GoogleCloudPlatform/google-auth-library-python-httplib2 ### [`v0.1.0`](https://togithub.com/GoogleCloudPlatform/google-auth-library-python-httplib2/blob/master/CHANGELOG.md#​010-httpswwwgithubcomgoogleapisgoogle-auth-library-python-httplib2comparev003v010-2021-03-01) [Compare Source](https://togithub.com/GoogleCloudPlatform/google-auth-library-python-httplib2/compare/v0.0.4...v0.1.0) ##### Features - add close method ([#​14](https://www.github.com/googleapis/google-auth-library-python-httplib2/issues/14)) ([feda187](https://www.github.com/googleapis/google-auth-library-python-httplib2/commit/feda187133beeb656fdd7f30ed124ed1e428a74a)) - expose a few httplib2 properties and a method ([#​9](https://www.github.com/googleapis/google-auth-library-python-httplib2/issues/9)) ([e3aa44e](https://www.github.com/googleapis/google-auth-library-python-httplib2/commit/e3aa44e01e2987989671467c7a022ea33829eb2f))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻️ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 98df063b..4574239f 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==1.12.8 google-auth==1.27.0 -google-auth-httplib2==0.0.4 +google-auth-httplib2==0.1.0 From ff0e6d7fa2bd10faf0e207b2ff07e8c88c2ebd3c Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 20 May 2021 19:40:02 +0200 Subject: [PATCH 007/254] chore(deps): update dependency pytest to v6.2.4 (#97) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [pytest](https://docs.pytest.org/en/latest/) ([source](https://togithub.com/pytest-dev/pytest), [changelog](https://docs.pytest.org/en/stable/changelog.html)) | `==6.0.1` -> `==6.2.4` | [![age](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/compatibility-slim/6.0.1)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/confidence-slim/6.0.1)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
pytest-dev/pytest ### [`v6.2.4`](https://togithub.com/pytest-dev/pytest/releases/6.2.4) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.3...6.2.4) # pytest 6.2.4 (2021-05-04) ## Bug Fixes - [#​8539](https://togithub.com/pytest-dev/pytest/issues/8539): Fixed assertion rewriting on Python 3.10. ### [`v6.2.3`](https://togithub.com/pytest-dev/pytest/releases/6.2.3) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.2...6.2.3) # pytest 6.2.3 (2021-04-03) ## Bug Fixes - [#​8414](https://togithub.com/pytest-dev/pytest/issues/8414): pytest used to create directories under `/tmp` with world-readable permissions. This means that any user in the system was able to read information written by tests in temporary directories (such as those created by the `tmp_path`/`tmpdir` fixture). Now the directories are created with private permissions. pytest used silenty use a pre-existing `/tmp/pytest-of-` directory, even if owned by another user. This means another user could pre-create such a directory and gain control of another user\\'s temporary directory. Now such a condition results in an error. ### [`v6.2.2`](https://togithub.com/pytest-dev/pytest/releases/6.2.2) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.1...6.2.2) # pytest 6.2.2 (2021-01-25) ## Bug Fixes - [#​8152](https://togithub.com/pytest-dev/pytest/issues/8152): Fixed "(<Skipped instance>)" being shown as a skip reason in the verbose test summary line when the reason is empty. - [#​8249](https://togithub.com/pytest-dev/pytest/issues/8249): Fix the `faulthandler` plugin for occasions when running with `twisted.logger` and using `pytest --capture=no`. ### [`v6.2.1`](https://togithub.com/pytest-dev/pytest/releases/6.2.1) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.0...6.2.1) # pytest 6.2.1 (2020-12-15) ## Bug Fixes - [#​7678](https://togithub.com/pytest-dev/pytest/issues/7678): Fixed bug where `ImportPathMismatchError` would be raised for files compiled in the host and loaded later from an UNC mounted path (Windows). - [#​8132](https://togithub.com/pytest-dev/pytest/issues/8132): Fixed regression in `approx`: in 6.2.0 `approx` no longer raises `TypeError` when dealing with non-numeric types, falling back to normal comparison. Before 6.2.0, array types like tf.DeviceArray fell through to the scalar case, and happened to compare correctly to a scalar if they had only one element. After 6.2.0, these types began failing, because they inherited neither from standard Python number hierarchy nor from `numpy.ndarray`. `approx` now converts arguments to `numpy.ndarray` if they expose the array protocol and are not scalars. This treats array-like objects like numpy arrays, regardless of size. ### [`v6.2.0`](https://togithub.com/pytest-dev/pytest/releases/6.2.0) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.1.2...6.2.0) # pytest 6.2.0 (2020-12-12) ## Breaking Changes - [#​7808](https://togithub.com/pytest-dev/pytest/issues/7808): pytest now supports python3.6+ only. ## Deprecations - [#​7469](https://togithub.com/pytest-dev/pytest/issues/7469): Directly constructing/calling the following classes/functions is now deprecated: - `_pytest.cacheprovider.Cache` - `_pytest.cacheprovider.Cache.for_config()` - `_pytest.cacheprovider.Cache.clear_cache()` - `_pytest.cacheprovider.Cache.cache_dir_from_config()` - `_pytest.capture.CaptureFixture` - `_pytest.fixtures.FixtureRequest` - `_pytest.fixtures.SubRequest` - `_pytest.logging.LogCaptureFixture` - `_pytest.pytester.Pytester` - `_pytest.pytester.Testdir` - `_pytest.recwarn.WarningsRecorder` - `_pytest.recwarn.WarningsChecker` - `_pytest.tmpdir.TempPathFactory` - `_pytest.tmpdir.TempdirFactory` These have always been considered private, but now issue a deprecation warning, which may become a hard error in pytest 7.0.0. - [#​7530](https://togithub.com/pytest-dev/pytest/issues/7530): The `--strict` command-line option has been deprecated, use `--strict-markers` instead. We have plans to maybe in the future to reintroduce `--strict` and make it an encompassing flag for all strictness related options (`--strict-markers` and `--strict-config` at the moment, more might be introduced in the future). - [#​7988](https://togithub.com/pytest-dev/pytest/issues/7988): The `@pytest.yield_fixture` decorator/function is now deprecated. Use pytest.fixture instead. `yield_fixture` has been an alias for `fixture` for a very long time, so can be search/replaced safely. ## Features - [#​5299](https://togithub.com/pytest-dev/pytest/issues/5299): pytest now warns about unraisable exceptions and unhandled thread exceptions that occur in tests on Python>=3.8. See unraisable for more information. - [#​7425](https://togithub.com/pytest-dev/pytest/issues/7425): New pytester fixture, which is identical to testdir but its methods return pathlib.Path when appropriate instead of `py.path.local`. This is part of the movement to use pathlib.Path objects internally, in order to remove the dependency to `py` in the future. Internally, the old Testdir <\_pytest.pytester.Testdir> is now a thin wrapper around Pytester <\_pytest.pytester.Pytester>, preserving the old interface. - [#​7695](https://togithub.com/pytest-dev/pytest/issues/7695): A new hook was added, pytest_markeval_namespace which should return a dictionary. This dictionary will be used to augment the "global" variables available to evaluate skipif/xfail/xpass markers. Pseudo example `conftest.py`: ```{.sourceCode .python} def pytest_markeval_namespace(): return {"color": "red"} ``` `test_func.py`: ```{.sourceCode .python} @​pytest.mark.skipif("color == 'blue'", reason="Color is not red") def test_func(): assert False ``` - [#​8006](https://togithub.com/pytest-dev/pytest/issues/8006): It is now possible to construct a ~pytest.MonkeyPatch object directly as `pytest.MonkeyPatch()`, in cases when the monkeypatch fixture cannot be used. Previously some users imported it from the private \_pytest.monkeypatch.MonkeyPatch namespace. Additionally, MonkeyPatch.context <pytest.MonkeyPatch.context> is now a classmethod, and can be used as `with MonkeyPatch.context() as mp: ...`. This is the recommended way to use `MonkeyPatch` directly, since unlike the `monkeypatch` fixture, an instance created directly is not `undo()`-ed automatically. ## Improvements - [#​1265](https://togithub.com/pytest-dev/pytest/issues/1265): Added an `__str__` implementation to the ~pytest.pytester.LineMatcher class which is returned from `pytester.run_pytest().stdout` and similar. It returns the entire output, like the existing `str()` method. - [#​2044](https://togithub.com/pytest-dev/pytest/issues/2044): Verbose mode now shows the reason that a test was skipped in the test's terminal line after the "SKIPPED", "XFAIL" or "XPASS". - [#​7469](https://togithub.com/pytest-dev/pytest/issues/7469) The types of builtin pytest fixtures are now exported so they may be used in type annotations of test functions. The newly-exported types are: - `pytest.FixtureRequest` for the request fixture. - `pytest.Cache` for the cache fixture. - `pytest.CaptureFixture[str]` for the capfd and capsys fixtures. - `pytest.CaptureFixture[bytes]` for the capfdbinary and capsysbinary fixtures. - `pytest.LogCaptureFixture` for the caplog fixture. - `pytest.Pytester` for the pytester fixture. - `pytest.Testdir` for the testdir fixture. - `pytest.TempdirFactory` for the tmpdir_factory fixture. - `pytest.TempPathFactory` for the tmp_path_factory fixture. - `pytest.MonkeyPatch` for the monkeypatch fixture. - `pytest.WarningsRecorder` for the recwarn fixture. Constructing them is not supported (except for MonkeyPatch); they are only meant for use in type annotations. Doing so will emit a deprecation warning, and may become a hard-error in pytest 7.0. Subclassing them is also not supported. This is not currently enforced at runtime, but is detected by type-checkers such as mypy. - [#​7527](https://togithub.com/pytest-dev/pytest/issues/7527): When a comparison between namedtuple <collections.namedtuple> instances of the same type fails, pytest now shows the differing field names (possibly nested) instead of their indexes. - [#​7615](https://togithub.com/pytest-dev/pytest/issues/7615): Node.warn <\_pytest.nodes.Node.warn> now permits any subclass of Warning, not just PytestWarning <pytest.PytestWarning>. - [#​7701](https://togithub.com/pytest-dev/pytest/issues/7701): Improved reporting when using `--collected-only`. It will now show the number of collected tests in the summary stats. - [#​7710](https://togithub.com/pytest-dev/pytest/issues/7710): Use strict equality comparison for non-numeric types in pytest.approx instead of raising TypeError. This was the undocumented behavior before 3.7, but is now officially a supported feature. - [#​7938](https://togithub.com/pytest-dev/pytest/issues/7938): New `--sw-skip` argument which is a shorthand for `--stepwise-skip`. - [#​8023](https://togithub.com/pytest-dev/pytest/issues/8023): Added `'node_modules'` to default value for norecursedirs. - [#​8032](https://togithub.com/pytest-dev/pytest/issues/8032): doClassCleanups <unittest.TestCase.doClassCleanups> (introduced in unittest in Python and 3.8) is now called appropriately. ## Bug Fixes - [#​4824](https://togithub.com/pytest-dev/pytest/issues/4824): Fixed quadratic behavior and improved performance of collection of items using autouse fixtures and xunit fixtures. - [#​7758](https://togithub.com/pytest-dev/pytest/issues/7758): Fixed an issue where some files in packages are getting lost from `--lf` even though they contain tests that failed. Regressed in pytest 5.4.0. - [#​7911](https://togithub.com/pytest-dev/pytest/issues/7911): Directories created by by tmp_path and tmpdir are now considered stale after 3 days without modification (previous value was 3 hours) to avoid deleting directories still in use in long running test suites. - [#​7913](https://togithub.com/pytest-dev/pytest/issues/7913): Fixed a crash or hang in pytester.spawn <\_pytest.pytester.Pytester.spawn> when the readline module is involved. - [#​7951](https://togithub.com/pytest-dev/pytest/issues/7951): Fixed handling of recursive symlinks when collecting tests. - [#​7981](https://togithub.com/pytest-dev/pytest/issues/7981): Fixed symlinked directories not being followed during collection. Regressed in pytest 6.1.0. - [#​8016](https://togithub.com/pytest-dev/pytest/issues/8016): Fixed only one doctest being collected when using `pytest --doctest-modules path/to/an/__init__.py`. ## Improved Documentation - [#​7429](https://togithub.com/pytest-dev/pytest/issues/7429): Add more information and use cases about skipping doctests. - [#​7780](https://togithub.com/pytest-dev/pytest/issues/7780): Classes which should not be inherited from are now marked `final class` in the API reference. - [#​7872](https://togithub.com/pytest-dev/pytest/issues/7872): `_pytest.config.argparsing.Parser.addini()` accepts explicit `None` and `"string"`. - [#​7878](https://togithub.com/pytest-dev/pytest/issues/7878): In pull request section, ask to commit after editing changelog and authors file. ## Trivial/Internal Changes - [#​7802](https://togithub.com/pytest-dev/pytest/issues/7802): The `attrs` dependency requirement is now >=19.2.0 instead of >=17.4.0. - [#​8014](https://togithub.com/pytest-dev/pytest/issues/8014): .pyc files created by pytest's assertion rewriting now conform to the newer PEP-552 format on Python>=3.7. (These files are internal and only interpreted by pytest itself.) ### [`v6.1.2`](https://togithub.com/pytest-dev/pytest/releases/6.1.2) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.1.1...6.1.2) # pytest 6.1.2 (2020-10-28) ## Bug Fixes - [#​7758](https://togithub.com/pytest-dev/pytest/issues/7758): Fixed an issue where some files in packages are getting lost from `--lf` even though they contain tests that failed. Regressed in pytest 5.4.0. - [#​7911](https://togithub.com/pytest-dev/pytest/issues/7911): Directories created by tmpdir are now considered stale after 3 days without modification (previous value was 3 hours) to avoid deleting directories still in use in long running test suites. ## Improved Documentation - [#​7815](https://togithub.com/pytest-dev/pytest/issues/7815): Improve deprecation warning message for `pytest._fillfuncargs()`. ### [`v6.1.1`](https://togithub.com/pytest-dev/pytest/releases/6.1.1) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.1.0...6.1.1) # pytest 6.1.1 (2020-10-03) ## Bug Fixes - [#​7807](https://togithub.com/pytest-dev/pytest/issues/7807): Fixed regression in pytest 6.1.0 causing incorrect rootdir to be determined in some non-trivial cases where parent directories have config files as well. - [#​7814](https://togithub.com/pytest-dev/pytest/issues/7814): Fixed crash in header reporting when testpaths is used and contains absolute paths (regression in 6.1.0). ### [`v6.1.0`](https://togithub.com/pytest-dev/pytest/releases/6.1.0) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.0.2...6.1.0) # pytest 6.1.0 (2020-09-26) ## Breaking Changes - [#​5585](https://togithub.com/pytest-dev/pytest/issues/5585): As per our policy, the following features which have been deprecated in the 5.X series are now removed: - The `funcargnames` read-only property of `FixtureRequest`, `Metafunc`, and `Function` classes. Use `fixturenames` attribute. - `@pytest.fixture` no longer supports positional arguments, pass all arguments by keyword instead. - Direct construction of `Node` subclasses now raise an error, use `from_parent` instead. - The default value for `junit_family` has changed to `xunit2`. If you require the old format, add `junit_family=xunit1` to your configuration file. - The `TerminalReporter` no longer has a `writer` attribute. Plugin authors may use the public functions of the `TerminalReporter` instead of accessing the `TerminalWriter` object directly. - The `--result-log` option has been removed. Users are recommended to use the [pytest-reportlog](https://togithub.com/pytest-dev/pytest-reportlog) plugin instead. For more information consult [Deprecations and Removals](https://docs.pytest.org/en/stable/deprecations.html) in the docs. ## Deprecations - [#​6981](https://togithub.com/pytest-dev/pytest/issues/6981): The `pytest.collect` module is deprecated: all its names can be imported from `pytest` directly. - [#​7097](https://togithub.com/pytest-dev/pytest/issues/7097): The `pytest._fillfuncargs` function is deprecated. This function was kept for backward compatibility with an older plugin. It's functionality is not meant to be used directly, but if you must replace it, use function.\_request.\_fillfixtures() instead, though note this is not a public API and may break in the future. - [#​7210](https://togithub.com/pytest-dev/pytest/issues/7210): The special `-k '-expr'` syntax to `-k` is deprecated. Use `-k 'not expr'` instead. The special `-k 'expr:'` syntax to `-k` is deprecated. Please open an issue if you use this and want a replacement. - [#​7255](https://togithub.com/pytest-dev/pytest/issues/7255): The pytest_warning_captured <\_pytest.hookspec.pytest_warning_captured> hook is deprecated in favor of pytest_warning_recorded <\_pytest.hookspec.pytest_warning_recorded>, and will be removed in a future version. - [#​7648](https://togithub.com/pytest-dev/pytest/issues/7648): The `gethookproxy()` and `isinitpath()` methods of `FSCollector` and `Package` are deprecated; use `self.session.gethookproxy()` and `self.session.isinitpath()` instead. This should work on all pytest versions. ## Features - [#​7667](https://togithub.com/pytest-dev/pytest/issues/7667): New `--durations-min` command-line flag controls the minimal duration for inclusion in the slowest list of tests shown by `--durations`. Previously this was hard-coded to `0.005s`. ## Improvements - [#​6681](https://togithub.com/pytest-dev/pytest/issues/6681): Internal pytest warnings issued during the early stages of initialization are now properly handled and can filtered through filterwarnings or `--pythonwarnings/-W`. This also fixes a number of long standing issues: [#​2891](https://togithub.com/pytest-dev/pytest/issues/2891), [#​7620](https://togithub.com/pytest-dev/pytest/issues/7620), [#​7426](https://togithub.com/pytest-dev/pytest/issues/7426). - [#​7572](https://togithub.com/pytest-dev/pytest/issues/7572): When a plugin listed in `required_plugins` is missing or an unknown config key is used with `--strict-config`, a simple error message is now shown instead of a stacktrace. - [#​7685](https://togithub.com/pytest-dev/pytest/issues/7685): Added two new attributes rootpath <\_pytest.config.Config.rootpath> and inipath <\_pytest.config.Config.inipath> to Config <\_pytest.config.Config>. These attributes are pathlib.Path versions of the existing rootdir <\_pytest.config.Config.rootdir> and inifile <\_pytest.config.Config.inifile> attributes, and should be preferred over them when possible. - [#​7780](https://togithub.com/pytest-dev/pytest/issues/7780): Public classes which are not designed to be inherited from are now marked [@​final](https://docs.python.org/3/library/typing.html#typing.final). Code which inherits from these classes will trigger a type-checking (e.g. mypy) error, but will still work in runtime. Currently the `final` designation does not appear in the API Reference but hopefully will in the future. ## Bug Fixes - [#​1953](https://togithub.com/pytest-dev/pytest/issues/1953): Fixed error when overwriting a parametrized fixture, while also reusing the super fixture value. ```{.sourceCode .python} ``` ### conftest.py import pytest @​pytest.fixture(params=[1, 2]) def foo(request): return request.param ### test_foo.py import pytest @​pytest.fixture def foo(foo): return foo * 2 ``` - [#​4984](https://togithub.com/pytest-dev/pytest/issues/4984): Fixed an internal error crash with `IndexError: list index out of range` when collecting a module which starts with a decorated function, the decorator raises, and assertion rewriting is enabled. - [#​7591](https://togithub.com/pytest-dev/pytest/issues/7591): pylint shouldn't complain anymore about unimplemented abstract methods when inheriting from File <non-python tests>. - [#​7628](https://togithub.com/pytest-dev/pytest/issues/7628): Fixed test collection when a full path without a drive letter was passed to pytest on Windows (for example `\projects\tests\test.py` instead of `c:\projects\tests\pytest.py`). - [#​7638](https://togithub.com/pytest-dev/pytest/issues/7638): Fix handling of command-line options that appear as paths but trigger an OS-level syntax error on Windows, such as the options used internally by `pytest-xdist`. - [#​7742](https://togithub.com/pytest-dev/pytest/issues/7742): Fixed INTERNALERROR when accessing locals / globals with faulty `exec`. ## Improved Documentation - [#​1477](https://togithub.com/pytest-dev/pytest/issues/1477): Removed faq.rst and its reference in contents.rst. ## Trivial/Internal Changes - [#​7536](https://togithub.com/pytest-dev/pytest/issues/7536): The internal `junitxml` plugin has rewritten to use `xml.etree.ElementTree`. The order of attributes in XML elements might differ. Some unneeded escaping is no longer performed. - [#​7587](https://togithub.com/pytest-dev/pytest/issues/7587): The dependency on the `more-itertools` package has been removed. - [#​7631](https://togithub.com/pytest-dev/pytest/issues/7631): The result type of capfd.readouterr() <\_pytest.capture.CaptureFixture.readouterr> (and similar) is no longer a namedtuple, but should behave like one in all respects. This was done for technical reasons. - [#​7671](https://togithub.com/pytest-dev/pytest/issues/7671): When collecting tests, pytest finds test classes and functions by examining the attributes of python objects (modules, classes and instances). To speed up this process, pytest now ignores builtin attributes (like `__class__`, `__delattr__` and `__new__`) without consulting the python_classes and python_functions configuration options and without passing them to plugins using the pytest_pycollect_makeitem <\_pytest.hookspec.pytest_pycollect_makeitem> hook. ### [`v6.0.2`](https://togithub.com/pytest-dev/pytest/releases/6.0.2) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.0.1...6.0.2) # pytest 6.0.2 (2020-09-04) ## Bug Fixes - [#​7148](https://togithub.com/pytest-dev/pytest/issues/7148): Fixed `--log-cli` potentially causing unrelated `print` output to be swallowed. - [#​7672](https://togithub.com/pytest-dev/pytest/issues/7672): Fixed log-capturing level restored incorrectly if `caplog.set_level` is called more than once. - [#​7686](https://togithub.com/pytest-dev/pytest/issues/7686): Fixed NotSetType.token being used as the parameter ID when the parametrization list is empty. Regressed in pytest 6.0.0. - [#​7707](https://togithub.com/pytest-dev/pytest/issues/7707): Fix internal error when handling some exceptions that contain multiple lines or the style uses multiple lines (`--tb=line` for example).
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻️ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements-test.txt | 2 +- samples/snippets/classify_text/requirements-test.txt | 2 +- samples/snippets/cloud-client/v1/requirements-test.txt | 2 +- samples/snippets/generated-samples/v1/requirements-test.txt | 2 +- samples/snippets/sentiment/requirements-test.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/api/requirements-test.txt +++ b/samples/snippets/api/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/classify_text/requirements-test.txt +++ b/samples/snippets/classify_text/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ b/samples/snippets/cloud-client/v1/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ b/samples/snippets/generated-samples/v1/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/sentiment/requirements-test.txt +++ b/samples/snippets/sentiment/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 From cc9c08ff52029ba40762641362a2efa4c26ccf74 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 20 May 2021 19:44:02 +0200 Subject: [PATCH 008/254] chore(deps): update dependency google-auth to v1.30.0 (#79) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-auth](https://togithub.com/googleapis/google-auth-library-python) | `==1.27.0` -> `==1.30.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-auth/1.30.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-auth/1.30.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-auth/1.30.0/compatibility-slim/1.27.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-auth/1.30.0/confidence-slim/1.27.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-auth-library-python ### [`v1.30.0`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1300-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1290v1300-2021-04-23) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.29.0...v1.30.0) ##### Features - add reauth support to async user credentials for gcloud ([#​738](https://www.github.com/googleapis/google-auth-library-python/issues/738)) ([9e10823](https://www.github.com/googleapis/google-auth-library-python/commit/9e1082366d113286bc063051fd76b4799791d943)). This internal feature is for gcloud developers only. ### [`v1.29.0`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1290-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1281v1290-2021-04-15) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.28.1...v1.29.0) ##### Features - add reauth feature to user credentials for gcloud ([#​727](https://www.github.com/googleapis/google-auth-library-python/issues/727)) ([82293fe](https://www.github.com/googleapis/google-auth-library-python/commit/82293fe2caaf5258babb5df1cff0a5ddc9e44b38)). This internal feature is for gcloud developers only. ##### Bug Fixes - Allow multiple audiences for id_token.verify_token ([#​733](https://www.github.com/googleapis/google-auth-library-python/issues/733)) ([56c3946](https://www.github.com/googleapis/google-auth-library-python/commit/56c394680ac6dfc07c611a9eb1e030e32edd4fe1)) ##### [1.28.1](https://www.github.com/googleapis/google-auth-library-python/compare/v1.28.0...v1.28.1) (2021-04-08) ##### Bug Fixes - support custom alg in jwt header for signing ([#​729](https://www.github.com/googleapis/google-auth-library-python/issues/729)) ([0a83706](https://www.github.com/googleapis/google-auth-library-python/commit/0a83706c9d65f7d5a30ea3b42c5beac269ed2a25)) ### [`v1.28.1`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1281-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1280v1281-2021-04-08) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.28.0...v1.28.1) ### [`v1.28.0`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1280-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1271v1280-2021-03-16) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.27.1...v1.28.0) ##### Features - allow the AWS_DEFAULT_REGION environment variable ([#​721](https://www.github.com/googleapis/google-auth-library-python/issues/721)) ([199da47](https://www.github.com/googleapis/google-auth-library-python/commit/199da4781029916dc075738ec7bd173bd89abe54)) - expose library version at `google.auth.__version` ([#​683](https://www.github.com/googleapis/google-auth-library-python/issues/683)) ([a2cbc32](https://www.github.com/googleapis/google-auth-library-python/commit/a2cbc3245460e1ae1d310de6a2a4007d5a3a06b7)) ##### Bug Fixes - fix unit tests so they can work in g3 ([#​714](https://www.github.com/googleapis/google-auth-library-python/issues/714)) ([d80c85f](https://www.github.com/googleapis/google-auth-library-python/commit/d80c85f285ae1a44ddc5a5d94a66e065a79f6d19)) ##### [1.27.1](https://www.github.com/googleapis/google-auth-library-python/compare/v1.27.0...v1.27.1) (2021-02-26) ##### Bug Fixes - ignore gcloud warning when getting project id ([#​708](https://www.github.com/googleapis/google-auth-library-python/issues/708)) ([3f2f3ea](https://www.github.com/googleapis/google-auth-library-python/commit/3f2f3eaf09006d3d0ec9c030d359114238479279)) - use gcloud creds flow ([#​705](https://www.github.com/googleapis/google-auth-library-python/issues/705)) ([333cb76](https://www.github.com/googleapis/google-auth-library-python/commit/333cb765b52028329ec3ca04edf32c5764b1db68)) ### [`v1.27.1`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1271-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1270v1271-2021-02-26) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.27.0...v1.27.1)
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻️ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 4574239f..c2320332 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==1.12.8 -google-auth==1.27.0 +google-auth==1.30.0 google-auth-httplib2==0.1.0 From 483b5c058df04e43fec9426e4f0f4a77bf0db281 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 20 May 2021 21:18:04 +0200 Subject: [PATCH 009/254] chore(deps): update dependency google-api-python-client to v2 (#81) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==1.12.8` -> `==2.5.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.5.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.5.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.5.0/compatibility-slim/1.12.8)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.5.0/confidence-slim/1.12.8)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.5.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​250-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev240v250-2021-05-20) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.4.0...v2.5.0) ##### Features - **adexchangebuyer:** update the api [`46d87cb`](https://togithub.com/googleapis/google-api-python-client/commit/46d87cb3e1f85ec9201134402b3c3afd2eb55770) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) - **analyticsadmin:** update the api [`9648bae`](https://togithub.com/googleapis/google-api-python-client/commit/9648bae09873a132e7b4627096c153043911be6e) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **analyticsadmin:** update the api [`adaafff`](https://togithub.com/googleapis/google-api-python-client/commit/adaafffbdeab31f05f9ad62d0f58846313bb3858) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) - **artifactregistry:** update the api [`7dd722f`](https://togithub.com/googleapis/google-api-python-client/commit/7dd722fe8b0ae822f4847219c442aa67a1aae7fd) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **assuredworkloads:** update the api [`9b84ffc`](https://togithub.com/googleapis/google-api-python-client/commit/9b84ffce415133e860cc55bfbd3b9c15c3d46a24) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **cloudasset:** update the api [`a8228db`](https://togithub.com/googleapis/google-api-python-client/commit/a8228db5ef31724493f0f62bf8062aca9adc44aa) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **cloudbuild:** update the api [`c9d8208`](https://togithub.com/googleapis/google-api-python-client/commit/c9d8208c0f9579d958224566af369b809e13016a) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **compute:** update the api [`685c19d`](https://togithub.com/googleapis/google-api-python-client/commit/685c19d4b5262d27a2b1016e01186188afe610fd) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **container:** update the api [`c5cd244`](https://togithub.com/googleapis/google-api-python-client/commit/c5cd244f996b1dfb605ef28eb22f8b0e76bffa1b) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **content:** update the api [`3b3e9be`](https://togithub.com/googleapis/google-api-python-client/commit/3b3e9be7e17c4efa89b45ac671a7c7f627a34cd7) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) - **dialogflow:** update the api [`0c6b31f`](https://togithub.com/googleapis/google-api-python-client/commit/0c6b31fd2deb75ca1c023fed36903b638f5e74f8) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **dialogflow:** update the api [`254b941`](https://togithub.com/googleapis/google-api-python-client/commit/254b9413a2ede306917031a2117f7af2df28a103) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) - **documentai:** update the api [`6dcec9f`](https://togithub.com/googleapis/google-api-python-client/commit/6dcec9fd8c0f803d37b4c8355870208e5a8c61ce) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **drive:** update the api [`8788823`](https://togithub.com/googleapis/google-api-python-client/commit/8788823461610f31eebd655915e07def9690da48) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **genomics:** update the api [`d0e6cc4`](https://togithub.com/googleapis/google-api-python-client/commit/d0e6cc48df2d0a00d91ce6fbab83aa82146f3573) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **logging:** update the api [`7f5fa16`](https://togithub.com/googleapis/google-api-python-client/commit/7f5fa161fd3db9ca6f2df23f5c8bd41ba01e9b9c) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **manufacturers:** update the api [`25bf19f`](https://togithub.com/googleapis/google-api-python-client/commit/25bf19f14a09428ab3fc6e51b0f6812867f99b04) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) - **privateca:** update the api [`0a5c31d`](https://togithub.com/googleapis/google-api-python-client/commit/0a5c31d74f788444640c174c413b12d494a00f1a) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **prod_tt_sasportal:** update the api [`af243b5`](https://togithub.com/googleapis/google-api-python-client/commit/af243b57a7039f4e01259fb085c7b07a66106fcf) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) - **pubsublite:** update the api [`dd67e9b`](https://togithub.com/googleapis/google-api-python-client/commit/dd67e9b117fdc8d0d0ecff6ade657003a95c12f7) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **recommender:** update the api [`4b261d9`](https://togithub.com/googleapis/google-api-python-client/commit/4b261d97bea2a8bc042a274c2d904be09da2d82c) ([c2cd326](https://www.github.com/googleapis/google-api-python-client/commit/c2cd326ef156fc2652d23e4c64fd06e2d66e3a80)) - **redis:** update the api [`5228389`](https://togithub.com/googleapis/google-api-python-client/commit/5228389cbd5fceb1bf8c2d36086faa147d91e50f) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) - **remotebuildexecution:** update the api [`7c8b314`](https://togithub.com/googleapis/google-api-python-client/commit/7c8b314e5508dda81cfb673039ea032f593fa97d) ([7700bbf](https://www.github.com/googleapis/google-api-python-client/commit/7700bbffda386345cc4426ef413fc643f6368ef4)) ### [`v2.4.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​240-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev230v240-2021-05-11) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.3.0...v2.4.0) ##### Features - **alertcenter:** update the api ([cbf5364](https://www.github.com/googleapis/google-api-python-client/commit/cbf5364f32932e6dc0baebfb3787a9f2fc889819)) - **analyticsadmin:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **androidenterprise:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **androidpublisher:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **artifactregistry:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **bigquery:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **chromepolicy:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **content:** update the api ([c0b883a](https://www.github.com/googleapis/google-api-python-client/commit/c0b883a43d90c27153eb1d205d52cd5d8b66c39a)) - **datacatalog:** update the api ([e58efe8](https://www.github.com/googleapis/google-api-python-client/commit/e58efe85e5988c93399dd3cf5290620d67baf038)) - **dataproc:** update the api ([cbf5364](https://www.github.com/googleapis/google-api-python-client/commit/cbf5364f32932e6dc0baebfb3787a9f2fc889819)) - **dialogflow:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **dns:** update the api ([c0b883a](https://www.github.com/googleapis/google-api-python-client/commit/c0b883a43d90c27153eb1d205d52cd5d8b66c39a)) - **documentai:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **file:** update the api ([cbf5364](https://www.github.com/googleapis/google-api-python-client/commit/cbf5364f32932e6dc0baebfb3787a9f2fc889819)) - **file:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **firebasestorage:** update the api ([27f691d](https://www.github.com/googleapis/google-api-python-client/commit/27f691d2f256447a41f44c77175edd0f37dddbdc)) - **gameservices:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **gkehub:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **lifesciences:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **monitoring:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **mybusinessaccountmanagement:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **networkmanagement:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **oslogin:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **pubsublite:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **recommender:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **retail:** update the api ([cbf5364](https://www.github.com/googleapis/google-api-python-client/commit/cbf5364f32932e6dc0baebfb3787a9f2fc889819)) - **servicedirectory:** update the api ([44a6719](https://www.github.com/googleapis/google-api-python-client/commit/44a6719b9f0024df4f4a4640743015507dbd0e94)) - **servicemanagement:** update the api ([c0b883a](https://www.github.com/googleapis/google-api-python-client/commit/c0b883a43d90c27153eb1d205d52cd5d8b66c39a)) - **servicenetworking:** update the api ([bfa2f1c](https://www.github.com/googleapis/google-api-python-client/commit/bfa2f1caee54b6f6bc8760a1d20e7014e607bd7f)) - **translate:** update the api ([c0b883a](https://www.github.com/googleapis/google-api-python-client/commit/c0b883a43d90c27153eb1d205d52cd5d8b66c39a)) ##### Bug Fixes - preventing accessing predefined discovery URLs when override is provided ([#​1324](https://www.github.com/googleapis/google-api-python-client/issues/1324)) ([1c4d199](https://www.github.com/googleapis/google-api-python-client/commit/1c4d1998086d89238ca5d961bc1c8eee5685345c)) ### [`v2.3.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​230-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev220v230-2021-04-28) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.2.0...v2.3.0) ##### Features - **apigee:** update the api ([3fd11cb](https://www.github.com/googleapis/google-api-python-client/commit/3fd11cbfa43679d14be7f09d9cb071d82d156ffa)) - **dataflow:** update the api ([3fd11cb](https://www.github.com/googleapis/google-api-python-client/commit/3fd11cbfa43679d14be7f09d9cb071d82d156ffa)) - **dialogflow:** update the api ([3fd11cb](https://www.github.com/googleapis/google-api-python-client/commit/3fd11cbfa43679d14be7f09d9cb071d82d156ffa)) - **documentai:** update the api ([3fd11cb](https://www.github.com/googleapis/google-api-python-client/commit/3fd11cbfa43679d14be7f09d9cb071d82d156ffa)) - **healthcare:** update the api ([3fd11cb](https://www.github.com/googleapis/google-api-python-client/commit/3fd11cbfa43679d14be7f09d9cb071d82d156ffa)) - **osconfig:** update the api ([afea316](https://www.github.com/googleapis/google-api-python-client/commit/afea316d32842ecb9e7d626842d5926b0bf3e34f)) - **sqladmin:** update the api ([cec4393](https://www.github.com/googleapis/google-api-python-client/commit/cec4393b8e37e229f68b2233a2041db062c2a335)) ### [`v2.2.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​220-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev210v220-2021-04-13) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.1.0...v2.2.0) ##### Features - Adds support for errors.py to also use 'errors' for error_details ([#​1281](https://www.github.com/googleapis/google-api-python-client/issues/1281)) ([a5d2081](https://www.github.com/googleapis/google-api-python-client/commit/a5d20813e8d7589b0cec030c149748e53ea555a5)) ### [`v2.1.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​210-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev202v210-2021-03-31) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.0.2...v2.1.0) ##### Features - add status_code property on http error handling ([#​1185](https://www.github.com/googleapis/google-api-python-client/issues/1185)) ([db2a766](https://www.github.com/googleapis/google-api-python-client/commit/db2a766bbd976742f6ef10d721d8423c8ac9246d)) ##### Bug Fixes - Change default of `static_discovery` when `discoveryServiceUrl` set ([#​1261](https://www.github.com/googleapis/google-api-python-client/issues/1261)) ([3b4f2e2](https://www.github.com/googleapis/google-api-python-client/commit/3b4f2e243709132b5ca41a3c23853d5067dfb0ab)) - correct api version in oauth-installed.md ([#​1258](https://www.github.com/googleapis/google-api-python-client/issues/1258)) ([d1a255f](https://www.github.com/googleapis/google-api-python-client/commit/d1a255fcbeaa36f615cede720692fea2b9f894db)) - fix .close() ([#​1231](https://www.github.com/googleapis/google-api-python-client/issues/1231)) ([a9583f7](https://www.github.com/googleapis/google-api-python-client/commit/a9583f712d13c67aa282d14cd30e00999b530d7c)) - Resolve issue where num_retries would have no effect ([#​1244](https://www.github.com/googleapis/google-api-python-client/issues/1244)) ([c518472](https://www.github.com/googleapis/google-api-python-client/commit/c518472e836c32ba2ff5e8480ab5a7643f722d46)) ##### Documentation - Distinguish between public/private docs in 2.0 guide ([#​1226](https://www.github.com/googleapis/google-api-python-client/issues/1226)) ([a6f1706](https://www.github.com/googleapis/google-api-python-client/commit/a6f17066caf6e911b7e94e8feab52fa3af2def1b)) - Update README to promote cloud client libraries ([#​1252](https://www.github.com/googleapis/google-api-python-client/issues/1252)) ([22807c9](https://www.github.com/googleapis/google-api-python-client/commit/22807c92ce754ff3d60f240ec5c38de50c5b654b)) ##### [2.0.2](https://www.github.com/googleapis/google-api-python-client/compare/v2.0.1...v2.0.2) (2021-03-04) ##### Bug Fixes - Include discovery artifacts in published package ([#​1221](https://www.github.com/googleapis/google-api-python-client/issues/1221)) ([ad618d0](https://www.github.com/googleapis/google-api-python-client/commit/ad618d0b266b86a795871d946367552905f4ccb6)) ##### [2.0.1](https://www.github.com/googleapis/google-api-python-client/compare/v2.0.0...v2.0.1) (2021-03-04) ##### Bug Fixes - add static discovery docs ([#​1216](https://www.github.com/googleapis/google-api-python-client/issues/1216)) ([b5d33d6](https://www.github.com/googleapis/google-api-python-client/commit/b5d33d6d520ca9589eefd08d34fe96844f420bce)) ##### Documentation - add a link to the migration guide in the changelog ([#​1213](https://www.github.com/googleapis/google-api-python-client/issues/1213)) ([b85da5b](https://www.github.com/googleapis/google-api-python-client/commit/b85da5bb7d6d6da60ff611221d3c4719eadb478a)) ### [`v2.0.2`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​202-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev201v202-2021-03-04) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.0.1...v2.0.2) ### [`v2.0.1`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​201-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev200v201-2021-03-04) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.0.0...v2.0.1) ### [`v2.0.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​200-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev1128v200-2021-03-03) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v1.12.8...v2.0.0) ##### ⚠ BREAKING CHANGES The 2.0 release of `google-api-python-client` is a significant upgrade compared to v1. Please see the [Migration Guide](UPGRADING.md) for more information. - **deps:** require 3.6+. ([#​961](https://togithub.com/googleapis/google-api-python-client/issues/961)) ##### Features - Add support for using static discovery documents ([#​1109](https://www.github.com/googleapis/google-api-python-client/issues/1109)) ([32d1c59](https://www.github.com/googleapis/google-api-python-client/commit/32d1c597b364e2641eca33ccf6df802bb218eea1)) - Update synth.py to copy discovery files from discovery-artifact-manager ([#​1104](https://www.github.com/googleapis/google-api-python-client/issues/1104)) ([af918e8](https://www.github.com/googleapis/google-api-python-client/commit/af918e8ef422438aaca0c468de8b3b2c184d884e)) ##### Bug Fixes - Catch ECONNRESET and other errors more reliably ([#​1147](https://www.github.com/googleapis/google-api-python-client/issues/1147)) ([ae9cd99](https://www.github.com/googleapis/google-api-python-client/commit/ae9cd99134160a5540e6f8d6d33d855122854e10)) - **deps:** add upper-bound google-auth dependency ([#​1180](https://www.github.com/googleapis/google-api-python-client/issues/1180)) ([c687f42](https://www.github.com/googleapis/google-api-python-client/commit/c687f4207b9c574e539a7eab75201a58f2e91f35)) - handle error on service not enabled ([#​1117](https://www.github.com/googleapis/google-api-python-client/issues/1117)) ([c691283](https://www.github.com/googleapis/google-api-python-client/commit/c6912836e88eea45aef7d515383e549082d37717)) - Improve support for error_details ([#​1126](https://www.github.com/googleapis/google-api-python-client/issues/1126)) ([e6a1da3](https://www.github.com/googleapis/google-api-python-client/commit/e6a1da3542e230e5287863f339ce1d28292cd92f)) - MediaFileUpload error if file does not exist ([#​1127](https://www.github.com/googleapis/google-api-python-client/issues/1127)) ([2c6d029](https://www.github.com/googleapis/google-api-python-client/commit/2c6d0297851c806ef850ca23686c51ca5878ac48)) - replace deprecated socket.error with OSError ([#​1161](https://www.github.com/googleapis/google-api-python-client/issues/1161)) ([b7b9986](https://www.github.com/googleapis/google-api-python-client/commit/b7b9986fe13c483eeefb77673b4091911978ee46)) - Use logging level info when file_cache is not available ([#​1125](https://www.github.com/googleapis/google-api-python-client/issues/1125)) ([0b32e69](https://www.github.com/googleapis/google-api-python-client/commit/0b32e69900eafec2cd1197ba054d4f9a765a3f29)) ##### Miscellaneous Chores - **deps:** require 3.6+ ([#​961](https://www.github.com/googleapis/google-api-python-client/issues/961)) ([8325d24](https://www.github.com/googleapis/google-api-python-client/commit/8325d24acaa2b2077acaaea26ea5fafb6dd856c5)) ##### Documentation - add networkconnectivity v1alpha1 ([#​1176](https://www.github.com/googleapis/google-api-python-client/issues/1176)) ([91b61d3](https://www.github.com/googleapis/google-api-python-client/commit/91b61d3272de9b5aebad0cf1eb76ca53c24f22f9)) - Delete redundant oauth-web.md ([#​1142](https://www.github.com/googleapis/google-api-python-client/issues/1142)) ([70bc6c9](https://www.github.com/googleapis/google-api-python-client/commit/70bc6c9db99eed5af7536b87448bd9323db9320b)) - fix MediaIoBaseUpload broken link ([#​1112](https://www.github.com/googleapis/google-api-python-client/issues/1112)) ([334b6e6](https://www.github.com/googleapis/google-api-python-client/commit/334b6e6d9e4924398e57bad2e53747584abf8cf4)) - fix regression with incorrect args order in docs ([#​1141](https://www.github.com/googleapis/google-api-python-client/issues/1141)) ([4249a7b](https://www.github.com/googleapis/google-api-python-client/commit/4249a7b92e891d1ecaf93944ca9c062ffbd54f77)) - fix typo in thread safety example code ([#​1100](https://www.github.com/googleapis/google-api-python-client/issues/1100)) ([5ae088d](https://www.github.com/googleapis/google-api-python-client/commit/5ae088dc027b89517b896a89a0aeb2ca80f492cf)) - Reduce noisy changes in docs regen ([#​1135](https://www.github.com/googleapis/google-api-python-client/issues/1135)) ([b1b0c83](https://www.github.com/googleapis/google-api-python-client/commit/b1b0c83ae0737e7b63cb77e4e7757213a216b88e)) - update docs/dyn ([#​1096](https://www.github.com/googleapis/google-api-python-client/issues/1096)) ([c2228be](https://www.github.com/googleapis/google-api-python-client/commit/c2228be4630e279e02a25b51566a0f93b67aa499)) - update guidance on service accounts ([#​1120](https://www.github.com/googleapis/google-api-python-client/issues/1120)) ([b2ea122](https://www.github.com/googleapis/google-api-python-client/commit/b2ea122c40ccac09c9e7b0b29f6b2bcca6db107b)) ##### [1.12.8](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.7...v1.12.8) (2020-11-18) ##### Documentation - add httplib2 authorization to thread_safety ([#​1005](https://www.github.com/googleapis/google-api-python-client/issues/1005)) ([205ae59](https://www.github.com/googleapis/google-api-python-client/commit/205ae5988bd89676823088d6c8a7bd17e3beefcf)), closes [#​808](https://www.github.com/googleapis/google-api-python-client/issues/808) [#​808](https://www.github.com/googleapis/google-api-python-client/issues/808) ##### [1.12.7](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.6...v1.12.7) (2020-11-17) ##### Documentation - Update Webmasters API sample ([#​1092](https://www.github.com/googleapis/google-api-python-client/issues/1092)) ([12831f3](https://www.github.com/googleapis/google-api-python-client/commit/12831f3e4716292b55b63dd2b08c3351f09b8a15)) ##### [1.12.6](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.5...v1.12.6) (2020-11-16) ##### Documentation - Change error parsing to check for 'message' ([#​1083](https://www.github.com/googleapis/google-api-python-client/issues/1083)) ([a341c5a](https://www.github.com/googleapis/google-api-python-client/commit/a341c5a5e31ba16da109658127b58cb7e5dbeedd)), closes [#​1082](https://www.github.com/googleapis/google-api-python-client/issues/1082) - Update oauth docs to include snippet to get email address of authenticated user ([#​1088](https://www.github.com/googleapis/google-api-python-client/issues/1088)) ([25fba64](https://www.github.com/googleapis/google-api-python-client/commit/25fba648ea647b62f2a6edc54ae927c1ed381b45)), closes [#​1071](https://www.github.com/googleapis/google-api-python-client/issues/1071) ##### [1.12.5](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.4...v1.12.5) (2020-10-22) ##### Bug Fixes - don't raise when downloading zero byte files ([#​1074](https://www.github.com/googleapis/google-api-python-client/issues/1074)) ([86d8788](https://www.github.com/googleapis/google-api-python-client/commit/86d8788ee8a766ca6818620f3fd2899be0e44190)) ##### [1.12.4](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.3...v1.12.4) (2020-10-20) ##### Bug Fixes - don't set content-range on empty uploads ([#​1070](https://www.github.com/googleapis/google-api-python-client/issues/1070)) ([af6035f](https://www.github.com/googleapis/google-api-python-client/commit/af6035f6754a155ee6b04bbbc5c39410c7316d6a)) ##### Documentation - fix typo in oauth.md ([#​1058](https://www.github.com/googleapis/google-api-python-client/issues/1058)) ([30eff9d](https://www.github.com/googleapis/google-api-python-client/commit/30eff9d8276919b8c4e50df2d3b1982594423692)) - update generated docs ([#​1053](https://www.github.com/googleapis/google-api-python-client/issues/1053)) ([3e17f89](https://www.github.com/googleapis/google-api-python-client/commit/3e17f8990db54bec16c48c319072799a14f5a53f)), closes [#​1049](https://www.github.com/googleapis/google-api-python-client/issues/1049) ##### [1.12.3](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.2...v1.12.3) (2020-09-29) ##### Bug Fixes - **deps:** update setup.py to install httplib2>=0.15.0 ([#​1050](https://www.github.com/googleapis/google-api-python-client/issues/1050)) ([c00f70d](https://www.github.com/googleapis/google-api-python-client/commit/c00f70d565a002b92374356be087927b131ce135)) ##### [1.12.2](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.1...v1.12.2) (2020-09-23) ##### Bug Fixes - add method to close httplib2 connections ([#​1038](https://www.github.com/googleapis/google-api-python-client/issues/1038)) ([98888da](https://www.github.com/googleapis/google-api-python-client/commit/98888dadf04e7e00524b6de273d28d02d7abc2c0)), closes [#​618](https://www.github.com/googleapis/google-api-python-client/issues/618) ##### [1.12.1](https://www.github.com/googleapis/google-api-python-client/compare/v1.12.0...v1.12.1) (2020-09-14) ##### Bug Fixes - **deps:** require six>=1.13.0 ([#​1030](https://www.github.com/googleapis/google-api-python-client/issues/1030)) ([4acecc3](https://www.github.com/googleapis/google-api-python-client/commit/4acecc3c0cd31308f9a256f065b7b1d1c3a4798d))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻️ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index c2320332..04d8d0ae 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==1.12.8 +google-api-python-client==2.5.0 google-auth==1.30.0 google-auth-httplib2==0.1.0 From 7e711ac63c95c1018d24c7c4db3bc02c191efcfc Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Sat, 22 May 2021 01:58:06 -0600 Subject: [PATCH 010/254] fix(deps): add packaging requirement (#113) --- setup.py | 1 + testing/constraints-3.6.txt | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index a6ee9706..c96cc6bc 100644 --- a/setup.py +++ b/setup.py @@ -31,6 +31,7 @@ dependencies = [ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.10.0", + "packaging >= 14.3", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 8f70f412..f462eab2 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -2,9 +2,10 @@ # are correct in setup.py # List all library dependencies and extras in this file. # Pin the version to the lower bound. - # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 google-api-core==1.22.2 proto-plus==1.10.0 libcst==0.2.5 +packaging==14.3 +google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 si transitively required through google-api-core From 0bdb2258c842a1fd1891bda8d18be8bc90b69d56 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 22 May 2021 09:32:06 +0000 Subject: [PATCH 011/254] chore: new owl bot post processor docker image (#115) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:3c3a445b3ddc99ccd5d31edc4b4519729635d20693900db32c4f587ed51f7479 --- .github/.OwlBot.lock.yaml | 2 +- noxfile.py | 6 ++++-- samples/snippets/api/noxfile.py | 8 +++++++- samples/snippets/classify_text/noxfile.py | 8 +++++++- samples/snippets/cloud-client/v1/noxfile.py | 8 +++++++- samples/snippets/generated-samples/v1/noxfile.py | 8 +++++++- samples/snippets/sentiment/noxfile.py | 8 +++++++- 7 files changed, 40 insertions(+), 8 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 864c1765..46e3f021 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa + digest: sha256:3c3a445b3ddc99ccd5d31edc4b4519729635d20693900db32c4f587ed51f7479 diff --git a/noxfile.py b/noxfile.py index 70417e8c..03aa2f58 100644 --- a/noxfile.py +++ b/noxfile.py @@ -179,7 +179,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -201,7 +201,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml") + session.install( + "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml" + ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 956cdf4f..5ff9e1db 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/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,6 +173,9 @@ 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"): if os.path.exists("constraints.txt"): diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 956cdf4f..5ff9e1db 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_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,6 +173,9 @@ 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"): if os.path.exists("constraints.txt"): diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 956cdf4f..5ff9e1db 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/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,6 +173,9 @@ 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"): if os.path.exists("constraints.txt"): diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 956cdf4f..5ff9e1db 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/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,6 +173,9 @@ 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"): if os.path.exists("constraints.txt"): diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 956cdf4f..5ff9e1db 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/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,6 +173,9 @@ 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"): if os.path.exists("constraints.txt"): From f1f2ab17259607d0c288352d98933630c567b148 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 25 May 2021 16:53:06 +0200 Subject: [PATCH 012/254] chore(deps): update dependency google-auth to v1.30.1 (#117) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 04d8d0ae..eb7666ab 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.5.0 -google-auth==1.30.0 +google-auth==1.30.1 google-auth-httplib2==0.1.0 From 8aaa04ef760ea799b6bcc63545b8f13714de3855 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 27 May 2021 20:03:14 +0200 Subject: [PATCH 013/254] chore(deps): update dependency google-api-python-client to v2.6.0 (#118) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index eb7666ab..f33cfcc1 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.5.0 +google-api-python-client==2.6.0 google-auth==1.30.1 google-auth-httplib2==0.1.0 From 828aa4ccdc4d33f9d66d90cbd1e6137fc911d5c8 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 28 May 2021 15:52:05 +0000 Subject: [PATCH 014/254] chore: new owl bot post processor docker image (#116) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:0856ca711da1fd5ec9d6d7da6c50aa0bbf550fb94acb47b55159a640791987bf --- .github/.OwlBot.lock.yaml | 2 +- docs/multiprocessing.rst | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 46e3f021..127c2cdf 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:3c3a445b3ddc99ccd5d31edc4b4519729635d20693900db32c4f587ed51f7479 + digest: sha256:0856ca711da1fd5ec9d6d7da6c50aa0bbf550fb94acb47b55159a640791987bf 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`. From d247efd98ea6ac1a876a11afad62921379398359 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 28 May 2021 17:02:04 +0000 Subject: [PATCH 015/254] chore: new owl bot post processor docker image (#119) Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 --- .github/.OwlBot.lock.yaml | 2 +- docs/conf.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 127c2cdf..da616c91 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:0856ca711da1fd5ec9d6d7da6c50aa0bbf550fb94acb47b55159a640791987bf + digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 diff --git a/docs/conf.py b/docs/conf.py index 91974e53..485a6f6e 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), } From 8c7f1ad041f8fb306ef23e4a75143bced3624a15 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 2 Jun 2021 05:30:55 -0400 Subject: [PATCH 016/254] chore: delete unused protos (#114) --- .../language_v1/proto/language_service.proto | 1122 ---------------- .../proto/language_service.proto | 1134 ----------------- 2 files changed, 2256 deletions(-) delete mode 100644 google/cloud/language_v1/proto/language_service.proto delete mode 100644 google/cloud/language_v1beta2/proto/language_service.proto diff --git a/google/cloud/language_v1/proto/language_service.proto b/google/cloud/language_v1/proto/language_service.proto deleted file mode 100644 index 304eab07..00000000 --- a/google/cloud/language_v1/proto/language_service.proto +++ /dev/null @@ -1,1122 +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.language.v1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; - -option go_package = "google.golang.org/genproto/googleapis/cloud/language/v1;language"; -option java_multiple_files = true; -option java_outer_classname = "LanguageServiceProto"; -option java_package = "com.google.cloud.language.v1"; - - -// Provides text analysis operations such as sentiment analysis and entity -// recognition. -service LanguageService { - option (google.api.default_host) = "language.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-language," - "https://www.googleapis.com/auth/cloud-platform"; - // Analyzes the sentiment of the provided text. - rpc AnalyzeSentiment(AnalyzeSentimentRequest) returns (AnalyzeSentimentResponse) { - option (google.api.http) = { - post: "/v1/documents:analyzeSentiment" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Finds named entities (currently proper names and common nouns) in the text - // along with entity types, salience, mentions for each entity, and - // other properties. - rpc AnalyzeEntities(AnalyzeEntitiesRequest) returns (AnalyzeEntitiesResponse) { - option (google.api.http) = { - post: "/v1/documents:analyzeEntities" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] in the text and analyzes - // sentiment associated with each entity and its mentions. - rpc AnalyzeEntitySentiment(AnalyzeEntitySentimentRequest) returns (AnalyzeEntitySentimentResponse) { - option (google.api.http) = { - post: "/v1/documents:analyzeEntitySentiment" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Analyzes the syntax of the text and provides sentence boundaries and - // tokenization along with part of speech tags, dependency trees, and other - // properties. - rpc AnalyzeSyntax(AnalyzeSyntaxRequest) returns (AnalyzeSyntaxResponse) { - option (google.api.http) = { - post: "/v1/documents:analyzeSyntax" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Classifies a document into categories. - rpc ClassifyText(ClassifyTextRequest) returns (ClassifyTextResponse) { - option (google.api.http) = { - post: "/v1/documents:classifyText" - body: "*" - }; - option (google.api.method_signature) = "document"; - } - - // A convenience method that provides all the features that analyzeSentiment, - // analyzeEntities, and analyzeSyntax provide in one call. - rpc AnnotateText(AnnotateTextRequest) returns (AnnotateTextResponse) { - option (google.api.http) = { - post: "/v1/documents:annotateText" - body: "*" - }; - option (google.api.method_signature) = "document,features,encoding_type"; - option (google.api.method_signature) = "document,features"; - } -} - - -// -// Represents the input to API methods. -message Document { - // The document types enum. - enum Type { - // The content type is not specified. - TYPE_UNSPECIFIED = 0; - - // Plain text - PLAIN_TEXT = 1; - - // HTML - HTML = 2; - } - - // Required. If the type is not set or is `TYPE_UNSPECIFIED`, - // returns an `INVALID_ARGUMENT` error. - Type type = 1; - - // The source of the document: a string containing the content or a - // Google Cloud Storage URI. - oneof source { - // The content of the input in string format. - // Cloud audit logging exempt since it is based on user data. - string content = 2; - - // The Google Cloud Storage URI where the file content is located. - // This URI must be of the form: gs://bucket_name/object_name. For more - // details, see https://cloud.google.com/storage/docs/reference-uris. - // NOTE: Cloud Storage object versioning is not supported. - string gcs_content_uri = 3; - } - - // The language of the document (if not specified, the language is - // automatically detected). Both ISO and BCP-47 language codes are - // accepted.
- // [Language - // Support](https://cloud.google.com/natural-language/docs/languages) lists - // currently supported languages for each API method. If the language (either - // specified by the caller or automatically detected) is not supported by the - // called API method, an `INVALID_ARGUMENT` error is returned. - string language = 4; -} - -// Represents a sentence in the input document. -message Sentence { - // The sentence text. - TextSpan text = 1; - - // For calls to [AnalyzeSentiment][] or if - // [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] is set to - // true, this field will contain the sentiment for the sentence. - Sentiment sentiment = 2; -} - -// Represents a phrase in the text that is a known entity, such as -// a person, an organization, or location. The API associates information, such -// as salience and mentions, with entities. -message Entity { - // The type of the entity. For most entity types, the associated metadata is a - // Wikipedia URL (`wikipedia_url`) and Knowledge Graph MID (`mid`). The table - // below lists the associated fields for entities that have different - // metadata. - enum Type { - // Unknown - UNKNOWN = 0; - - // Person - PERSON = 1; - - // Location - LOCATION = 2; - - // Organization - ORGANIZATION = 3; - - // Event - EVENT = 4; - - // Artwork - WORK_OF_ART = 5; - - // Consumer product - CONSUMER_GOOD = 6; - - // Other types of entities - OTHER = 7; - - // Phone number

- // The metadata lists the phone number, formatted according to local - // convention, plus whichever additional elements appear in the text:
    - //
  • number – the actual number, broken down into - // sections as per local convention
  • national_prefix - // – country code, if detected
  • area_code – - // region or area code, if detected
  • extension – - // phone extension (to be dialed after connection), if detected
- PHONE_NUMBER = 9; - - // Address

- // The metadata identifies the street number and locality plus whichever - // additional elements appear in the text:
    - //
  • street_number – street number
  • - //
  • locality – city or town
  • - //
  • street_name – street/route name, if detected
  • - //
  • postal_code – postal code, if detected
  • - //
  • country – country, if detected
  • - //
  • broad_region – administrative area, such as the - // state, if detected
  • narrow_region – smaller - // administrative area, such as county, if detected
  • - //
  • sublocality – used in Asian addresses to demark a - // district within a city, if detected
- ADDRESS = 10; - - // Date

- // The metadata identifies the components of the date:
    - //
  • year – four digit year, if detected
  • - //
  • month – two digit month number, if detected
  • - //
  • day – two digit day number, if detected
- DATE = 11; - - // Number

- // The metadata is the number itself. - NUMBER = 12; - - // Price

- // The metadata identifies the value and currency. - PRICE = 13; - } - - // The representative name for the entity. - string name = 1; - - // The entity type. - Type type = 2; - - // Metadata associated with the entity. - // - // For most entity types, the metadata is a Wikipedia URL (`wikipedia_url`) - // and Knowledge Graph MID (`mid`), if they are available. For the metadata - // associated with other entity types, see the Type table below. - map metadata = 3; - - // The salience score associated with the entity in the [0, 1.0] range. - // - // The salience score for an entity provides information about the - // importance or centrality of that entity to the entire document text. - // Scores closer to 0 are less salient, while scores closer to 1.0 are highly - // salient. - float salience = 4; - - // The mentions of this entity in the input document. The API currently - // supports proper noun mentions. - repeated EntityMention mentions = 5; - - // For calls to [AnalyzeEntitySentiment][] or if - // [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_entity_sentiment] is set to - // true, this field will contain the aggregate sentiment expressed for this - // entity in the provided document. - Sentiment sentiment = 6; -} - -// Represents the text encoding that the caller uses to process the output. -// Providing an `EncodingType` is recommended because the API provides the -// beginning offsets for various outputs, such as tokens and mentions, and -// languages that natively use different text encodings may access offsets -// differently. -enum EncodingType { - // If `EncodingType` is not specified, encoding-dependent information (such as - // `begin_offset`) will be set at `-1`. - NONE = 0; - - // Encoding-dependent information (such as `begin_offset`) is calculated based - // on the UTF-8 encoding of the input. C++ and Go are examples of languages - // that use this encoding natively. - UTF8 = 1; - - // Encoding-dependent information (such as `begin_offset`) is calculated based - // on the UTF-16 encoding of the input. Java and JavaScript are examples of - // languages that use this encoding natively. - UTF16 = 2; - - // Encoding-dependent information (such as `begin_offset`) is calculated based - // on the UTF-32 encoding of the input. Python is an example of a language - // that uses this encoding natively. - UTF32 = 3; -} - -// Represents the smallest syntactic building block of the text. -message Token { - // The token text. - TextSpan text = 1; - - // Parts of speech tag for this token. - PartOfSpeech part_of_speech = 2; - - // Dependency tree parse for this token. - DependencyEdge dependency_edge = 3; - - // [Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token. - string lemma = 4; -} - -// Represents the feeling associated with the entire text or entities in -// the text. -message Sentiment { - // A non-negative number in the [0, +inf) range, which represents - // the absolute magnitude of sentiment regardless of score (positive or - // negative). - float magnitude = 2; - - // Sentiment score between -1.0 (negative sentiment) and 1.0 - // (positive sentiment). - float score = 3; -} - -// Represents part of speech information for a token. Parts of speech -// are as defined in -// http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf -message PartOfSpeech { - // The part of speech tags enum. - enum Tag { - // Unknown - UNKNOWN = 0; - - // Adjective - ADJ = 1; - - // Adposition (preposition and postposition) - ADP = 2; - - // Adverb - ADV = 3; - - // Conjunction - CONJ = 4; - - // Determiner - DET = 5; - - // Noun (common and proper) - NOUN = 6; - - // Cardinal number - NUM = 7; - - // Pronoun - PRON = 8; - - // Particle or other function word - PRT = 9; - - // Punctuation - PUNCT = 10; - - // Verb (all tenses and modes) - VERB = 11; - - // Other: foreign words, typos, abbreviations - X = 12; - - // Affix - AFFIX = 13; - } - - // The characteristic of a verb that expresses time flow during an event. - enum Aspect { - // Aspect is not applicable in the analyzed language or is not predicted. - ASPECT_UNKNOWN = 0; - - // Perfective - PERFECTIVE = 1; - - // Imperfective - IMPERFECTIVE = 2; - - // Progressive - PROGRESSIVE = 3; - } - - // The grammatical function performed by a noun or pronoun in a phrase, - // clause, or sentence. In some languages, other parts of speech, such as - // adjective and determiner, take case inflection in agreement with the noun. - enum Case { - // Case is not applicable in the analyzed language or is not predicted. - CASE_UNKNOWN = 0; - - // Accusative - ACCUSATIVE = 1; - - // Adverbial - ADVERBIAL = 2; - - // Complementive - COMPLEMENTIVE = 3; - - // Dative - DATIVE = 4; - - // Genitive - GENITIVE = 5; - - // Instrumental - INSTRUMENTAL = 6; - - // Locative - LOCATIVE = 7; - - // Nominative - NOMINATIVE = 8; - - // Oblique - OBLIQUE = 9; - - // Partitive - PARTITIVE = 10; - - // Prepositional - PREPOSITIONAL = 11; - - // Reflexive - REFLEXIVE_CASE = 12; - - // Relative - RELATIVE_CASE = 13; - - // Vocative - VOCATIVE = 14; - } - - // Depending on the language, Form can be categorizing different forms of - // verbs, adjectives, adverbs, etc. For example, categorizing inflected - // endings of verbs and adjectives or distinguishing between short and long - // forms of adjectives and participles - enum Form { - // Form is not applicable in the analyzed language or is not predicted. - FORM_UNKNOWN = 0; - - // Adnomial - ADNOMIAL = 1; - - // Auxiliary - AUXILIARY = 2; - - // Complementizer - COMPLEMENTIZER = 3; - - // Final ending - FINAL_ENDING = 4; - - // Gerund - GERUND = 5; - - // Realis - REALIS = 6; - - // Irrealis - IRREALIS = 7; - - // Short form - SHORT = 8; - - // Long form - LONG = 9; - - // Order form - ORDER = 10; - - // Specific form - SPECIFIC = 11; - } - - // Gender classes of nouns reflected in the behaviour of associated words. - enum Gender { - // Gender is not applicable in the analyzed language or is not predicted. - GENDER_UNKNOWN = 0; - - // Feminine - FEMININE = 1; - - // Masculine - MASCULINE = 2; - - // Neuter - NEUTER = 3; - } - - // The grammatical feature of verbs, used for showing modality and attitude. - enum Mood { - // Mood is not applicable in the analyzed language or is not predicted. - MOOD_UNKNOWN = 0; - - // Conditional - CONDITIONAL_MOOD = 1; - - // Imperative - IMPERATIVE = 2; - - // Indicative - INDICATIVE = 3; - - // Interrogative - INTERROGATIVE = 4; - - // Jussive - JUSSIVE = 5; - - // Subjunctive - SUBJUNCTIVE = 6; - } - - // Count distinctions. - enum Number { - // Number is not applicable in the analyzed language or is not predicted. - NUMBER_UNKNOWN = 0; - - // Singular - SINGULAR = 1; - - // Plural - PLURAL = 2; - - // Dual - DUAL = 3; - } - - // The distinction between the speaker, second person, third person, etc. - enum Person { - // Person is not applicable in the analyzed language or is not predicted. - PERSON_UNKNOWN = 0; - - // First - FIRST = 1; - - // Second - SECOND = 2; - - // Third - THIRD = 3; - - // Reflexive - REFLEXIVE_PERSON = 4; - } - - // This category shows if the token is part of a proper name. - enum Proper { - // Proper is not applicable in the analyzed language or is not predicted. - PROPER_UNKNOWN = 0; - - // Proper - PROPER = 1; - - // Not proper - NOT_PROPER = 2; - } - - // Reciprocal features of a pronoun. - enum Reciprocity { - // Reciprocity is not applicable in the analyzed language or is not - // predicted. - RECIPROCITY_UNKNOWN = 0; - - // Reciprocal - RECIPROCAL = 1; - - // Non-reciprocal - NON_RECIPROCAL = 2; - } - - // Time reference. - enum Tense { - // Tense is not applicable in the analyzed language or is not predicted. - TENSE_UNKNOWN = 0; - - // Conditional - CONDITIONAL_TENSE = 1; - - // Future - FUTURE = 2; - - // Past - PAST = 3; - - // Present - PRESENT = 4; - - // Imperfect - IMPERFECT = 5; - - // Pluperfect - PLUPERFECT = 6; - } - - // The relationship between the action that a verb expresses and the - // participants identified by its arguments. - enum Voice { - // Voice is not applicable in the analyzed language or is not predicted. - VOICE_UNKNOWN = 0; - - // Active - ACTIVE = 1; - - // Causative - CAUSATIVE = 2; - - // Passive - PASSIVE = 3; - } - - // The part of speech tag. - Tag tag = 1; - - // The grammatical aspect. - Aspect aspect = 2; - - // The grammatical case. - Case case = 3; - - // The grammatical form. - Form form = 4; - - // The grammatical gender. - Gender gender = 5; - - // The grammatical mood. - Mood mood = 6; - - // The grammatical number. - Number number = 7; - - // The grammatical person. - Person person = 8; - - // The grammatical properness. - Proper proper = 9; - - // The grammatical reciprocity. - Reciprocity reciprocity = 10; - - // The grammatical tense. - Tense tense = 11; - - // The grammatical voice. - Voice voice = 12; -} - -// Represents dependency parse tree information for a token. (For more -// information on dependency labels, see -// http://www.aclweb.org/anthology/P13-2017 -message DependencyEdge { - // The parse label enum for the token. - enum Label { - // Unknown - UNKNOWN = 0; - - // Abbreviation modifier - ABBREV = 1; - - // Adjectival complement - ACOMP = 2; - - // Adverbial clause modifier - ADVCL = 3; - - // Adverbial modifier - ADVMOD = 4; - - // Adjectival modifier of an NP - AMOD = 5; - - // Appositional modifier of an NP - APPOS = 6; - - // Attribute dependent of a copular verb - ATTR = 7; - - // Auxiliary (non-main) verb - AUX = 8; - - // Passive auxiliary - AUXPASS = 9; - - // Coordinating conjunction - CC = 10; - - // Clausal complement of a verb or adjective - CCOMP = 11; - - // Conjunct - CONJ = 12; - - // Clausal subject - CSUBJ = 13; - - // Clausal passive subject - CSUBJPASS = 14; - - // Dependency (unable to determine) - DEP = 15; - - // Determiner - DET = 16; - - // Discourse - DISCOURSE = 17; - - // Direct object - DOBJ = 18; - - // Expletive - EXPL = 19; - - // Goes with (part of a word in a text not well edited) - GOESWITH = 20; - - // Indirect object - IOBJ = 21; - - // Marker (word introducing a subordinate clause) - MARK = 22; - - // Multi-word expression - MWE = 23; - - // Multi-word verbal expression - MWV = 24; - - // Negation modifier - NEG = 25; - - // Noun compound modifier - NN = 26; - - // Noun phrase used as an adverbial modifier - NPADVMOD = 27; - - // Nominal subject - NSUBJ = 28; - - // Passive nominal subject - NSUBJPASS = 29; - - // Numeric modifier of a noun - NUM = 30; - - // Element of compound number - NUMBER = 31; - - // Punctuation mark - P = 32; - - // Parataxis relation - PARATAXIS = 33; - - // Participial modifier - PARTMOD = 34; - - // The complement of a preposition is a clause - PCOMP = 35; - - // Object of a preposition - POBJ = 36; - - // Possession modifier - POSS = 37; - - // Postverbal negative particle - POSTNEG = 38; - - // Predicate complement - PRECOMP = 39; - - // Preconjunt - PRECONJ = 40; - - // Predeterminer - PREDET = 41; - - // Prefix - PREF = 42; - - // Prepositional modifier - PREP = 43; - - // The relationship between a verb and verbal morpheme - PRONL = 44; - - // Particle - PRT = 45; - - // Associative or possessive marker - PS = 46; - - // Quantifier phrase modifier - QUANTMOD = 47; - - // Relative clause modifier - RCMOD = 48; - - // Complementizer in relative clause - RCMODREL = 49; - - // Ellipsis without a preceding predicate - RDROP = 50; - - // Referent - REF = 51; - - // Remnant - REMNANT = 52; - - // Reparandum - REPARANDUM = 53; - - // Root - ROOT = 54; - - // Suffix specifying a unit of number - SNUM = 55; - - // Suffix - SUFF = 56; - - // Temporal modifier - TMOD = 57; - - // Topic marker - TOPIC = 58; - - // Clause headed by an infinite form of the verb that modifies a noun - VMOD = 59; - - // Vocative - VOCATIVE = 60; - - // Open clausal complement - XCOMP = 61; - - // Name suffix - SUFFIX = 62; - - // Name title - TITLE = 63; - - // Adverbial phrase modifier - ADVPHMOD = 64; - - // Causative auxiliary - AUXCAUS = 65; - - // Helper auxiliary - AUXVV = 66; - - // Rentaishi (Prenominal modifier) - DTMOD = 67; - - // Foreign words - FOREIGN = 68; - - // Keyword - KW = 69; - - // List for chains of comparable items - LIST = 70; - - // Nominalized clause - NOMC = 71; - - // Nominalized clausal subject - NOMCSUBJ = 72; - - // Nominalized clausal passive - NOMCSUBJPASS = 73; - - // Compound of numeric modifier - NUMC = 74; - - // Copula - COP = 75; - - // Dislocated relation (for fronted/topicalized elements) - DISLOCATED = 76; - - // Aspect marker - ASP = 77; - - // Genitive modifier - GMOD = 78; - - // Genitive object - GOBJ = 79; - - // Infinitival modifier - INFMOD = 80; - - // Measure - MES = 81; - - // Nominal complement of a noun - NCOMP = 82; - } - - // Represents the head of this token in the dependency tree. - // This is the index of the token which has an arc going to this token. - // The index is the position of the token in the array of tokens returned - // by the API method. If this token is a root token, then the - // `head_token_index` is its own index. - int32 head_token_index = 1; - - // The parse label for the token. - Label label = 2; -} - -// Represents a mention for an entity in the text. Currently, proper noun -// mentions are supported. -message EntityMention { - // The supported types of mentions. - enum Type { - // Unknown - TYPE_UNKNOWN = 0; - - // Proper name - PROPER = 1; - - // Common noun (or noun compound) - COMMON = 2; - } - - // The mention text. - TextSpan text = 1; - - // The type of the entity mention. - Type type = 2; - - // For calls to [AnalyzeEntitySentiment][] or if - // [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_entity_sentiment] is set to - // true, this field will contain the sentiment expressed for this mention of - // the entity in the provided document. - Sentiment sentiment = 3; -} - -// Represents an output piece of text. -message TextSpan { - // The content of the output text. - string content = 1; - - // The API calculates the beginning offset of the content in the original - // document according to the [EncodingType][google.cloud.language.v1.EncodingType] specified in the API request. - int32 begin_offset = 2; -} - -// Represents a category returned from the text classifier. -message ClassificationCategory { - // The name of the category representing the document, from the [predefined - // taxonomy](https://cloud.google.com/natural-language/docs/categories). - string name = 1; - - // The classifier's confidence of the category. Number represents how certain - // the classifier is that this category represents the given text. - float confidence = 2; -} - -// The sentiment analysis request message. -message AnalyzeSentimentRequest { - // Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate sentence offsets. - EncodingType encoding_type = 2; -} - -// The sentiment analysis response message. -message AnalyzeSentimentResponse { - // The overall sentiment of the input document. - Sentiment document_sentiment = 1; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1.Document.language] field for more details. - string language = 2; - - // The sentiment for all the sentences in the document. - repeated Sentence sentences = 3; -} - -// The entity-level sentiment analysis request message. -message AnalyzeEntitySentimentRequest { - // Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 2; -} - -// The entity-level sentiment analysis response message. -message AnalyzeEntitySentimentResponse { - // The recognized entities in the input document with associated sentiments. - repeated Entity entities = 1; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1.Document.language] field for more details. - string language = 2; -} - -// The entity analysis request message. -message AnalyzeEntitiesRequest { - // Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 2; -} - -// The entity analysis response message. -message AnalyzeEntitiesResponse { - // The recognized entities in the input document. - repeated Entity entities = 1; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1.Document.language] field for more details. - string language = 2; -} - -// The syntax analysis request message. -message AnalyzeSyntaxRequest { - // Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 2; -} - -// The syntax analysis response message. -message AnalyzeSyntaxResponse { - // Sentences in the input document. - repeated Sentence sentences = 1; - - // Tokens, along with their syntactic information, in the input document. - repeated Token tokens = 2; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1.Document.language] field for more details. - string language = 3; -} - -// The document classification request message. -message ClassifyTextRequest { - // Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// The document classification response message. -message ClassifyTextResponse { - // Categories representing the input document. - repeated ClassificationCategory categories = 1; -} - -// The request message for the text annotation API, which can perform multiple -// analysis types (sentiment, entities, and syntax) in one call. -message AnnotateTextRequest { - // All available features for sentiment, syntax, and semantic analysis. - // Setting each one to true will enable that specific analysis for the input. - message Features { - // Extract syntax information. - bool extract_syntax = 1; - - // Extract entities. - bool extract_entities = 2; - - // Extract document-level sentiment. - bool extract_document_sentiment = 3; - - // Extract entities and their associated sentiment. - bool extract_entity_sentiment = 4; - - // Classify the full document into categories. - bool classify_text = 6; - } - - // Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The enabled features. - Features features = 2 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 3; -} - -// The text annotations response message. -message AnnotateTextResponse { - // Sentences in the input document. Populated if the user enables - // [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1.AnnotateTextRequest.Features.extract_syntax]. - repeated Sentence sentences = 1; - - // Tokens, along with their syntactic information, in the input document. - // Populated if the user enables - // [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1.AnnotateTextRequest.Features.extract_syntax]. - repeated Token tokens = 2; - - // Entities, along with their semantic information, in the input document. - // Populated if the user enables - // [AnnotateTextRequest.Features.extract_entities][google.cloud.language.v1.AnnotateTextRequest.Features.extract_entities]. - repeated Entity entities = 3; - - // The overall sentiment for the document. Populated if the user enables - // [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment]. - Sentiment document_sentiment = 4; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1.Document.language] field for more details. - string language = 5; - - // Categories identified in the input document. - repeated ClassificationCategory categories = 6; -} diff --git a/google/cloud/language_v1beta2/proto/language_service.proto b/google/cloud/language_v1beta2/proto/language_service.proto deleted file mode 100644 index bd4167a3..00000000 --- a/google/cloud/language_v1beta2/proto/language_service.proto +++ /dev/null @@ -1,1134 +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.language.v1beta2; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "google.golang.org/genproto/googleapis/cloud/language/v1beta2;language"; -option java_multiple_files = true; -option java_outer_classname = "LanguageServiceProto"; -option java_package = "com.google.cloud.language.v1beta2"; - -// Provides text analysis operations such as sentiment analysis and entity -// recognition. -service LanguageService { - option (google.api.default_host) = "language.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-language," - "https://www.googleapis.com/auth/cloud-platform"; - - // Analyzes the sentiment of the provided text. - rpc AnalyzeSentiment(AnalyzeSentimentRequest) returns (AnalyzeSentimentResponse) { - option (google.api.http) = { - post: "/v1beta2/documents:analyzeSentiment" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Finds named entities (currently proper names and common nouns) in the text - // along with entity types, salience, mentions for each entity, and - // other properties. - rpc AnalyzeEntities(AnalyzeEntitiesRequest) returns (AnalyzeEntitiesResponse) { - option (google.api.http) = { - post: "/v1beta2/documents:analyzeEntities" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes - // sentiment associated with each entity and its mentions. - rpc AnalyzeEntitySentiment(AnalyzeEntitySentimentRequest) returns (AnalyzeEntitySentimentResponse) { - option (google.api.http) = { - post: "/v1beta2/documents:analyzeEntitySentiment" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Analyzes the syntax of the text and provides sentence boundaries and - // tokenization along with part-of-speech tags, dependency trees, and other - // properties. - rpc AnalyzeSyntax(AnalyzeSyntaxRequest) returns (AnalyzeSyntaxResponse) { - option (google.api.http) = { - post: "/v1beta2/documents:analyzeSyntax" - body: "*" - }; - option (google.api.method_signature) = "document,encoding_type"; - option (google.api.method_signature) = "document"; - } - - // Classifies a document into categories. - rpc ClassifyText(ClassifyTextRequest) returns (ClassifyTextResponse) { - option (google.api.http) = { - post: "/v1beta2/documents:classifyText" - body: "*" - }; - option (google.api.method_signature) = "document"; - } - - // A convenience method that provides all syntax, sentiment, entity, and - // classification features in one call. - rpc AnnotateText(AnnotateTextRequest) returns (AnnotateTextResponse) { - option (google.api.http) = { - post: "/v1beta2/documents:annotateText" - body: "*" - }; - option (google.api.method_signature) = "document,features,encoding_type"; - option (google.api.method_signature) = "document,features"; - } -} - - -// -// Represents the input to API methods. -message Document { - // The document types enum. - enum Type { - // The content type is not specified. - TYPE_UNSPECIFIED = 0; - - // Plain text - PLAIN_TEXT = 1; - - // HTML - HTML = 2; - } - - // Required. If the type is not set or is `TYPE_UNSPECIFIED`, - // returns an `INVALID_ARGUMENT` error. - Type type = 1; - - // The source of the document: a string containing the content or a - // Google Cloud Storage URI. - oneof source { - // The content of the input in string format. - // Cloud audit logging exempt since it is based on user data. - string content = 2; - - // The Google Cloud Storage URI where the file content is located. - // This URI must be of the form: gs://bucket_name/object_name. For more - // details, see https://cloud.google.com/storage/docs/reference-uris. - // NOTE: Cloud Storage object versioning is not supported. - string gcs_content_uri = 3; - } - - // The language of the document (if not specified, the language is - // automatically detected). Both ISO and BCP-47 language codes are - // accepted.
- // [Language - // Support](https://cloud.google.com/natural-language/docs/languages) lists - // currently supported languages for each API method. If the language (either - // specified by the caller or automatically detected) is not supported by the - // called API method, an `INVALID_ARGUMENT` error is returned. - string language = 4; -} - -// Represents a sentence in the input document. -message Sentence { - // The sentence text. - TextSpan text = 1; - - // For calls to [AnalyzeSentiment][] or if - // [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_document_sentiment] is set to - // true, this field will contain the sentiment for the sentence. - Sentiment sentiment = 2; -} - -// Represents a phrase in the text that is a known entity, such as -// a person, an organization, or location. The API associates information, such -// as salience and mentions, with entities. -message Entity { - // The type of the entity. For most entity types, the associated metadata is a - // Wikipedia URL (`wikipedia_url`) and Knowledge Graph MID (`mid`). The table - // below lists the associated fields for entities that have different - // metadata. - enum Type { - // Unknown - UNKNOWN = 0; - - // Person - PERSON = 1; - - // Location - LOCATION = 2; - - // Organization - ORGANIZATION = 3; - - // Event - EVENT = 4; - - // Artwork - WORK_OF_ART = 5; - - // Consumer product - CONSUMER_GOOD = 6; - - // Other types of entities - OTHER = 7; - - // Phone number - // - // The metadata lists the phone number, formatted according to local - // convention, plus whichever additional elements appear in the text: - // - // * `number` - the actual number, broken down into sections as per local - // convention - // * `national_prefix` - country code, if detected - // * `area_code` - region or area code, if detected - // * `extension` - phone extension (to be dialed after connection), if - // detected - PHONE_NUMBER = 9; - - // Address - // - // The metadata identifies the street number and locality plus whichever - // additional elements appear in the text: - // - // * `street_number` - street number - // * `locality` - city or town - // * `street_name` - street/route name, if detected - // * `postal_code` - postal code, if detected - // * `country` - country, if detected< - // * `broad_region` - administrative area, such as the state, if detected - // * `narrow_region` - smaller administrative area, such as county, if - // detected - // * `sublocality` - used in Asian addresses to demark a district within a - // city, if detected - ADDRESS = 10; - - // Date - // - // The metadata identifies the components of the date: - // - // * `year` - four digit year, if detected - // * `month` - two digit month number, if detected - // * `day` - two digit day number, if detected - DATE = 11; - - // Number - // - // The metadata is the number itself. - NUMBER = 12; - - // Price - // - // The metadata identifies the `value` and `currency`. - PRICE = 13; - } - - // The representative name for the entity. - string name = 1; - - // The entity type. - Type type = 2; - - // Metadata associated with the entity. - // - // For most entity types, the metadata is a Wikipedia URL (`wikipedia_url`) - // and Knowledge Graph MID (`mid`), if they are available. For the metadata - // associated with other entity types, see the Type table below. - map metadata = 3; - - // The salience score associated with the entity in the [0, 1.0] range. - // - // The salience score for an entity provides information about the - // importance or centrality of that entity to the entire document text. - // Scores closer to 0 are less salient, while scores closer to 1.0 are highly - // salient. - float salience = 4; - - // The mentions of this entity in the input document. The API currently - // supports proper noun mentions. - repeated EntityMention mentions = 5; - - // For calls to [AnalyzeEntitySentiment][] or if - // [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_entity_sentiment] is set to - // true, this field will contain the aggregate sentiment expressed for this - // entity in the provided document. - Sentiment sentiment = 6; -} - -// Represents the smallest syntactic building block of the text. -message Token { - // The token text. - TextSpan text = 1; - - // Parts of speech tag for this token. - PartOfSpeech part_of_speech = 2; - - // Dependency tree parse for this token. - DependencyEdge dependency_edge = 3; - - // [Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token. - string lemma = 4; -} - -// Represents the text encoding that the caller uses to process the output. -// Providing an `EncodingType` is recommended because the API provides the -// beginning offsets for various outputs, such as tokens and mentions, and -// languages that natively use different text encodings may access offsets -// differently. -enum EncodingType { - // If `EncodingType` is not specified, encoding-dependent information (such as - // `begin_offset`) will be set at `-1`. - NONE = 0; - - // Encoding-dependent information (such as `begin_offset`) is calculated based - // on the UTF-8 encoding of the input. C++ and Go are examples of languages - // that use this encoding natively. - UTF8 = 1; - - // Encoding-dependent information (such as `begin_offset`) is calculated based - // on the UTF-16 encoding of the input. Java and JavaScript are examples of - // languages that use this encoding natively. - UTF16 = 2; - - // Encoding-dependent information (such as `begin_offset`) is calculated based - // on the UTF-32 encoding of the input. Python is an example of a language - // that uses this encoding natively. - UTF32 = 3; -} - -// Represents the feeling associated with the entire text or entities in -// the text. -// Next ID: 6 -message Sentiment { - // A non-negative number in the [0, +inf) range, which represents - // the absolute magnitude of sentiment regardless of score (positive or - // negative). - float magnitude = 2; - - // Sentiment score between -1.0 (negative sentiment) and 1.0 - // (positive sentiment). - float score = 3; -} - -// Represents part of speech information for a token. -message PartOfSpeech { - // The part of speech tags enum. - enum Tag { - // Unknown - UNKNOWN = 0; - - // Adjective - ADJ = 1; - - // Adposition (preposition and postposition) - ADP = 2; - - // Adverb - ADV = 3; - - // Conjunction - CONJ = 4; - - // Determiner - DET = 5; - - // Noun (common and proper) - NOUN = 6; - - // Cardinal number - NUM = 7; - - // Pronoun - PRON = 8; - - // Particle or other function word - PRT = 9; - - // Punctuation - PUNCT = 10; - - // Verb (all tenses and modes) - VERB = 11; - - // Other: foreign words, typos, abbreviations - X = 12; - - // Affix - AFFIX = 13; - } - - // The characteristic of a verb that expresses time flow during an event. - enum Aspect { - // Aspect is not applicable in the analyzed language or is not predicted. - ASPECT_UNKNOWN = 0; - - // Perfective - PERFECTIVE = 1; - - // Imperfective - IMPERFECTIVE = 2; - - // Progressive - PROGRESSIVE = 3; - } - - // The grammatical function performed by a noun or pronoun in a phrase, - // clause, or sentence. In some languages, other parts of speech, such as - // adjective and determiner, take case inflection in agreement with the noun. - enum Case { - // Case is not applicable in the analyzed language or is not predicted. - CASE_UNKNOWN = 0; - - // Accusative - ACCUSATIVE = 1; - - // Adverbial - ADVERBIAL = 2; - - // Complementive - COMPLEMENTIVE = 3; - - // Dative - DATIVE = 4; - - // Genitive - GENITIVE = 5; - - // Instrumental - INSTRUMENTAL = 6; - - // Locative - LOCATIVE = 7; - - // Nominative - NOMINATIVE = 8; - - // Oblique - OBLIQUE = 9; - - // Partitive - PARTITIVE = 10; - - // Prepositional - PREPOSITIONAL = 11; - - // Reflexive - REFLEXIVE_CASE = 12; - - // Relative - RELATIVE_CASE = 13; - - // Vocative - VOCATIVE = 14; - } - - // Depending on the language, Form can be categorizing different forms of - // verbs, adjectives, adverbs, etc. For example, categorizing inflected - // endings of verbs and adjectives or distinguishing between short and long - // forms of adjectives and participles - enum Form { - // Form is not applicable in the analyzed language or is not predicted. - FORM_UNKNOWN = 0; - - // Adnomial - ADNOMIAL = 1; - - // Auxiliary - AUXILIARY = 2; - - // Complementizer - COMPLEMENTIZER = 3; - - // Final ending - FINAL_ENDING = 4; - - // Gerund - GERUND = 5; - - // Realis - REALIS = 6; - - // Irrealis - IRREALIS = 7; - - // Short form - SHORT = 8; - - // Long form - LONG = 9; - - // Order form - ORDER = 10; - - // Specific form - SPECIFIC = 11; - } - - // Gender classes of nouns reflected in the behaviour of associated words. - enum Gender { - // Gender is not applicable in the analyzed language or is not predicted. - GENDER_UNKNOWN = 0; - - // Feminine - FEMININE = 1; - - // Masculine - MASCULINE = 2; - - // Neuter - NEUTER = 3; - } - - // The grammatical feature of verbs, used for showing modality and attitude. - enum Mood { - // Mood is not applicable in the analyzed language or is not predicted. - MOOD_UNKNOWN = 0; - - // Conditional - CONDITIONAL_MOOD = 1; - - // Imperative - IMPERATIVE = 2; - - // Indicative - INDICATIVE = 3; - - // Interrogative - INTERROGATIVE = 4; - - // Jussive - JUSSIVE = 5; - - // Subjunctive - SUBJUNCTIVE = 6; - } - - // Count distinctions. - enum Number { - // Number is not applicable in the analyzed language or is not predicted. - NUMBER_UNKNOWN = 0; - - // Singular - SINGULAR = 1; - - // Plural - PLURAL = 2; - - // Dual - DUAL = 3; - } - - // The distinction between the speaker, second person, third person, etc. - enum Person { - // Person is not applicable in the analyzed language or is not predicted. - PERSON_UNKNOWN = 0; - - // First - FIRST = 1; - - // Second - SECOND = 2; - - // Third - THIRD = 3; - - // Reflexive - REFLEXIVE_PERSON = 4; - } - - // This category shows if the token is part of a proper name. - enum Proper { - // Proper is not applicable in the analyzed language or is not predicted. - PROPER_UNKNOWN = 0; - - // Proper - PROPER = 1; - - // Not proper - NOT_PROPER = 2; - } - - // Reciprocal features of a pronoun. - enum Reciprocity { - // Reciprocity is not applicable in the analyzed language or is not - // predicted. - RECIPROCITY_UNKNOWN = 0; - - // Reciprocal - RECIPROCAL = 1; - - // Non-reciprocal - NON_RECIPROCAL = 2; - } - - // Time reference. - enum Tense { - // Tense is not applicable in the analyzed language or is not predicted. - TENSE_UNKNOWN = 0; - - // Conditional - CONDITIONAL_TENSE = 1; - - // Future - FUTURE = 2; - - // Past - PAST = 3; - - // Present - PRESENT = 4; - - // Imperfect - IMPERFECT = 5; - - // Pluperfect - PLUPERFECT = 6; - } - - // The relationship between the action that a verb expresses and the - // participants identified by its arguments. - enum Voice { - // Voice is not applicable in the analyzed language or is not predicted. - VOICE_UNKNOWN = 0; - - // Active - ACTIVE = 1; - - // Causative - CAUSATIVE = 2; - - // Passive - PASSIVE = 3; - } - - // The part of speech tag. - Tag tag = 1; - - // The grammatical aspect. - Aspect aspect = 2; - - // The grammatical case. - Case case = 3; - - // The grammatical form. - Form form = 4; - - // The grammatical gender. - Gender gender = 5; - - // The grammatical mood. - Mood mood = 6; - - // The grammatical number. - Number number = 7; - - // The grammatical person. - Person person = 8; - - // The grammatical properness. - Proper proper = 9; - - // The grammatical reciprocity. - Reciprocity reciprocity = 10; - - // The grammatical tense. - Tense tense = 11; - - // The grammatical voice. - Voice voice = 12; -} - -// Represents dependency parse tree information for a token. -message DependencyEdge { - // The parse label enum for the token. - enum Label { - // Unknown - UNKNOWN = 0; - - // Abbreviation modifier - ABBREV = 1; - - // Adjectival complement - ACOMP = 2; - - // Adverbial clause modifier - ADVCL = 3; - - // Adverbial modifier - ADVMOD = 4; - - // Adjectival modifier of an NP - AMOD = 5; - - // Appositional modifier of an NP - APPOS = 6; - - // Attribute dependent of a copular verb - ATTR = 7; - - // Auxiliary (non-main) verb - AUX = 8; - - // Passive auxiliary - AUXPASS = 9; - - // Coordinating conjunction - CC = 10; - - // Clausal complement of a verb or adjective - CCOMP = 11; - - // Conjunct - CONJ = 12; - - // Clausal subject - CSUBJ = 13; - - // Clausal passive subject - CSUBJPASS = 14; - - // Dependency (unable to determine) - DEP = 15; - - // Determiner - DET = 16; - - // Discourse - DISCOURSE = 17; - - // Direct object - DOBJ = 18; - - // Expletive - EXPL = 19; - - // Goes with (part of a word in a text not well edited) - GOESWITH = 20; - - // Indirect object - IOBJ = 21; - - // Marker (word introducing a subordinate clause) - MARK = 22; - - // Multi-word expression - MWE = 23; - - // Multi-word verbal expression - MWV = 24; - - // Negation modifier - NEG = 25; - - // Noun compound modifier - NN = 26; - - // Noun phrase used as an adverbial modifier - NPADVMOD = 27; - - // Nominal subject - NSUBJ = 28; - - // Passive nominal subject - NSUBJPASS = 29; - - // Numeric modifier of a noun - NUM = 30; - - // Element of compound number - NUMBER = 31; - - // Punctuation mark - P = 32; - - // Parataxis relation - PARATAXIS = 33; - - // Participial modifier - PARTMOD = 34; - - // The complement of a preposition is a clause - PCOMP = 35; - - // Object of a preposition - POBJ = 36; - - // Possession modifier - POSS = 37; - - // Postverbal negative particle - POSTNEG = 38; - - // Predicate complement - PRECOMP = 39; - - // Preconjunt - PRECONJ = 40; - - // Predeterminer - PREDET = 41; - - // Prefix - PREF = 42; - - // Prepositional modifier - PREP = 43; - - // The relationship between a verb and verbal morpheme - PRONL = 44; - - // Particle - PRT = 45; - - // Associative or possessive marker - PS = 46; - - // Quantifier phrase modifier - QUANTMOD = 47; - - // Relative clause modifier - RCMOD = 48; - - // Complementizer in relative clause - RCMODREL = 49; - - // Ellipsis without a preceding predicate - RDROP = 50; - - // Referent - REF = 51; - - // Remnant - REMNANT = 52; - - // Reparandum - REPARANDUM = 53; - - // Root - ROOT = 54; - - // Suffix specifying a unit of number - SNUM = 55; - - // Suffix - SUFF = 56; - - // Temporal modifier - TMOD = 57; - - // Topic marker - TOPIC = 58; - - // Clause headed by an infinite form of the verb that modifies a noun - VMOD = 59; - - // Vocative - VOCATIVE = 60; - - // Open clausal complement - XCOMP = 61; - - // Name suffix - SUFFIX = 62; - - // Name title - TITLE = 63; - - // Adverbial phrase modifier - ADVPHMOD = 64; - - // Causative auxiliary - AUXCAUS = 65; - - // Helper auxiliary - AUXVV = 66; - - // Rentaishi (Prenominal modifier) - DTMOD = 67; - - // Foreign words - FOREIGN = 68; - - // Keyword - KW = 69; - - // List for chains of comparable items - LIST = 70; - - // Nominalized clause - NOMC = 71; - - // Nominalized clausal subject - NOMCSUBJ = 72; - - // Nominalized clausal passive - NOMCSUBJPASS = 73; - - // Compound of numeric modifier - NUMC = 74; - - // Copula - COP = 75; - - // Dislocated relation (for fronted/topicalized elements) - DISLOCATED = 76; - - // Aspect marker - ASP = 77; - - // Genitive modifier - GMOD = 78; - - // Genitive object - GOBJ = 79; - - // Infinitival modifier - INFMOD = 80; - - // Measure - MES = 81; - - // Nominal complement of a noun - NCOMP = 82; - } - - // Represents the head of this token in the dependency tree. - // This is the index of the token which has an arc going to this token. - // The index is the position of the token in the array of tokens returned - // by the API method. If this token is a root token, then the - // `head_token_index` is its own index. - int32 head_token_index = 1; - - // The parse label for the token. - Label label = 2; -} - -// Represents a mention for an entity in the text. Currently, proper noun -// mentions are supported. -message EntityMention { - // The supported types of mentions. - enum Type { - // Unknown - TYPE_UNKNOWN = 0; - - // Proper name - PROPER = 1; - - // Common noun (or noun compound) - COMMON = 2; - } - - // The mention text. - TextSpan text = 1; - - // The type of the entity mention. - Type type = 2; - - // For calls to [AnalyzeEntitySentiment][] or if - // [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_entity_sentiment] is set to - // true, this field will contain the sentiment expressed for this mention of - // the entity in the provided document. - Sentiment sentiment = 3; -} - -// Represents an output piece of text. -message TextSpan { - // The content of the output text. - string content = 1; - - // The API calculates the beginning offset of the content in the original - // document according to the [EncodingType][google.cloud.language.v1beta2.EncodingType] specified in the API request. - int32 begin_offset = 2; -} - -// Represents a category returned from the text classifier. -message ClassificationCategory { - // The name of the category representing the document, from the [predefined - // taxonomy](https://cloud.google.com/natural-language/docs/categories). - string name = 1; - - // The classifier's confidence of the category. Number represents how certain - // the classifier is that this category represents the given text. - float confidence = 2; -} - -// The sentiment analysis request message. -message AnalyzeSentimentRequest { - // Required. Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate sentence offsets for the - // sentence sentiment. - EncodingType encoding_type = 2; -} - -// The sentiment analysis response message. -message AnalyzeSentimentResponse { - // The overall sentiment of the input document. - Sentiment document_sentiment = 1; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1beta2.Document.language] field for more details. - string language = 2; - - // The sentiment for all the sentences in the document. - repeated Sentence sentences = 3; -} - -// The entity-level sentiment analysis request message. -message AnalyzeEntitySentimentRequest { - // Required. Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 2; -} - -// The entity-level sentiment analysis response message. -message AnalyzeEntitySentimentResponse { - // The recognized entities in the input document with associated sentiments. - repeated Entity entities = 1; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1beta2.Document.language] field for more details. - string language = 2; -} - -// The entity analysis request message. -message AnalyzeEntitiesRequest { - // Required. Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 2; -} - -// The entity analysis response message. -message AnalyzeEntitiesResponse { - // The recognized entities in the input document. - repeated Entity entities = 1; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1beta2.Document.language] field for more details. - string language = 2; -} - -// The syntax analysis request message. -message AnalyzeSyntaxRequest { - // Required. Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 2; -} - -// The syntax analysis response message. -message AnalyzeSyntaxResponse { - // Sentences in the input document. - repeated Sentence sentences = 1; - - // Tokens, along with their syntactic information, in the input document. - repeated Token tokens = 2; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1beta2.Document.language] field for more details. - string language = 3; -} - -// The document classification request message. -message ClassifyTextRequest { - // Required. Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// The document classification response message. -message ClassifyTextResponse { - // Categories representing the input document. - repeated ClassificationCategory categories = 1; -} - -// The request message for the text annotation API, which can perform multiple -// analysis types (sentiment, entities, and syntax) in one call. -message AnnotateTextRequest { - // All available features for sentiment, syntax, and semantic analysis. - // Setting each one to true will enable that specific analysis for the input. - // Next ID: 10 - message Features { - // Extract syntax information. - bool extract_syntax = 1; - - // Extract entities. - bool extract_entities = 2; - - // Extract document-level sentiment. - bool extract_document_sentiment = 3; - - // Extract entities and their associated sentiment. - bool extract_entity_sentiment = 4; - - // Classify the full document into categories. If this is true, - // the API will use the default model which classifies into a - // [predefined - // taxonomy](https://cloud.google.com/natural-language/docs/categories). - bool classify_text = 6; - } - - // Required. Input document. - Document document = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. The enabled features. - Features features = 2 [(google.api.field_behavior) = REQUIRED]; - - // The encoding type used by the API to calculate offsets. - EncodingType encoding_type = 3; -} - -// The text annotations response message. -message AnnotateTextResponse { - // Sentences in the input document. Populated if the user enables - // [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_syntax]. - repeated Sentence sentences = 1; - - // Tokens, along with their syntactic information, in the input document. - // Populated if the user enables - // [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_syntax]. - repeated Token tokens = 2; - - // Entities, along with their semantic information, in the input document. - // Populated if the user enables - // [AnnotateTextRequest.Features.extract_entities][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_entities]. - repeated Entity entities = 3; - - // The overall sentiment for the document. Populated if the user enables - // [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_document_sentiment]. - Sentiment document_sentiment = 4; - - // The language of the text, which will be the same as the language specified - // in the request or, if not specified, the automatically-detected language. - // See [Document.language][google.cloud.language.v1beta2.Document.language] field for more details. - string language = 5; - - // Categories identified in the input document. - repeated ClassificationCategory categories = 6; -} From e7b4e0c2723469e5914dd19a299ac29a707706b7 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 11 Jun 2021 14:36:04 +0200 Subject: [PATCH 017/254] chore(deps): update dependency google-auth to v1.31.0 (#122) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-auth](https://togithub.com/googleapis/google-auth-library-python) | `==1.30.1` -> `==1.31.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-auth/1.31.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-auth/1.31.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-auth/1.31.0/compatibility-slim/1.30.1)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-auth/1.31.0/confidence-slim/1.30.1)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-auth-library-python ### [`v1.31.0`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1310-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1302v1310-2021-06-09) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.30.2...v1.31.0) ##### Features - define useful properties on `google.auth.external_account.Credentials` ([#​770](https://www.github.com/googleapis/google-auth-library-python/issues/770)) ([f97499c](https://www.github.com/googleapis/google-auth-library-python/commit/f97499c718af70d17c17e0c58d6381273eceabcd)) ##### Bug Fixes - avoid deleting items while iterating ([#​772](https://www.github.com/googleapis/google-auth-library-python/issues/772)) ([a5e6b65](https://www.github.com/googleapis/google-auth-library-python/commit/a5e6b651aa8ad407ce087fe32f40b46925bae527)) ##### [1.30.2](https://www.github.com/googleapis/google-auth-library-python/compare/v1.30.1...v1.30.2) (2021-06-03) ##### Bug Fixes - **dependencies:** add urllib3 and requests to aiohttp extra ([#​755](https://www.github.com/googleapis/google-auth-library-python/issues/755)) ([a923442](https://www.github.com/googleapis/google-auth-library-python/commit/a9234423cb2b69068fc0d30a5a0ee86a599ab8b7)) - enforce constraints during unit tests ([#​760](https://www.github.com/googleapis/google-auth-library-python/issues/760)) ([1a6496a](https://www.github.com/googleapis/google-auth-library-python/commit/1a6496abfc17ab781bfa485dc74d0f7dbbe0c44b)), closes [#​759](https://www.github.com/googleapis/google-auth-library-python/issues/759) - session object was never used in aiohttp request ([#​700](https://www.github.com/googleapis/google-auth-library-python/issues/700)) ([#​701](https://www.github.com/googleapis/google-auth-library-python/issues/701)) ([09e0389](https://www.github.com/googleapis/google-auth-library-python/commit/09e0389db72cc9d6c5dde34864cb54d717dc0b92)) ##### [1.30.1](https://www.github.com/googleapis/google-auth-library-python/compare/v1.30.0...v1.30.1) (2021-05-20) ##### Bug Fixes - allow user to customize context aware metadata path in \_mtls_helper ([#​754](https://www.github.com/googleapis/google-auth-library-python/issues/754)) ([e697687](https://www.github.com/googleapis/google-auth-library-python/commit/e6976879b392508c022610ab3ea2ea55c7089c63)) - fix function name in signing error message ([#​751](https://www.github.com/googleapis/google-auth-library-python/issues/751)) ([e9ca25f](https://www.github.com/googleapis/google-auth-library-python/commit/e9ca25fa39a112cc1a376388ab47a4e1b3ea746c)) ### [`v1.30.2`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1302-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1301v1302-2021-06-03) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.30.1...v1.30.2)
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index f33cfcc1..4a7d27a0 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.6.0 -google-auth==1.30.1 +google-auth==1.31.0 google-auth-httplib2==0.1.0 From cde297cbef6d20e81f793173340af3a6d3051080 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 11 Jun 2021 14:42:02 +0200 Subject: [PATCH 018/254] chore(deps): update dependency google-api-python-client to v2.8.0 (#120) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==2.6.0` -> `==2.8.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.8.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.8.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.8.0/compatibility-slim/2.6.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.8.0/confidence-slim/2.6.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.8.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​280-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev270v280-2021-06-08) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.7.0...v2.8.0) ##### Features - **apigee:** update the api https://github.com/googleapis/google-api-python-client/commit/e1ea8735612457f6f8b85226887babd904958b25 ([cb945f3](https://www.github.com/googleapis/google-api-python-client/commit/cb945f37130d2950801e02512761f061cef0b54e)) - **bigquery:** update the api https://github.com/googleapis/google-api-python-client/commit/73965daab29cd6ae78004ede62f8c6c80f5587a3 ([31fbcc0](https://www.github.com/googleapis/google-api-python-client/commit/31fbcc014f8642fb0cde7de47889b55a2eaf3f71)) - **compute:** update the api https://github.com/googleapis/google-api-python-client/commit/b8ce2754752f8157b84091a99594f9a45a8f8eed ([8759538](https://www.github.com/googleapis/google-api-python-client/commit/8759538c0ab491be1678db74a3ad538957610d70)) - **container:** update the api https://github.com/googleapis/google-api-python-client/commit/a73f41e49d7ab6258bd722b4ee6d022c195975c2 ([8759538](https://www.github.com/googleapis/google-api-python-client/commit/8759538c0ab491be1678db74a3ad538957610d70)) - **content:** update the api https://github.com/googleapis/google-api-python-client/commit/097e3329e1e5de3ae416cdabc9a73e2fa63a09e9 ([cb945f3](https://www.github.com/googleapis/google-api-python-client/commit/cb945f37130d2950801e02512761f061cef0b54e)) - **dataproc:** update the api https://github.com/googleapis/google-api-python-client/commit/be0dde6ee43f4ff05396d33b16e0af2a1fabfc28 ([8759538](https://www.github.com/googleapis/google-api-python-client/commit/8759538c0ab491be1678db74a3ad538957610d70)) - **dialogflow:** update the api https://github.com/googleapis/google-api-python-client/commit/f7b0ebc0047427b3633480999ed28e0f37fa77f1 ([50e1b7a](https://www.github.com/googleapis/google-api-python-client/commit/50e1b7a1b5c337926c5d2b2f648f057d67431cd6)) - **displayvideo:** update the api https://github.com/googleapis/google-api-python-client/commit/f6b1a8e2d291c2ac9d2ea590101bb3c8c6fbe6cf ([eb505db](https://www.github.com/googleapis/google-api-python-client/commit/eb505dbed724dbd07b151d06fd1b45037dc7e75f)) - **documentai:** update the api https://github.com/googleapis/google-api-python-client/commit/72f3faea1be17c074dc566b33707dad37c9ba16b ([cb945f3](https://www.github.com/googleapis/google-api-python-client/commit/cb945f37130d2950801e02512761f061cef0b54e)) - **lifesciences:** update the api https://github.com/googleapis/google-api-python-client/commit/c524c0a316e4206c8b0e0075e3ed5eceb7e60016 ([8759538](https://www.github.com/googleapis/google-api-python-client/commit/8759538c0ab491be1678db74a3ad538957610d70)) - **metastore:** update the api https://github.com/googleapis/google-api-python-client/commit/54639a05ea77c1a067ed1e3b5df46b2c029c47ea ([4d1153d](https://www.github.com/googleapis/google-api-python-client/commit/4d1153db18a3edf86c5bb83149b4f1c0ba95f810)) - **metastore:** update the api https://github.com/googleapis/google-api-python-client/commit/c9632ee831b9c135f3a0c018b3fdfe73d7e698a4 ([7357b05](https://www.github.com/googleapis/google-api-python-client/commit/7357b05a33a3780716b77161f86f247d92d91903)) - **osconfig:** update the api https://github.com/googleapis/google-api-python-client/commit/5dbaaad34dec45eb5f5a9e98710b3ec05b4d5429 ([8759538](https://www.github.com/googleapis/google-api-python-client/commit/8759538c0ab491be1678db74a3ad538957610d70)) - **pagespeedonline:** update the api https://github.com/googleapis/google-api-python-client/commit/47d41c544376b1911261410235b63ffe3e5faa91 ([8759538](https://www.github.com/googleapis/google-api-python-client/commit/8759538c0ab491be1678db74a3ad538957610d70)) - **privateca:** update the api https://github.com/googleapis/google-api-python-client/commit/8f7ad0d176d61f9e9a409d7fe35b20c5f1c239a5 ([8759538](https://www.github.com/googleapis/google-api-python-client/commit/8759538c0ab491be1678db74a3ad538957610d70)) - **realtimebidding:** update the api https://github.com/googleapis/google-api-python-client/commit/34d5d2606070b0c6fef053d6b88a65be085227b5 ([31fbcc0](https://www.github.com/googleapis/google-api-python-client/commit/31fbcc014f8642fb0cde7de47889b55a2eaf3f71)) - **sasportal:** update the api https://github.com/googleapis/google-api-python-client/commit/ca30eddc3d583c1851cc2f70f37c1d9f81f4342f ([50e1b7a](https://www.github.com/googleapis/google-api-python-client/commit/50e1b7a1b5c337926c5d2b2f648f057d67431cd6)) - **servicemanagement:** update the api https://github.com/googleapis/google-api-python-client/commit/491bafaefd792deae68c24337ebd7011faeb723b ([cb945f3](https://www.github.com/googleapis/google-api-python-client/commit/cb945f37130d2950801e02512761f061cef0b54e)) - **youtube:** update the api https://github.com/googleapis/google-api-python-client/commit/981cfb0ae51df0d2f48152bb74f79840ca19727a ([50e1b7a](https://www.github.com/googleapis/google-api-python-client/commit/50e1b7a1b5c337926c5d2b2f648f057d67431cd6)) ### [`v2.7.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​270-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev260v270-2021-06-01) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.6.0...v2.7.0) ##### Features - **adexchangebuyer:** update the api https://github.com/googleapis/google-api-python-client/commit/3cf7a8dceb567f3c89c307f3496c381af91b0fc6 ([ab1d6dc](https://www.github.com/googleapis/google-api-python-client/commit/ab1d6dc365fc482d482de197da7f7583afd04bd0)) - **admin:** update the api https://github.com/googleapis/google-api-python-client/commit/7bac81fc588ccbe7b5e6c75af52b719e73efd118 ([ab1d6dc](https://www.github.com/googleapis/google-api-python-client/commit/ab1d6dc365fc482d482de197da7f7583afd04bd0)) - **androidmanagement:** update the api https://github.com/googleapis/google-api-python-client/commit/877990251a43acbc447a1f2f963beb3bbfc6352f ([bdce941](https://www.github.com/googleapis/google-api-python-client/commit/bdce9419ca05d20e0eecd817f404f292a56ce79c)) - **apigee:** update the api https://github.com/googleapis/google-api-python-client/commit/37f31420ffc3adb1bdd23d7fc91f80701522aac8 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **bigquery:** update the api https://github.com/googleapis/google-api-python-client/commit/086d714317a73331fcfdf4027496c3b36354955f ([508c39f](https://www.github.com/googleapis/google-api-python-client/commit/508c39fa665c901d9d754aa31dc9d1af45469ec4)) - **container:** update the api https://github.com/googleapis/google-api-python-client/commit/514acdbf2c7eeaf6b1b9773c63b180131418ff57 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **content:** update the api https://github.com/googleapis/google-api-python-client/commit/aab557d6c59a5c414d0ac0bc6349763523c9816f ([ab1d6dc](https://www.github.com/googleapis/google-api-python-client/commit/ab1d6dc365fc482d482de197da7f7583afd04bd0)) - **content:** update the api https://github.com/googleapis/google-api-python-client/commit/eaf742d4e933744abc72c1808f1e5a16dccaa1d4 ([bdce941](https://www.github.com/googleapis/google-api-python-client/commit/bdce9419ca05d20e0eecd817f404f292a56ce79c)) - **dataflow:** update the api https://github.com/googleapis/google-api-python-client/commit/d979251cc4f8f537a875841cc0f6d86bbe0f195b ([38664e8](https://www.github.com/googleapis/google-api-python-client/commit/38664e8dec117413b8d27fc7230eb9c351d2c0de)) - **dfareporting:** update the api https://github.com/googleapis/google-api-python-client/commit/c83912bec60626d3388fbe749d7a395fa3bc6c22 ([ab1d6dc](https://www.github.com/googleapis/google-api-python-client/commit/ab1d6dc365fc482d482de197da7f7583afd04bd0)) - **dlp:** update the api https://github.com/googleapis/google-api-python-client/commit/7e3d1c4ab85d50307d42af3048f9a7dd47a2b9eb ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **documentai:** update the api https://github.com/googleapis/google-api-python-client/commit/222030d8c1583f49657862a308b5eae41311d7e7 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **doubleclickbidmanager:** update the api https://github.com/googleapis/google-api-python-client/commit/895ff465e58dffd1f6e29dffd673418c76007e1b ([ab1d6dc](https://www.github.com/googleapis/google-api-python-client/commit/ab1d6dc365fc482d482de197da7f7583afd04bd0)) - **firebase:** update the api https://github.com/googleapis/google-api-python-client/commit/6bd0412a11a1a55770415fdc76100b3c76a83a94 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **ondemandscanning:** update the api https://github.com/googleapis/google-api-python-client/commit/b77d12d24d17264123231dd86699fceada262440 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **osconfig:** update the api https://github.com/googleapis/google-api-python-client/commit/c541143744c4b077d0a044455a35d0de227a0bf6 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **prod_tt_sasportal:** update the api https://github.com/googleapis/google-api-python-client/commit/1e0f4a6e5e0bfde1ba4c06223d7fb02f63756690 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **redis:** update the api https://github.com/googleapis/google-api-python-client/commit/4350b35f065e8d651839ebcc047cfaec787b4f98 ([38664e8](https://www.github.com/googleapis/google-api-python-client/commit/38664e8dec117413b8d27fc7230eb9c351d2c0de)) - **serviceconsumermanagement:** update the api https://github.com/googleapis/google-api-python-client/commit/e2046363f037151e02020ea178651b814c11761a ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **servicecontrol:** update the api https://github.com/googleapis/google-api-python-client/commit/facd7ecc18c129cf8010d19d3969e8d5b4598dfc ([ab1d6dc](https://www.github.com/googleapis/google-api-python-client/commit/ab1d6dc365fc482d482de197da7f7583afd04bd0)) - **serviceusage:** update the api https://github.com/googleapis/google-api-python-client/commit/b79b21e71246ab6935214ca751125c83b1990167 ([4c9ccb0](https://www.github.com/googleapis/google-api-python-client/commit/4c9ccb08aa866b5402c5e63c70306b5a3c121ba1)) - **sqladmin:** update the api https://github.com/googleapis/google-api-python-client/commit/f2bb5e677634a0866836353bc40b26d40b1d044b ([a940762](https://www.github.com/googleapis/google-api-python-client/commit/a9407624e954e34bfd989f64ed0f5be74c40d4c5)) ##### Bug Fixes - resolve issue where certain artifacts would not be updated ([#​1385](https://www.github.com/googleapis/google-api-python-client/issues/1385)) ([31bbe51](https://www.github.com/googleapis/google-api-python-client/commit/31bbe51739f966491f1be8ab67c500c65c049daf))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 4a7d27a0..a7cacabf 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.6.0 +google-api-python-client==2.8.0 google-auth==1.31.0 google-auth-httplib2==0.1.0 From 788176feff5fb541e0d16f236b10b765d04ecb98 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 11 Jun 2021 12:10:07 -0400 Subject: [PATCH 019/254] docs: fix typos (#125) --- samples/v1/language_syntax_gcs.py | 2 +- samples/v1/language_syntax_text.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/v1/language_syntax_gcs.py b/samples/v1/language_syntax_gcs.py index 4e8a5cc4..32c64ede 100644 --- a/samples/v1/language_syntax_gcs.py +++ b/samples/v1/language_syntax_gcs.py @@ -62,7 +62,7 @@ def sample_analyze_syntax(gcs_content_uri): u"Location of this token in overall document: {}".format(text.begin_offset) ) # Get the part of speech information for this token. - # Parts of spech are as defined in: + # Part of speech is defined in: # http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf part_of_speech = token.part_of_speech # Get the tag, e.g. NOUN, ADJ for Adjective, et al. diff --git a/samples/v1/language_syntax_text.py b/samples/v1/language_syntax_text.py index c3eb9383..132c5779 100644 --- a/samples/v1/language_syntax_text.py +++ b/samples/v1/language_syntax_text.py @@ -61,7 +61,7 @@ def sample_analyze_syntax(text_content): u"Location of this token in overall document: {}".format(text.begin_offset) ) # Get the part of speech information for this token. - # Parts of spech are as defined in: + # Part of speech is defined in: # http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf part_of_speech = token.part_of_speech # Get the tag, e.g. NOUN, ADJ for Adjective, et al. From 92fa7f995013c302f3bd3eb6bec53d92d8d9990c Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 11 Jun 2021 12:14:06 -0400 Subject: [PATCH 020/254] chore: release as 2.1.0 (#126) Release-As: 2.1.0 From 397049ab8018ed5a708a676a935237f7ea039192 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 16 Jun 2021 14:52:02 +0200 Subject: [PATCH 021/254] chore(deps): update dependency google-api-python-client to v2.9.0 (#128) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==2.8.0` -> `==2.9.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.9.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.9.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.9.0/compatibility-slim/2.8.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.9.0/confidence-slim/2.8.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.9.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​290-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev280v290-2021-06-12) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.8.0...v2.9.0) ##### Features - **analyticsadmin:** update the api https://github.com/googleapis/google-api-python-client/commit/3ed78879365ebef411b2748be8b5d52c047210eb ([33237a8](https://www.github.com/googleapis/google-api-python-client/commit/33237a8250e3becfaa1e4b5f67ef0c887cfc44a9)) - **analyticsadmin:** update the api https://github.com/googleapis/google-api-python-client/commit/a715d2b2c5d5535f9317c5b3922350de2bfb883a ([0f0918f](https://www.github.com/googleapis/google-api-python-client/commit/0f0918f92a699753b52c77dd236ad84ee00a32a7)) - **apigee:** update the api https://github.com/googleapis/google-api-python-client/commit/9fcf80b4e92dca6ebc251781c69764e42aa186b3 ([0f0918f](https://www.github.com/googleapis/google-api-python-client/commit/0f0918f92a699753b52c77dd236ad84ee00a32a7)) - **appengine:** update the api https://github.com/googleapis/google-api-python-client/commit/ffcf86035a751e98a763c8a2d54b70d3a55ca14d ([26aa9e2](https://www.github.com/googleapis/google-api-python-client/commit/26aa9e282e30ca9c8797ee5346cbe9c0b9ca65a7)) - **chat:** update the api https://github.com/googleapis/google-api-python-client/commit/47ff8a5cac1b7dbd95c6f2b970a74629f700d4fc ([0f0918f](https://www.github.com/googleapis/google-api-python-client/commit/0f0918f92a699753b52c77dd236ad84ee00a32a7)) - **composer:** update the api https://github.com/googleapis/google-api-python-client/commit/4862529435851dbb106efa0311c2b7515d2ad2ea ([33237a8](https://www.github.com/googleapis/google-api-python-client/commit/33237a8250e3becfaa1e4b5f67ef0c887cfc44a9)) - **containeranalysis:** update the api https://github.com/googleapis/google-api-python-client/commit/9a1c70b7df3e074fc9fbd0eebdaf75a91046078c ([26aa9e2](https://www.github.com/googleapis/google-api-python-client/commit/26aa9e282e30ca9c8797ee5346cbe9c0b9ca65a7)) - **documentai:** update the api https://github.com/googleapis/google-api-python-client/commit/07a6e774ac185442a99437896eaee774946b5846 ([26aa9e2](https://www.github.com/googleapis/google-api-python-client/commit/26aa9e282e30ca9c8797ee5346cbe9c0b9ca65a7)) - **drive:** update the api https://github.com/googleapis/google-api-python-client/commit/773910fdf25b084aa3623d24fe99c8a1330fbecb ([26aa9e2](https://www.github.com/googleapis/google-api-python-client/commit/26aa9e282e30ca9c8797ee5346cbe9c0b9ca65a7)) - **genomics:** update the api https://github.com/googleapis/google-api-python-client/commit/8a1c8a67e7e5b76581cfa95ffa14c01019c305af ([33237a8](https://www.github.com/googleapis/google-api-python-client/commit/33237a8250e3becfaa1e4b5f67ef0c887cfc44a9)) - **gkehub:** update the api https://github.com/googleapis/google-api-python-client/commit/0fd49e0d39455077e39d850ac464635034d253b8 ([33237a8](https://www.github.com/googleapis/google-api-python-client/commit/33237a8250e3becfaa1e4b5f67ef0c887cfc44a9)) - **managedidentities:** update the api https://github.com/googleapis/google-api-python-client/commit/0927c1989574ae4272e4f753f4d55c88af62d8f2 ([c3f8675](https://www.github.com/googleapis/google-api-python-client/commit/c3f86757bccb6b42552f87d37a645651c58d6c7a)) - **managedidentities:** update the api https://github.com/googleapis/google-api-python-client/commit/e96adbb1ba3e4e56d916cc28474f85543f17ad0e ([26aa9e2](https://www.github.com/googleapis/google-api-python-client/commit/26aa9e282e30ca9c8797ee5346cbe9c0b9ca65a7)) - **spanner:** update the api https://github.com/googleapis/google-api-python-client/commit/87da2f3605ec1b8986324cddc33f2b5601d3e896 ([26aa9e2](https://www.github.com/googleapis/google-api-python-client/commit/26aa9e282e30ca9c8797ee5346cbe9c0b9ca65a7)) ##### Bug Fixes - update content-length header for next page ([#​1404](https://www.github.com/googleapis/google-api-python-client/issues/1404)) ([8019f2f](https://www.github.com/googleapis/google-api-python-client/commit/8019f2f96abc6a4375873becb2f17b399f738654)), closes [#​1403](https://www.github.com/googleapis/google-api-python-client/issues/1403)
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index a7cacabf..46527bb0 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.8.0 +google-api-python-client==2.9.0 google-auth==1.31.0 google-auth-httplib2==0.1.0 From 1026842f703160217f4874a8f9f26a3a30480e01 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 16 Jun 2021 12:58:02 +0000 Subject: [PATCH 022/254] chore: release 2.1.0 (#127) :robot: I have created a release \*beep\* \*boop\* --- ## [2.1.0](https://www.github.com/googleapis/python-language/compare/v1.4.0...v2.1.0) (2021-06-16) ### Features * add 'from_service_account_info' factory to clients ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) * add common resource helper methods; expose client transport ([#55](https://www.github.com/googleapis/python-language/issues/55)) ([8dde55c](https://www.github.com/googleapis/python-language/commit/8dde55cdd0e956c333039c0b74e49a06dd6ad33b)) * add from_service_account_info factory and fix sphinx identifiers ([#66](https://www.github.com/googleapis/python-language/issues/66)) ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) * support self-signed JWT flow for service accounts ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) ### Bug Fixes * add async client to %name_%version/init.py ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) * adds underscore to "type" to NL API samples ([#49](https://www.github.com/googleapis/python-language/issues/49)) ([36aa320](https://www.github.com/googleapis/python-language/commit/36aa320bf3e0018d66a7d0c91ce4733f20e9acc0)) * **deps:** add packaging requirement ([#113](https://www.github.com/googleapis/python-language/issues/113)) ([7e711ac](https://www.github.com/googleapis/python-language/commit/7e711ac63c95c1018d24c7c4db3bc02c191efcfc)) * fix sphinx identifiers ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) * remove client recv msg limit fix: add enums to `types/__init__.py` ([#62](https://www.github.com/googleapis/python-language/issues/62)) ([3476c0f](https://www.github.com/googleapis/python-language/commit/3476c0f72529cbcbe61ea5c7e6a22291777bed7e)) * use correct retry deadlines ([#83](https://www.github.com/googleapis/python-language/issues/83)) ([e2be2d8](https://www.github.com/googleapis/python-language/commit/e2be2d8ecf849940f2ea066655fda3bee68d8a74)) ### Documentation * fix typos ([#125](https://www.github.com/googleapis/python-language/issues/125)) ([788176f](https://www.github.com/googleapis/python-language/commit/788176feff5fb541e0d16f236b10b765d04ecb98)) ### Miscellaneous Chores * release as 2.1.0 ([#126](https://www.github.com/googleapis/python-language/issues/126)) ([92fa7f9](https://www.github.com/googleapis/python-language/commit/92fa7f995013c302f3bd3eb6bec53d92d8d9990c)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 30 ++++++++++++++++++++++++++++++ setup.py | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b5b2403..00186afc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,36 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.1.0](https://www.github.com/googleapis/python-language/compare/v1.4.0...v2.1.0) (2021-06-16) + + +### Features + +* add 'from_service_account_info' factory to clients ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) +* add common resource helper methods; expose client transport ([#55](https://www.github.com/googleapis/python-language/issues/55)) ([8dde55c](https://www.github.com/googleapis/python-language/commit/8dde55cdd0e956c333039c0b74e49a06dd6ad33b)) +* add from_service_account_info factory and fix sphinx identifiers ([#66](https://www.github.com/googleapis/python-language/issues/66)) ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) +* support self-signed JWT flow for service accounts ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) + + +### Bug Fixes + +* add async client to %name_%version/init.py ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) +* adds underscore to "type" to NL API samples ([#49](https://www.github.com/googleapis/python-language/issues/49)) ([36aa320](https://www.github.com/googleapis/python-language/commit/36aa320bf3e0018d66a7d0c91ce4733f20e9acc0)) +* **deps:** add packaging requirement ([#113](https://www.github.com/googleapis/python-language/issues/113)) ([7e711ac](https://www.github.com/googleapis/python-language/commit/7e711ac63c95c1018d24c7c4db3bc02c191efcfc)) +* fix sphinx identifiers ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) +* remove client recv msg limit fix: add enums to `types/__init__.py` ([#62](https://www.github.com/googleapis/python-language/issues/62)) ([3476c0f](https://www.github.com/googleapis/python-language/commit/3476c0f72529cbcbe61ea5c7e6a22291777bed7e)) +* use correct retry deadlines ([#83](https://www.github.com/googleapis/python-language/issues/83)) ([e2be2d8](https://www.github.com/googleapis/python-language/commit/e2be2d8ecf849940f2ea066655fda3bee68d8a74)) + + +### Documentation + +* fix typos ([#125](https://www.github.com/googleapis/python-language/issues/125)) ([788176f](https://www.github.com/googleapis/python-language/commit/788176feff5fb541e0d16f236b10b765d04ecb98)) + + +### Miscellaneous Chores + +* release as 2.1.0 ([#126](https://www.github.com/googleapis/python-language/issues/126)) ([92fa7f9](https://www.github.com/googleapis/python-language/commit/92fa7f995013c302f3bd3eb6bec53d92d8d9990c)) + ## [2.0.0](https://www.github.com/googleapis/python-language/compare/v1.3.0...v2.0.0) (2020-10-16) diff --git a/setup.py b/setup.py index c96cc6bc..4899a7c4 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.0.0" +version = "2.1.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 8cffbb7f7f8bed8dc93a85fd095b3d463fab5289 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 17 Jun 2021 10:52:29 +0000 Subject: [PATCH 023/254] chore: new owl bot post processor docker image (#129) Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:58c7342b0bccf85028100adaa3d856cb4a871c22ca9c01960d996e66c40548ce --- .github/.OwlBot.lock.yaml | 2 +- docs/conf.py | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index da616c91..ea06d395 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 + digest: sha256:58c7342b0bccf85028100adaa3d856cb4a871c22ca9c01960d996e66c40548ce diff --git a/docs/conf.py b/docs/conf.py index 485a6f6e..30faa8d1 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -80,9 +80,9 @@ master_doc = "index" # General information about the project. -project = u"google-cloud-language" -copyright = u"2019, Google" -author = u"Google APIs" +project = "google-cloud-language" +copyright = "2019, Google" +author = "Google APIs" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -281,7 +281,7 @@ ( master_doc, "google-cloud-language.tex", - u"google-cloud-language Documentation", + "google-cloud-language Documentation", author, "manual", ) @@ -316,7 +316,7 @@ ( master_doc, "google-cloud-language", - u"google-cloud-language Documentation", + "google-cloud-language Documentation", [author], 1, ) @@ -335,7 +335,7 @@ ( master_doc, "google-cloud-language", - u"google-cloud-language Documentation", + "google-cloud-language Documentation", author, "google-cloud-language", "google-cloud-language Library", From bc5f89e3d21bccd2d78ae3f2f4038b19db54871d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 19 Jun 2021 01:54:05 +0000 Subject: [PATCH 024/254] docs: omit mention of Python 2.7 in 'CONTRIBUTING.rst' (#1127) (#132) Source-Link: https://github.com/googleapis/synthtool/commit/b91f129527853d5b756146a0b5044481fb4e09a8 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:b6169fc6a5207b11800a7c002d0c5c2bc6d82697185ca12e666f44031468cfcd --- .github/.OwlBot.lock.yaml | 2 +- CONTRIBUTING.rst | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index ea06d395..cc49c6a3 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:58c7342b0bccf85028100adaa3d856cb4a871c22ca9c01960d996e66c40548ce + digest: sha256:b6169fc6a5207b11800a7c002d0c5c2bc6d82697185ca12e666f44031468cfcd diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 3938ab27..92891290 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -69,7 +69,6 @@ We use `nox `__ to instrument our tests. - To test your changes, run unit tests with ``nox``:: - $ nox -s unit-2.7 $ nox -s unit-3.8 $ ... @@ -144,7 +143,6 @@ Running System Tests # Run all system tests $ nox -s system-3.8 - $ nox -s system-2.7 # Run a single system test $ nox -s system-3.8 -- -k @@ -152,9 +150,8 @@ Running System Tests .. note:: - System tests are only configured to run under Python 2.7 and - Python 3.8. For expediency, we do not run them in older versions - of Python 3. + System tests are only configured to run under Python 3.8. + For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local auth settings and change some configuration in your project to From 0483d783d8c89ae57396dd9c68d8711c84d40685 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Sun, 20 Jun 2021 02:58:02 +0200 Subject: [PATCH 025/254] chore(deps): update dependency google-cloud-language to v2.1.0 (#130) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-cloud-language](https://togithub.com/googleapis/python-language) | `==2.0.0` -> `==2.1.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-cloud-language/2.1.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-cloud-language/2.1.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-cloud-language/2.1.0/compatibility-slim/2.0.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-cloud-language/2.1.0/confidence-slim/2.0.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/python-language ### [`v2.1.0`](https://togithub.com/googleapis/python-language/blob/master/CHANGELOG.md#​210-httpswwwgithubcomgoogleapispython-languagecomparev140v210-2021-06-16) [Compare Source](https://togithub.com/googleapis/python-language/compare/v2.0.0...v2.1.0) ##### Features - add 'from_service_account_info' factory to clients ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) - add common resource helper methods; expose client transport ([#​55](https://www.github.com/googleapis/python-language/issues/55)) ([8dde55c](https://www.github.com/googleapis/python-language/commit/8dde55cdd0e956c333039c0b74e49a06dd6ad33b)) - add from_service_account_info factory and fix sphinx identifiers ([#​66](https://www.github.com/googleapis/python-language/issues/66)) ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) - support self-signed JWT flow for service accounts ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) ##### Bug Fixes - add async client to %name\_%version/init.py ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) - adds underscore to "type" to NL API samples ([#​49](https://www.github.com/googleapis/python-language/issues/49)) ([36aa320](https://www.github.com/googleapis/python-language/commit/36aa320bf3e0018d66a7d0c91ce4733f20e9acc0)) - **deps:** add packaging requirement ([#​113](https://www.github.com/googleapis/python-language/issues/113)) ([7e711ac](https://www.github.com/googleapis/python-language/commit/7e711ac63c95c1018d24c7c4db3bc02c191efcfc)) - fix sphinx identifiers ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) - remove client recv msg limit fix: add enums to `types/__init__.py` ([#​62](https://www.github.com/googleapis/python-language/issues/62)) ([3476c0f](https://www.github.com/googleapis/python-language/commit/3476c0f72529cbcbe61ea5c7e6a22291777bed7e)) - use correct retry deadlines ([#​83](https://www.github.com/googleapis/python-language/issues/83)) ([e2be2d8](https://www.github.com/googleapis/python-language/commit/e2be2d8ecf849940f2ea066655fda3bee68d8a74)) ##### Documentation - fix typos ([#​125](https://www.github.com/googleapis/python-language/issues/125)) ([788176f](https://www.github.com/googleapis/python-language/commit/788176feff5fb541e0d16f236b10b765d04ecb98)) ##### Miscellaneous Chores - release as 2.1.0 ([#​126](https://www.github.com/googleapis/python-language/issues/126)) ([92fa7f9](https://www.github.com/googleapis/python-language/commit/92fa7f995013c302f3bd3eb6bec53d92d8d9990c))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 328dc7a5..5c6d9db7 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.0.0 +google-cloud-language==2.1.0 numpy==1.20.1; python_version > '3.6' numpy==1.19.5; python_version <= '3.6' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 83a8cba4..d79946ba 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.0.0 +google-cloud-language==2.1.0 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 83a8cba4..d79946ba 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.0.0 +google-cloud-language==2.1.0 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 83a8cba4..d79946ba 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.0.0 +google-cloud-language==2.1.0 From cc460bd068c4001e0b5fd774ca1fbf056f289be7 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sun, 20 Jun 2021 01:12:04 +0000 Subject: [PATCH 026/254] chore: update precommit hook pre-commit/pre-commit-hooks to v4 (#1083) (#134) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [pre-commit/pre-commit-hooks](https://togithub.com/pre-commit/pre-commit-hooks) | repository | major | `v3.4.0` -> `v4.0.1` | --- ### Release Notes
pre-commit/pre-commit-hooks ### [`v4.0.1`](https://togithub.com/pre-commit/pre-commit-hooks/releases/v4.0.1) [Compare Source](https://togithub.com/pre-commit/pre-commit-hooks/compare/v4.0.0...v4.0.1) ##### Fixes - `check-shebang-scripts-are-executable` fix entry point. - [#​602](https://togithub.com/pre-commit/pre-commit-hooks/issues/602) issue by [@​Person-93](https://togithub.com/Person-93). - [#​603](https://togithub.com/pre-commit/pre-commit-hooks/issues/603) PR by [@​scop](https://togithub.com/scop). ### [`v4.0.0`](https://togithub.com/pre-commit/pre-commit-hooks/releases/v4.0.0) [Compare Source](https://togithub.com/pre-commit/pre-commit-hooks/compare/v3.4.0...v4.0.0) ##### Features - `check-json`: report duplicate keys. - [#​558](https://togithub.com/pre-commit/pre-commit-hooks/issues/558) PR by [@​AdityaKhursale](https://togithub.com/AdityaKhursale). - [#​554](https://togithub.com/pre-commit/pre-commit-hooks/issues/554) issue by [@​adamchainz](https://togithub.com/adamchainz). - `no-commit-to-branch`: add `main` to default blocked branches. - [#​565](https://togithub.com/pre-commit/pre-commit-hooks/issues/565) PR by [@​ndevenish](https://togithub.com/ndevenish). - `check-case-conflict`: check conflicts in directory names as well. - [#​575](https://togithub.com/pre-commit/pre-commit-hooks/issues/575) PR by [@​slsyy](https://togithub.com/slsyy). - [#​70](https://togithub.com/pre-commit/pre-commit-hooks/issues/70) issue by [@​andyjack](https://togithub.com/andyjack). - `check-vcs-permalinks`: forbid other branch names. - [#​582](https://togithub.com/pre-commit/pre-commit-hooks/issues/582) PR by [@​jack1142](https://togithub.com/jack1142). - [#​581](https://togithub.com/pre-commit/pre-commit-hooks/issues/581) issue by [@​jack1142](https://togithub.com/jack1142). - `check-shebang-scripts-are-executable`: new hook which ensures shebang'd scripts are executable. - [#​545](https://togithub.com/pre-commit/pre-commit-hooks/issues/545) PR by [@​scop](https://togithub.com/scop). ##### Fixes - `check-executables-have-shebangs`: Short circuit shebang lookup on windows. - [#​544](https://togithub.com/pre-commit/pre-commit-hooks/issues/544) PR by [@​scop](https://togithub.com/scop). - `requirements-txt-fixer`: Fix comments which have indentation - [#​549](https://togithub.com/pre-commit/pre-commit-hooks/issues/549) PR by [@​greshilov](https://togithub.com/greshilov). - [#​548](https://togithub.com/pre-commit/pre-commit-hooks/issues/548) issue by [@​greshilov](https://togithub.com/greshilov). - `pretty-format-json`: write to stdout using UTF-8 encoding. - [#​571](https://togithub.com/pre-commit/pre-commit-hooks/issues/571) PR by [@​jack1142](https://togithub.com/jack1142). - [#​570](https://togithub.com/pre-commit/pre-commit-hooks/issues/570) issue by [@​jack1142](https://togithub.com/jack1142). - Use more inclusive language. - [#​599](https://togithub.com/pre-commit/pre-commit-hooks/issues/599) PR by [@​asottile](https://togithub.com/asottile). ##### Breaking changes - Remove deprecated hooks: `flake8`, `pyflakes`, `autopep8-wrapper`. - [#​597](https://togithub.com/pre-commit/pre-commit-hooks/issues/597) PR by [@​asottile](https://togithub.com/asottile).
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻️ **Rebasing**: Renovate will not automatically rebase this PR, because other commits have been found. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/synthtool). Source-Link: https://github.com/googleapis/synthtool/commit/333fd90856f1454380514bc59fc0936cdaf1c202 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:b8c131c558606d3cea6e18f8e87befbd448c1482319b0db3c5d5388fa6ea72e3 --- .github/.OwlBot.lock.yaml | 2 +- .pre-commit-config.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index cc49c6a3..9602d540 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:b6169fc6a5207b11800a7c002d0c5c2bc6d82697185ca12e666f44031468cfcd + digest: sha256:b8c131c558606d3cea6e18f8e87befbd448c1482319b0db3c5d5388fa6ea72e3 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4f00c7cf..62eb5a77 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.4.0 + rev: v4.0.1 hooks: - id: trailing-whitespace - id: end-of-file-fixer From 617738842d51e86cd0afa5d5689e0c2b9a038d4e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 22 Jun 2021 18:30:29 +0000 Subject: [PATCH 027/254] chore: add kokoro 3.9 config templates (#1128) (#136) Source-Link: https://github.com/googleapis/synthtool/commit/b0eb8a8b30b46a3c98d23c23107acb748c6601a1 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:df50e8d462f86d6bcb42f27ecad55bb12c404f1c65de9c6fe4c4d25120080bd6 --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/samples/python3.9/common.cfg | 40 +++++++++++++++++++++ .kokoro/samples/python3.9/continuous.cfg | 6 ++++ .kokoro/samples/python3.9/periodic-head.cfg | 11 ++++++ .kokoro/samples/python3.9/periodic.cfg | 6 ++++ .kokoro/samples/python3.9/presubmit.cfg | 6 ++++ 6 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 .kokoro/samples/python3.9/common.cfg create mode 100644 .kokoro/samples/python3.9/continuous.cfg create mode 100644 .kokoro/samples/python3.9/periodic-head.cfg create mode 100644 .kokoro/samples/python3.9/periodic.cfg create mode 100644 .kokoro/samples/python3.9/presubmit.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 9602d540..0954585f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:b8c131c558606d3cea6e18f8e87befbd448c1482319b0db3c5d5388fa6ea72e3 + digest: sha256:df50e8d462f86d6bcb42f27ecad55bb12c404f1c65de9c6fe4c4d25120080bd6 diff --git a/.kokoro/samples/python3.9/common.cfg b/.kokoro/samples/python3.9/common.cfg new file mode 100644 index 00000000..38c3cc08 --- /dev/null +++ b/.kokoro/samples/python3.9/common.cfg @@ -0,0 +1,40 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Specify which tests to run +env_vars: { + key: "RUN_TESTS_SESSION" + value: "py-3.9" +} + +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py39" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-language/.kokoro/test-samples.sh" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" +} + +# Download secrets for samples +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "python-language/.kokoro/trampoline.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.9/continuous.cfg b/.kokoro/samples/python3.9/continuous.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.9/continuous.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.9/periodic-head.cfg b/.kokoro/samples/python3.9/periodic-head.cfg new file mode 100644 index 00000000..f9cfcd33 --- /dev/null +++ b/.kokoro/samples/python3.9/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.9/periodic.cfg b/.kokoro/samples/python3.9/periodic.cfg new file mode 100644 index 00000000..50fec964 --- /dev/null +++ b/.kokoro/samples/python3.9/periodic.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "False" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.9/presubmit.cfg b/.kokoro/samples/python3.9/presubmit.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.9/presubmit.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file From 242aa5e997161104b760f554f69f2eecd86cd560 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 23 Jun 2021 20:24:43 +0000 Subject: [PATCH 028/254] feat: add always_use_jwt_access (#138) ... chore: update gapic-generator-ruby to the latest commit chore: release gapic-generator-typescript 1.5.0 Committer: @miraleung PiperOrigin-RevId: 380641501 Source-Link: https://github.com/googleapis/googleapis/commit/076f7e9f0b258bdb54338895d7251b202e8f0de3 Source-Link: https://github.com/googleapis/googleapis-gen/commit/27e4c88b4048e5f56508d4e1aa417d60a3380892 --- .coveragerc | 1 - .../language_service/transports/base.py | 40 +++---- .../language_service/transports/grpc.py | 7 +- .../transports/grpc_asyncio.py | 7 +- .../language_service/transports/base.py | 40 +++---- .../language_service/transports/grpc.py | 7 +- .../transports/grpc_asyncio.py | 7 +- setup.py | 2 +- testing/constraints-3.6.txt | 2 +- .../language_v1/test_language_service.py | 107 +++--------------- .../language_v1beta2/test_language_service.py | 107 +++--------------- 11 files changed, 76 insertions(+), 251 deletions(-) diff --git a/.coveragerc b/.coveragerc index 8aa27c09..a2e29fbf 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,7 +2,6 @@ branch = True [report] -fail_under = 100 show_missing = True omit = google/cloud/language/__init__.py diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 4f538035..183851d3 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.language_v1.types import language_service @@ -43,8 +44,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class LanguageServiceTransport(abc.ABC): """Abstract transport class for LanguageService.""" @@ -65,6 +64,7 @@ def __init__( scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +88,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -116,13 +118,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is 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. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +152,6 @@ def _get_scopes_kwargs( 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 = { diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 209156ba..079c61c1 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -150,6 +150,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -205,14 +206,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 1647c0e5..fe2cea52 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -79,14 +79,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - 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, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -196,6 +196,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 66de5600..c9f4b51c 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.language_v1beta2.types import language_service @@ -43,8 +44,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class LanguageServiceTransport(abc.ABC): """Abstract transport class for LanguageService.""" @@ -65,6 +64,7 @@ def __init__( scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +88,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -116,13 +118,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is 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. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +152,6 @@ def _get_scopes_kwargs( 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 = { diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 9083013f..7b471585 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -150,6 +150,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -205,14 +206,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 6b44fe14..9c23a3e5 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -79,14 +79,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - 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, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -196,6 +196,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/setup.py b/setup.py index 4899a7c4..e3503c0c 100644 --- a/setup.py +++ b/setup.py @@ -29,7 +29,7 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "google-api-core[grpc] >= 1.26.0, <2.0.0dev", "proto-plus >= 1.10.0", "packaging >= 14.3", ] diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index f462eab2..90b6c319 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -4,7 +4,7 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.22.2 +google-api-core==1.26.0 proto-plus==1.10.0 libcst==0.2.5 packaging==14.3 diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index a41f245d..6c3e890b 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -36,9 +36,6 @@ ) from google.cloud.language_v1.services.language_service import LanguageServiceClient from google.cloud.language_v1.services.language_service import transports -from google.cloud.language_v1.services.language_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.language_v1.services.language_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ 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 +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the 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"), @@ -59,16 +57,6 @@ 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(): return b"cert bytes", b"key bytes" @@ -131,6 +119,18 @@ def test_language_service_client_from_service_account_info(client_class): assert client.transport._host == "language.googleapis.com:443" +@pytest.mark.parametrize( + "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] +) +def test_language_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_called_with(True) + + @pytest.mark.parametrize( "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] ) @@ -1807,7 +1807,6 @@ def test_language_service_transport_auth_adc_old_google_auth(transport_class): (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 def test_language_service_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1839,82 +1838,6 @@ def test_language_service_transport_create_channel(transport_class, grpc_helpers ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LanguageServiceGrpcTransport, grpc_helpers), - (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_language_service_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( - "language.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LanguageServiceGrpcTransport, grpc_helpers), - (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_language_service_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( - "language.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", [ diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 17d28b09..ce020432 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -38,9 +38,6 @@ LanguageServiceClient, ) from google.cloud.language_v1beta2.services.language_service import transports -from google.cloud.language_v1beta2.services.language_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.language_v1beta2.services.language_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ 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 +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the 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"), @@ -61,16 +59,6 @@ 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(): return b"cert bytes", b"key bytes" @@ -133,6 +121,18 @@ def test_language_service_client_from_service_account_info(client_class): assert client.transport._host == "language.googleapis.com:443" +@pytest.mark.parametrize( + "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] +) +def test_language_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_called_with(True) + + @pytest.mark.parametrize( "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] ) @@ -1809,7 +1809,6 @@ def test_language_service_transport_auth_adc_old_google_auth(transport_class): (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 def test_language_service_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1841,82 +1840,6 @@ def test_language_service_transport_create_channel(transport_class, grpc_helpers ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LanguageServiceGrpcTransport, grpc_helpers), - (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_language_service_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( - "language.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LanguageServiceGrpcTransport, grpc_helpers), - (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_language_service_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( - "language.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", [ From 2d838f1f856f7b7b72d648cb9c4836e5d6359cf5 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 26 Jun 2021 11:38:10 +0000 Subject: [PATCH 029/254] chore(python): simplify nox steps in CONTRIBUTING.rst (#141) Source-Link: https://github.com/googleapis/synthtool/commit/26558bae8976a985d73c2d98c31d8612273f907d Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:99d90d097e4a4710cc8658ee0b5b963f4426d0e424819787c3ac1405c9a26719 --- .github/.OwlBot.lock.yaml | 2 +- CONTRIBUTING.rst | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0954585f..e2b39f94 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:df50e8d462f86d6bcb42f27ecad55bb12c404f1c65de9c6fe4c4d25120080bd6 + digest: sha256:99d90d097e4a4710cc8658ee0b5b963f4426d0e424819787c3ac1405c9a26719 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 92891290..750ac35c 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -68,14 +68,12 @@ Using ``nox`` We use `nox `__ to instrument our tests. - To test your changes, run unit tests with ``nox``:: + $ nox -s unit - $ nox -s unit-3.8 - $ ... +- To run a single unit test:: -- Args to pytest can be passed through the nox command separated by a `--`. For - example, to run a single test:: + $ nox -s unit-3.9 -- -k - $ nox -s unit-3.8 -- -k .. note:: @@ -142,7 +140,7 @@ Running System Tests - To run system tests, you can execute:: # Run all system tests - $ nox -s system-3.8 + $ nox -s system # Run a single system test $ nox -s system-3.8 -- -k @@ -215,8 +213,8 @@ Supported versions can be found in our ``noxfile.py`` `config`_. .. _config: https://github.com/googleapis/python-language/blob/master/noxfile.py -We also explicitly decided to support Python 3 beginning with version -3.6. Reasons for this include: +We also explicitly decided to support Python 3 beginning with version 3.6. +Reasons for this include: - Encouraging use of newest versions of Python 3 - Taking the lead of `prominent`_ open-source `projects`_ From 85d5e79c2122e82f1851c5dedddea93e6617b682 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Sat, 26 Jun 2021 13:42:10 +0200 Subject: [PATCH 030/254] chore(deps): update dependency google-api-python-client to v2.10.0 (#139) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==2.9.0` -> `==2.10.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.10.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.10.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.10.0/compatibility-slim/2.9.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.10.0/confidence-slim/2.9.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.10.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​2100-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev290v2100-2021-06-22) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.9.0...v2.10.0) ##### Features - **analyticsadmin:** update the api https://github.com/googleapis/google-api-python-client/commit/5a2e42e9a4631216c4883d5538c970a5faad59eb ([b1eafb3](https://www.github.com/googleapis/google-api-python-client/commit/b1eafb327669474d202bb2a430ed9e9561102db3)) - **androidmanagement:** update the api https://github.com/googleapis/google-api-python-client/commit/5fcc274bcd4a9a71a0a568e2771c443a2b2b20b0 ([b1eafb3](https://www.github.com/googleapis/google-api-python-client/commit/b1eafb327669474d202bb2a430ed9e9561102db3)) - **bigqueryreservation:** update the api https://github.com/googleapis/google-api-python-client/commit/63c00f6819408b943c2a7cc4bd2185828be173c6 ([3659137](https://www.github.com/googleapis/google-api-python-client/commit/365913780592552488cc5792d26b3f22b9e9ed1b)) - **dialogflow:** update the api https://github.com/googleapis/google-api-python-client/commit/512fc42343fa946889ec155456a05f0d64969903 ([b1eafb3](https://www.github.com/googleapis/google-api-python-client/commit/b1eafb327669474d202bb2a430ed9e9561102db3)) - **firebaserules:** update the api https://github.com/googleapis/google-api-python-client/commit/7b2000437a01ecd25e4ba571049f62c5b6dc9d63 ([3659137](https://www.github.com/googleapis/google-api-python-client/commit/365913780592552488cc5792d26b3f22b9e9ed1b)) - **iap:** update the api https://github.com/googleapis/google-api-python-client/commit/18550fd0501057584ef6d2fa329f09b75dad97d8 ([3659137](https://www.github.com/googleapis/google-api-python-client/commit/365913780592552488cc5792d26b3f22b9e9ed1b)) - **keep:** update the api https://github.com/googleapis/google-api-python-client/commit/45eb6dac450c1055a6ced84332529b70b0a8c831 ([b1eafb3](https://www.github.com/googleapis/google-api-python-client/commit/b1eafb327669474d202bb2a430ed9e9561102db3)) - **managedidentities:** update the api https://github.com/googleapis/google-api-python-client/commit/d2220014e787c2a2c90808cfd1e49a25cd783e72 ([3659137](https://www.github.com/googleapis/google-api-python-client/commit/365913780592552488cc5792d26b3f22b9e9ed1b)) ##### Bug Fixes - **smartdevicemanagement:** update the api https://github.com/googleapis/google-api-python-client/commit/772982044da691f9116073855e692f7793edacce ([b1eafb3](https://www.github.com/googleapis/google-api-python-client/commit/b1eafb327669474d202bb2a430ed9e9561102db3))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 46527bb0..9d43b1ba 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.9.0 +google-api-python-client==2.10.0 google-auth==1.31.0 google-auth-httplib2==0.1.0 From ae89d265a786a401bd31892a9be1656aeb49b266 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Sat, 26 Jun 2021 13:52:23 +0200 Subject: [PATCH 031/254] chore(deps): update dependency google-auth to v1.32.0 (#137) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-auth](https://togithub.com/googleapis/google-auth-library-python) | `==1.31.0` -> `==1.32.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.0/compatibility-slim/1.31.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.0/confidence-slim/1.31.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-auth-library-python ### [`v1.32.0`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1320-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1310v1320-2021-06-16) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.31.0...v1.32.0) ##### Features - allow scopes for self signed jwt ([#​776](https://www.github.com/googleapis/google-auth-library-python/issues/776)) ([2cfe655](https://www.github.com/googleapis/google-auth-library-python/commit/2cfe655bba837170abc07701557a1a5e0fe3294e))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 9d43b1ba..e9032aab 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.10.0 -google-auth==1.31.0 +google-auth==1.32.0 google-auth-httplib2==0.1.0 From 21c9d6e1a96707007bdcf23ce667f02b42c8a207 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 1 Jul 2021 02:20:09 +0000 Subject: [PATCH 032/254] fix: disable always_use_jwt_access (#143) Committer: @busunkim96 PiperOrigin-RevId: 382142900 Source-Link: https://github.com/googleapis/googleapis/commit/513440fda515f3c799c22a30e3906dcda325004e Source-Link: https://github.com/googleapis/googleapis-gen/commit/7b1e2c31233f79a704ec21ca410bf661d6bc68d0 --- .../language_service/transports/base.py | 2 +- .../language_service/transports/grpc.py | 5 ++- .../transports/grpc_asyncio.py | 5 ++- .../language_service/transports/base.py | 2 +- .../language_service/transports/grpc.py | 5 ++- .../transports/grpc_asyncio.py | 5 ++- .../language_v1/test_language_service.py | 35 ++++++++++++------- .../language_v1beta2/test_language_service.py | 35 ++++++++++++------- 8 files changed, 62 insertions(+), 32 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 183851d3..42537ea4 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -99,7 +99,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 079c61c1..a059ea93 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -98,6 +99,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -150,7 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index fe2cea52..4f849e85 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -104,6 +104,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -145,6 +146,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -196,7 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index c9f4b51c..38f98b34 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -99,7 +99,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 7b471585..ad25eaa4 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -98,6 +99,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -150,7 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 9c23a3e5..a141b4cb 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -104,6 +104,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -145,6 +146,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -196,7 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 6c3e890b..c6b8ffae 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -128,7 +128,25 @@ def test_language_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.LanguageServiceGrpcTransport, "grpc"), + (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_language_service_client_service_account_always_use_jwt_true( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) @pytest.mark.parametrize( @@ -1860,10 +1878,7 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1972,10 +1987,7 @@ def test_language_service_transport_channel_mtls_with_client_cert_source( "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -2022,10 +2034,7 @@ def test_language_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index ce020432..9cf4a9f2 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -130,7 +130,25 @@ def test_language_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.LanguageServiceGrpcTransport, "grpc"), + (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_language_service_client_service_account_always_use_jwt_true( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) @pytest.mark.parametrize( @@ -1862,10 +1880,7 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1974,10 +1989,7 @@ def test_language_service_transport_channel_mtls_with_client_cert_source( "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -2024,10 +2036,7 @@ def test_language_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ From 34face7ed224e389f72ed7cf3d052b5b142d4599 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 1 Jul 2021 09:13:23 -0700 Subject: [PATCH 033/254] chore: release 2.2.0 (#140) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 17 +++++++++++++++++ setup.py | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00186afc..5ea6668d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.2.0](https://www.github.com/googleapis/python-language/compare/v2.1.0...v2.2.0) (2021-07-01) + + +### Features + +* add always_use_jwt_access ([#138](https://www.github.com/googleapis/python-language/issues/138)) ([242aa5e](https://www.github.com/googleapis/python-language/commit/242aa5e997161104b760f554f69f2eecd86cd560)) + + +### Bug Fixes + +* disable always_use_jwt_access ([#143](https://www.github.com/googleapis/python-language/issues/143)) ([21c9d6e](https://www.github.com/googleapis/python-language/commit/21c9d6e1a96707007bdcf23ce667f02b42c8a207)) + + +### Documentation + +* omit mention of Python 2.7 in 'CONTRIBUTING.rst' ([#1127](https://www.github.com/googleapis/python-language/issues/1127)) ([#132](https://www.github.com/googleapis/python-language/issues/132)) ([bc5f89e](https://www.github.com/googleapis/python-language/commit/bc5f89e3d21bccd2d78ae3f2f4038b19db54871d)) + ## [2.1.0](https://www.github.com/googleapis/python-language/compare/v1.4.0...v2.1.0) (2021-06-16) diff --git a/setup.py b/setup.py index e3503c0c..f96d2c35 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.1.0" +version = "2.2.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 80d44431d650f7b6a3707cc6f096b749ebd0ec69 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 2 Jul 2021 20:15:20 +0200 Subject: [PATCH 034/254] chore(deps): update dependency google-cloud-language to v2.2.0 (#146) --- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 5c6d9db7..0020383c 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.1.0 +google-cloud-language==2.2.0 numpy==1.20.1; python_version > '3.6' numpy==1.19.5; python_version <= '3.6' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index d79946ba..62e406fc 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.1.0 +google-cloud-language==2.2.0 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index d79946ba..62e406fc 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.1.0 +google-cloud-language==2.2.0 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index d79946ba..62e406fc 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.1.0 +google-cloud-language==2.2.0 From c272d7c40e72e632bd9451581b0dc4e3b97a8065 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Sat, 3 Jul 2021 13:40:23 +0200 Subject: [PATCH 035/254] chore(deps): update dependency google-api-python-client to v2.11.0 (#144) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==2.10.0` -> `==2.11.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.11.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.11.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.11.0/compatibility-slim/2.10.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.11.0/confidence-slim/2.10.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.11.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​2110-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev2100v2110-2021-06-29) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.10.0...v2.11.0) ##### Features - **admin:** update the api https://github.com/googleapis/google-api-python-client/commit/1534f8926019f43dc87a29c1ca32191884556e3b ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **alertcenter:** update the api https://github.com/googleapis/google-api-python-client/commit/7a488d3f0deef3e1f106cff63b1e4f66ad1727bb ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **analyticsadmin:** update the api https://github.com/googleapis/google-api-python-client/commit/934358e5c041ffd1449e7c744463e61e94381ed5 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **analyticsdata:** update the api https://github.com/googleapis/google-api-python-client/commit/40f712130674cec09c1dd7560f69a330a335b226 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **androiddeviceprovisioning:** update the api https://github.com/googleapis/google-api-python-client/commit/81a0002a7051aeab647a3296fb18ce7973bf7137 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **apigee:** update the api https://github.com/googleapis/google-api-python-client/commit/2e6c78a93b2c0ee7001eb163ec95f9afc8f35575 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **appengine:** update the api https://github.com/googleapis/google-api-python-client/commit/125f74a61a94af17c01930841a79db46d3a059c5 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **bigquery:** update the api https://github.com/googleapis/google-api-python-client/commit/59c51e319602741632201d2ce61a6b03f13e4003 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **cloudasset:** update the api https://github.com/googleapis/google-api-python-client/commit/e615264971ccee6eb9b450fe3d85614209c0fee8 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **cloudbuild:** update the api https://github.com/googleapis/google-api-python-client/commit/ceddaccf23eb8b809688907cfdef8906cd77d65d ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **cloudidentity:** update the api https://github.com/googleapis/google-api-python-client/commit/22cd08b69b034c2cdfd854e1ac784f834539db3a ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **container:** update the api https://github.com/googleapis/google-api-python-client/commit/f494c63a42dc418559292c6269289317d9cebc23 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **documentai:** update the api https://github.com/googleapis/google-api-python-client/commit/e8aaabbc7670aefc4a745916fccb31424745f748 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **drive:** update the api https://github.com/googleapis/google-api-python-client/commit/72cab88ce591d906ea1cfcbe4dee354cccb623f2 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **file:** update the api https://github.com/googleapis/google-api-python-client/commit/0cd409a2d15c68aca3ea864400fc4772b9b4e503 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **firebaseappcheck:** update the api https://github.com/googleapis/google-api-python-client/commit/9a0131b2326327109d1ba7af97b1f4808dd7a898 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **healthcare:** update the api https://github.com/googleapis/google-api-python-client/commit/45ee6b28b86a43f44c707e15a7e06fdf8fce6a0f ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **ideahub:** update the api https://github.com/googleapis/google-api-python-client/commit/73b86d9d37f33aeaed74772d0319ba1350e54ed5 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **managedidentities:** update the api https://github.com/googleapis/google-api-python-client/commit/a07ed4558c93cb8f7fae49c7b353f46ccfea6c10 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **memcache:** update the api https://github.com/googleapis/google-api-python-client/commit/665ce5b47b9b3238dcfa201b9343bf6447df5994 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **metastore:** update the api https://github.com/googleapis/google-api-python-client/commit/9fd5ffbf37fb052323f5fa68d307c68391c519ac ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **ml:** update the api https://github.com/googleapis/google-api-python-client/commit/cf54d564915a558569c093287b448a7819e215f6 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **monitoring:** update the api https://github.com/googleapis/google-api-python-client/commit/d1ffbfc041f23f904cd8bc35a450871b2909473b ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **networkconnectivity:** update the api https://github.com/googleapis/google-api-python-client/commit/2cc462638aec61f4e775bfce883e725b104eeabb ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **notebooks:** update the api https://github.com/googleapis/google-api-python-client/commit/831ba938855aa4bdefafedf63e01af43350e7ed2 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **ondemandscanning:** update the api https://github.com/googleapis/google-api-python-client/commit/c04b4023477393cbb41984b14e0c734fc8587d45 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **paymentsresellersubscription:** update the api https://github.com/googleapis/google-api-python-client/commit/2cd5b1c2ef524f3ab00630508710cce7bee53574 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **prod_tt_sasportal:** update the api https://github.com/googleapis/google-api-python-client/commit/8b6bd24e57a79f470c750ad04052f79a3cafe0fa ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **realtimebidding:** update the api https://github.com/googleapis/google-api-python-client/commit/fd514dc8d86182dc17698f3293144928535f709c ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **reseller:** update the api https://github.com/googleapis/google-api-python-client/commit/20226c4401956732772e2a563c7920666135e605 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **sasportal:** update the api https://github.com/googleapis/google-api-python-client/commit/38d5156350b79a9933b2806f4bbe443043a33185 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **sts:** update the api https://github.com/googleapis/google-api-python-client/commit/190e13ebe5a4660d8825d3a8708559077a342bdf ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **transcoder:** update the api https://github.com/googleapis/google-api-python-client/commit/fbcacce6a17c1cae45b22f4a2058e730ec84b55a ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127)) - **youtube:** update the api https://github.com/googleapis/google-api-python-client/commit/5046950872559fe93b954dc9a4f71fd724176247 ([04bafe1](https://www.github.com/googleapis/google-api-python-client/commit/04bafe14efe7a6d1a7da03de89312062a4afa127))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index e9032aab..411e17cd 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.10.0 +google-api-python-client==2.11.0 google-auth==1.32.0 google-auth-httplib2==0.1.0 From 49256f910be5a588e095f5d2bf72743e491ab59c Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 7 Jul 2021 17:22:46 +0200 Subject: [PATCH 036/254] chore(deps): update dependency google-api-python-client to v2.12.0 (#147) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==2.11.0` -> `==2.12.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.12.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.12.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.12.0/compatibility-slim/2.11.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.12.0/confidence-slim/2.11.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.12.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​2120-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev2110v2120-2021-07-06) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.11.0...v2.12.0) ##### Features - **artifactregistry:** update the api https://github.com/googleapis/google-api-python-client/commit/bc9a38bf901a63525fb4c7b1e94fd4ce5fb441c3 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **chat:** update the api https://github.com/googleapis/google-api-python-client/commit/eea3c5c177aaded427fd3b5bab80812bf748ef79 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **cloudasset:** update the api https://github.com/googleapis/google-api-python-client/commit/2e31dd0b58d3c656df5aaa042994c637d0100f97 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **cloudbuild:** update the api https://github.com/googleapis/google-api-python-client/commit/3a3b420d53aabe1fdf6ddca483a3d164f72d6268 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **composer:** update the api https://github.com/googleapis/google-api-python-client/commit/78c0d8decbe640c522c45850c97002e7da12f4e0 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **container:** update the api https://github.com/googleapis/google-api-python-client/commit/a54737fe763fd288e54505faace58040cbf8920b ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **datafusion:** update the api https://github.com/googleapis/google-api-python-client/commit/f6bf3c6b92fbf7072798b987998bf55ee9276389 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **dataproc:** update the api https://github.com/googleapis/google-api-python-client/commit/3fde9a3604e4811ce02f1062dcee9cef35b1ad51 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **documentai:** update the api https://github.com/googleapis/google-api-python-client/commit/79c556d389889fb0f48c8cc5ad5ab4a2caaab603 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **groupssettings:** update the api https://github.com/googleapis/google-api-python-client/commit/d537f96a20a699629fa85fbdeadb74ead3b32699 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **logging:** update the api https://github.com/googleapis/google-api-python-client/commit/d3548c505e4b1065365584493d15f21a19639626 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **monitoring:** update the api https://github.com/googleapis/google-api-python-client/commit/d24af68a9621fda9d7a576d3615178604a1482d2 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **paymentsresellersubscription:** update the api https://github.com/googleapis/google-api-python-client/commit/cff9039529278d95cee936826b5406867c638430 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **redis:** update the api https://github.com/googleapis/google-api-python-client/commit/46102d1726393f872420820e6200bb83cefd74b6 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **run:** update the api https://github.com/googleapis/google-api-python-client/commit/db18e29c7f616f212121960fe8efd6fb7cdf9b22 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **slides:** update the api https://github.com/googleapis/google-api-python-client/commit/68634cd565914e6003c851ec5f43fa2ff290afca ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **spanner:** update the api https://github.com/googleapis/google-api-python-client/commit/289512124fc77a69957b912f06e9c3d315aa0526 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193)) - **storagetransfer:** update the api https://github.com/googleapis/google-api-python-client/commit/24895f156f10c03f2da686be95d8c70ea34008a3 ([a933dad](https://www.github.com/googleapis/google-api-python-client/commit/a933dad7e72d3093be480ce6af3965f41db1d193))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 411e17cd..517ba4af 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.11.0 +google-api-python-client==2.12.0 google-auth==1.32.0 google-auth-httplib2==0.1.0 From cb9751e51fae49df3d473b1854924e3e78a79e44 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Mon, 12 Jul 2021 22:08:11 +0200 Subject: [PATCH 037/254] chore(deps): update dependency google-auth to v1.32.1 (#145) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-auth](https://togithub.com/googleapis/google-auth-library-python) | `==1.32.0` -> `==1.32.1` | [![age](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.1/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.1/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.1/compatibility-slim/1.32.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-auth/1.32.1/confidence-slim/1.32.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-auth-library-python ### [`v1.32.1`](https://togithub.com/googleapis/google-auth-library-python/blob/master/CHANGELOG.md#​1321-httpswwwgithubcomgoogleapisgoogle-auth-library-pythoncomparev1320v1321-2021-06-30) [Compare Source](https://togithub.com/googleapis/google-auth-library-python/compare/v1.32.0...v1.32.1)
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Renovate will not automatically rebase this PR, because other commits have been found. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 517ba4af..db263f95 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.12.0 -google-auth==1.32.0 +google-auth==1.32.1 google-auth-httplib2==0.1.0 From d22cc9bdaaf432e0e5c747e84a4c2a3ec0d6956a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 14 Jul 2021 15:26:32 +0000 Subject: [PATCH 038/254] build(python): exit with success status if no samples found (#157) Source-Link: https://github.com/googleapis/synthtool/commit/53ea3896a52f87c758e79b5a19fa338c83925a98 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:e1793a23ae0ee9aafb2e3a53b564a351f74790dbe3c2d75f8fc3b8c43e5c036c --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/test-samples-impl.sh | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index e2b39f94..a5d3697f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:99d90d097e4a4710cc8658ee0b5b963f4426d0e424819787c3ac1405c9a26719 + digest: sha256:e1793a23ae0ee9aafb2e3a53b564a351f74790dbe3c2d75f8fc3b8c43e5c036c diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh index cf5de74c..311a8d54 100755 --- a/.kokoro/test-samples-impl.sh +++ b/.kokoro/test-samples-impl.sh @@ -20,9 +20,9 @@ set -eo pipefail # Enables `**` to include files nested inside sub-folders shopt -s globstar -# Exit early if samples directory doesn't exist -if [ ! -d "./samples" ]; then - echo "No tests run. `./samples` not found" +# Exit early if samples don't exist +if ! find samples -name 'requirements.txt' | grep -q .; then + echo "No tests run. './samples/**/requirements.txt' not found" exit 0 fi From 211a96820f8b5b708d8915d35b487ab54e895672 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 14 Jul 2021 17:56:42 +0000 Subject: [PATCH 039/254] build(python): remove python 3.7 from kokoro Dockerfile (#158) Source-Link: https://github.com/googleapis/synthtool/commit/e44dc0c742b1230887a73552357e0c18dcc30b92 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:5ff7446edeaede81c3ed58b23a4e76a5403fba1350ce28478045657303b6479d --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/docker/docs/Dockerfile | 35 ++------------------- .kokoro/docker/docs/fetch_gpg_keys.sh | 45 --------------------------- 3 files changed, 3 insertions(+), 79 deletions(-) delete mode 100755 .kokoro/docker/docs/fetch_gpg_keys.sh diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index a5d3697f..cb06536d 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:e1793a23ae0ee9aafb2e3a53b564a351f74790dbe3c2d75f8fc3b8c43e5c036c + digest: sha256:5ff7446edeaede81c3ed58b23a4e76a5403fba1350ce28478045657303b6479d diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile index 412b0b56..4e1b1fb8 100644 --- a/.kokoro/docker/docs/Dockerfile +++ b/.kokoro/docker/docs/Dockerfile @@ -40,6 +40,7 @@ RUN apt-get update \ libssl-dev \ libsqlite3-dev \ portaudio19-dev \ + python3-distutils \ redis-server \ software-properties-common \ ssh \ @@ -59,40 +60,8 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* \ && rm -f /var/cache/apt/archives/*.deb - -COPY fetch_gpg_keys.sh /tmp -# Install the desired versions of Python. -RUN set -ex \ - && export GNUPGHOME="$(mktemp -d)" \ - && echo "disable-ipv6" >> "${GNUPGHOME}/dirmngr.conf" \ - && /tmp/fetch_gpg_keys.sh \ - && for PYTHON_VERSION in 3.7.8 3.8.5; do \ - wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \ - && wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \ - && gpg --batch --verify python-${PYTHON_VERSION}.tar.xz.asc python-${PYTHON_VERSION}.tar.xz \ - && rm -r python-${PYTHON_VERSION}.tar.xz.asc \ - && mkdir -p /usr/src/python-${PYTHON_VERSION} \ - && tar -xJC /usr/src/python-${PYTHON_VERSION} --strip-components=1 -f python-${PYTHON_VERSION}.tar.xz \ - && rm python-${PYTHON_VERSION}.tar.xz \ - && cd /usr/src/python-${PYTHON_VERSION} \ - && ./configure \ - --enable-shared \ - # This works only on Python 2.7 and throws a warning on every other - # version, but seems otherwise harmless. - --enable-unicode=ucs4 \ - --with-system-ffi \ - --without-ensurepip \ - && make -j$(nproc) \ - && make install \ - && ldconfig \ - ; done \ - && rm -rf "${GNUPGHOME}" \ - && rm -rf /usr/src/python* \ - && rm -rf ~/.cache/ - RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ - && python3.7 /tmp/get-pip.py \ && python3.8 /tmp/get-pip.py \ && rm /tmp/get-pip.py -CMD ["python3.7"] +CMD ["python3.8"] diff --git a/.kokoro/docker/docs/fetch_gpg_keys.sh b/.kokoro/docker/docs/fetch_gpg_keys.sh deleted file mode 100755 index d653dd86..00000000 --- a/.kokoro/docker/docs/fetch_gpg_keys.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/bash -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# A script to fetch gpg keys with retry. -# Avoid jinja parsing the file. -# - -function retry { - if [[ "${#}" -le 1 ]]; then - echo "Usage: ${0} retry_count commands.." - exit 1 - fi - local retries=${1} - local command="${@:2}" - until [[ "${retries}" -le 0 ]]; do - $command && return 0 - if [[ $? -ne 0 ]]; then - echo "command failed, retrying" - ((retries--)) - fi - done - return 1 -} - -# 3.6.9, 3.7.5 (Ned Deily) -retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ - 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D - -# 3.8.0 (Łukasz Langa) -retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ - E3FF2839C048B25C084DEBE9B26995E310250568 - -# From b9f82a8c77d8e138cb0539c56e04d90300ed0576 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 16 Jul 2021 00:15:17 +0200 Subject: [PATCH 040/254] chore(deps): update dependency google-auth to v1.33.0 (#159) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index db263f95..0b69cc09 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.12.0 -google-auth==1.32.1 +google-auth==1.33.0 google-auth-httplib2==0.1.0 From 3e8e978aad3693aee58fd8c5c7082875fa806313 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 16 Jul 2021 16:06:23 +0200 Subject: [PATCH 041/254] chore(deps): update dependency google-api-python-client to v2.13.0 (#151) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==2.12.0` -> `==2.13.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.13.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.13.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.13.0/compatibility-slim/2.12.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.13.0/confidence-slim/2.12.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.13.0`](https://togithub.com/googleapis/google-api-python-client/blob/master/CHANGELOG.md#​2130-httpswwwgithubcomgoogleapisgoogle-api-python-clientcomparev2120v2130-2021-07-13) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.12.0...v2.13.0) ##### Features - **analyticsadmin:** update the api https://github.com/googleapis/google-api-python-client/commit/96675a8d9158ec13353fe241f858201fc51b784d ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **composer:** update the api https://github.com/googleapis/google-api-python-client/commit/add2fbdc3afb6696537eb087bc1d79df9194a37a ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **container:** update the api https://github.com/googleapis/google-api-python-client/commit/f8fae98db6d1943411b1a6c0f5a65dea336569f6 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **content:** update the api https://github.com/googleapis/google-api-python-client/commit/0814e009a4a11800db5b4afd7b6260e504c98047 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **datacatalog:** update the api https://github.com/googleapis/google-api-python-client/commit/99706059e58bb3d616253a1af2cd162b5a0b0279 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **dataflow:** update the api https://github.com/googleapis/google-api-python-client/commit/d5f09ef30392532bcfdd82901148bdd3ac6eec01 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **docs:** update the api https://github.com/googleapis/google-api-python-client/commit/dc66f4cafba86baff6149b2f6e59ae1888006911 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **file:** update the api https://github.com/googleapis/google-api-python-client/commit/523fc5c900f53489d56400deb650f6586c9681a0 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **firebasehosting:** update the api https://github.com/googleapis/google-api-python-client/commit/c83ac386b65f82e7ba29851d56b496b09a29cf98 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **healthcare:** update the api https://github.com/googleapis/google-api-python-client/commit/a407471b14349b8c08018196041568f2a35f8d4f ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **ideahub:** update the api https://github.com/googleapis/google-api-python-client/commit/c6b0d83940f238b1330896240492e8db397dcd15 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **managedidentities:** update the api https://github.com/googleapis/google-api-python-client/commit/863b333da7848029fd1614fd48b46cfbe12afcd5 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **memcache:** update the api https://github.com/googleapis/google-api-python-client/commit/17dc001e4649f54944066ce153e3c552c850a146 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **metastore:** update the api https://github.com/googleapis/google-api-python-client/commit/f3a76c9359babc48cc0b76ce7e3be0711ba028ae ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **slides:** update the api https://github.com/googleapis/google-api-python-client/commit/314d61b9ef8c5c30f9756462504dc0df92284cb2 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **sqladmin:** update the api https://github.com/googleapis/google-api-python-client/commit/62784e0b1b5752b480afe1ddd77dcf412bb35dbb ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **tpu:** update the api https://github.com/googleapis/google-api-python-client/commit/16bf712cca4a393d96e4135de3d02e5005051b6d ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) - **youtube:** update the api https://github.com/googleapis/google-api-python-client/commit/ec21dff96d9538ad6c7f9b318eca88178533aa95 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) ##### Bug Fixes - **keep:** update the api https://github.com/googleapis/google-api-python-client/commit/08fee732e96d3220e624c8fca7b8a9b0c0bcb146 ([1a4514d](https://www.github.com/googleapis/google-api-python-client/commit/1a4514d2862f81fc97e424cd550c286cda0fc859)) ##### Documentation - add recommendation to use v2.x and static discovery artifacts ([#​1434](https://www.github.com/googleapis/google-api-python-client/issues/1434)) ([ca7328c](https://www.github.com/googleapis/google-api-python-client/commit/ca7328cb5340ea282a3d98782926a0b6881a33ed))
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 0b69cc09..3e6cecbd 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.12.0 +google-api-python-client==2.13.0 google-auth==1.33.0 google-auth-httplib2==0.1.0 From f8f90924ca4332016d5bbd9ed131cc82f07c7f9f Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Tue, 20 Jul 2021 03:44:23 -0600 Subject: [PATCH 042/254] fix(deps): pin 'google-{api,cloud}-core', 'google-auth' to allow 2.x versions (#160) Expand pins on library dependencies in preparation for these dependencies taking a new major version. See https://github.com/googleapis/google-cloud-python/issues/10566. --- setup.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index f96d2c35..9eccb4f5 100644 --- a/setup.py +++ b/setup.py @@ -29,7 +29,10 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.26.0, <2.0.0dev", + # NOTE: Maintainers, please do not require google-api-core>=2.x.x + # Until this issue is closed + # https://github.com/googleapis/google-cloud-python/issues/10566 + "google-api-core[grpc] >= 1.26.0, <3.0.0dev", "proto-plus >= 1.10.0", "packaging >= 14.3", ] From 16530e9ab84d8d1a93b8d785e58cc6c963370ead Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 21 Jul 2021 23:02:14 +0000 Subject: [PATCH 043/254] chore: release 2.2.1 (#162) :robot: I have created a release \*beep\* \*boop\* --- ### [2.2.1](https://www.github.com/googleapis/python-language/compare/v2.2.0...v2.2.1) (2021-07-20) ### Bug Fixes * **deps:** pin 'google-{api,cloud}-core', 'google-auth' to allow 2.x versions ([#160](https://www.github.com/googleapis/python-language/issues/160)) ([f8f9092](https://www.github.com/googleapis/python-language/commit/f8f90924ca4332016d5bbd9ed131cc82f07c7f9f)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 7 +++++++ setup.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ea6668d..c2a51aa1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +### [2.2.1](https://www.github.com/googleapis/python-language/compare/v2.2.0...v2.2.1) (2021-07-20) + + +### Bug Fixes + +* **deps:** pin 'google-{api,cloud}-core', 'google-auth' to allow 2.x versions ([#160](https://www.github.com/googleapis/python-language/issues/160)) ([f8f9092](https://www.github.com/googleapis/python-language/commit/f8f90924ca4332016d5bbd9ed131cc82f07c7f9f)) + ## [2.2.0](https://www.github.com/googleapis/python-language/compare/v2.1.0...v2.2.0) (2021-07-01) diff --git a/setup.py b/setup.py index 9eccb4f5..331d926b 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.2.0" +version = "2.2.1" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 5c28a169c9723fec23fac8bb5e2aa9e0dd420c66 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 22 Jul 2021 13:52:23 +0000 Subject: [PATCH 044/254] feat: add Samples section to CONTRIBUTING.rst (#161) Source-Link: https://github.com/googleapis/synthtool/commit/52e4e46eff2a0b70e3ff5506a02929d089d077d4 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:6186535cbdbf6b9fe61f00294929221d060634dae4a0795c1cefdbc995b2d605 --- .github/.OwlBot.lock.yaml | 2 +- CONTRIBUTING.rst | 24 +++++++++++++++++++ samples/snippets/api/noxfile.py | 5 ++-- samples/snippets/classify_text/noxfile.py | 5 ++-- samples/snippets/cloud-client/v1/noxfile.py | 5 ++-- .../snippets/generated-samples/v1/noxfile.py | 5 ++-- samples/snippets/sentiment/noxfile.py | 5 ++-- 7 files changed, 40 insertions(+), 11 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index cb06536d..d57f7420 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:5ff7446edeaede81c3ed58b23a4e76a5403fba1350ce28478045657303b6479d + digest: sha256:6186535cbdbf6b9fe61f00294929221d060634dae4a0795c1cefdbc995b2d605 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 750ac35c..755aea73 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -177,6 +177,30 @@ Build the docs via: $ nox -s docs +************************* +Samples and code snippets +************************* + +Code samples and snippets live in the `samples/` catalogue. Feel free to +provide more examples, but make sure to write tests for those examples. +Each folder containing example code requires its own `noxfile.py` script +which automates testing. If you decide to create a new folder, you can +base it on the `samples/snippets` folder (providing `noxfile.py` and +the requirements files). + +The tests will run against a real Google Cloud Project, so you should +configure them just like the System Tests. + +- To run sample tests, you can execute:: + + # Run all tests in a folder + $ cd samples/snippets + $ nox -s py-3.8 + + # Run a single sample test + $ cd samples/snippets + $ nox -s py-3.8 -- -k + ******************************************** Note About ``README`` as it pertains to PyPI ******************************************** diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 5ff9e1db..6a8ccdae 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -28,8 +28,9 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -# Copy `noxfile_config.py` to your directory and modify it instead. +BLACK_VERSION = "black==19.10b0" +# Copy `noxfile_config.py` to your directory and modify it instead. # `TEST_CONFIG` dict is a configuration hook that allows users to # modify the test configurations. The values here should be in sync @@ -159,7 +160,7 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: - session.install("black") + session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 5ff9e1db..6a8ccdae 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -28,8 +28,9 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -# Copy `noxfile_config.py` to your directory and modify it instead. +BLACK_VERSION = "black==19.10b0" +# Copy `noxfile_config.py` to your directory and modify it instead. # `TEST_CONFIG` dict is a configuration hook that allows users to # modify the test configurations. The values here should be in sync @@ -159,7 +160,7 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: - session.install("black") + session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 5ff9e1db..6a8ccdae 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -28,8 +28,9 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -# Copy `noxfile_config.py` to your directory and modify it instead. +BLACK_VERSION = "black==19.10b0" +# Copy `noxfile_config.py` to your directory and modify it instead. # `TEST_CONFIG` dict is a configuration hook that allows users to # modify the test configurations. The values here should be in sync @@ -159,7 +160,7 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: - session.install("black") + session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 5ff9e1db..6a8ccdae 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -28,8 +28,9 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -# Copy `noxfile_config.py` to your directory and modify it instead. +BLACK_VERSION = "black==19.10b0" +# Copy `noxfile_config.py` to your directory and modify it instead. # `TEST_CONFIG` dict is a configuration hook that allows users to # modify the test configurations. The values here should be in sync @@ -159,7 +160,7 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: - session.install("black") + session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 5ff9e1db..6a8ccdae 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -28,8 +28,9 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -# Copy `noxfile_config.py` to your directory and modify it instead. +BLACK_VERSION = "black==19.10b0" +# Copy `noxfile_config.py` to your directory and modify it instead. # `TEST_CONFIG` dict is a configuration hook that allows users to # modify the test configurations. The values here should be in sync @@ -159,7 +160,7 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: - session.install("black") + session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) From 2ebe4fa6c9dee80994b49cfb7e276addbef4ec0f Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 23 Jul 2021 15:38:38 +0000 Subject: [PATCH 045/254] chore: fix kokoro config for samples (#167) Source-Link: https://github.com/googleapis/synthtool/commit/dd05f9d12f134871c9e45282349c9856fbebecdd Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:aea14a583128771ae8aefa364e1652f3c56070168ef31beb203534222d842b8b --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/samples/python3.6/periodic-head.cfg | 2 +- .kokoro/samples/python3.7/periodic-head.cfg | 2 +- .kokoro/samples/python3.8/periodic-head.cfg | 2 +- .kokoro/samples/python3.9/periodic-head.cfg | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index d57f7420..9ee60f7e 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:6186535cbdbf6b9fe61f00294929221d060634dae4a0795c1cefdbc995b2d605 + digest: sha256:aea14a583128771ae8aefa364e1652f3c56070168ef31beb203534222d842b8b diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg index f9cfcd33..676f8aa8 100644 --- a/.kokoro/samples/python3.6/periodic-head.cfg +++ b/.kokoro/samples/python3.6/periodic-head.cfg @@ -7,5 +7,5 @@ env_vars: { env_vars: { key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" + value: "github/python-language/.kokoro/test-samples-against-head.sh" } diff --git a/.kokoro/samples/python3.7/periodic-head.cfg b/.kokoro/samples/python3.7/periodic-head.cfg index f9cfcd33..676f8aa8 100644 --- a/.kokoro/samples/python3.7/periodic-head.cfg +++ b/.kokoro/samples/python3.7/periodic-head.cfg @@ -7,5 +7,5 @@ env_vars: { env_vars: { key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" + value: "github/python-language/.kokoro/test-samples-against-head.sh" } diff --git a/.kokoro/samples/python3.8/periodic-head.cfg b/.kokoro/samples/python3.8/periodic-head.cfg index f9cfcd33..676f8aa8 100644 --- a/.kokoro/samples/python3.8/periodic-head.cfg +++ b/.kokoro/samples/python3.8/periodic-head.cfg @@ -7,5 +7,5 @@ env_vars: { env_vars: { key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" + value: "github/python-language/.kokoro/test-samples-against-head.sh" } diff --git a/.kokoro/samples/python3.9/periodic-head.cfg b/.kokoro/samples/python3.9/periodic-head.cfg index f9cfcd33..676f8aa8 100644 --- a/.kokoro/samples/python3.9/periodic-head.cfg +++ b/.kokoro/samples/python3.9/periodic-head.cfg @@ -7,5 +7,5 @@ env_vars: { env_vars: { key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" + value: "github/python-language/.kokoro/test-samples-against-head.sh" } From 4249607b20905b54b14e84d313838e46727bad54 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 24 Jul 2021 10:16:39 +0000 Subject: [PATCH 046/254] fix: enable self signed jwt for grpc (#168) PiperOrigin-RevId: 386504689 Source-Link: https://github.com/googleapis/googleapis/commit/762094a99ac6e03a17516b13dfbef37927267a70 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6bfc480e1a161d5de121c2bcc3745885d33b265a --- .../services/language_service/client.py | 4 +++ .../services/language_service/client.py | 4 +++ .../language_v1/test_language_service.py | 31 +++++++++++-------- .../language_v1beta2/test_language_service.py | 31 +++++++++++-------- 4 files changed, 44 insertions(+), 26 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index a86da109..eb724c09 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -329,6 +329,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def analyze_sentiment( diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 080e5909..70fc8afc 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -329,6 +329,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def analyze_sentiment( diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index c6b8ffae..1f4dcf06 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -119,18 +119,6 @@ def test_language_service_client_from_service_account_info(client_class): assert client.transport._host == "language.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] -) -def test_language_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -138,7 +126,7 @@ def test_language_service_client_service_account_always_use_jwt(client_class): (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_language_service_client_service_account_always_use_jwt_true( +def test_language_service_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -148,6 +136,13 @@ def test_language_service_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize( "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] @@ -228,6 +223,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -244,6 +240,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -260,6 +257,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -288,6 +286,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -364,6 +363,7 @@ def test_language_service_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -397,6 +397,7 @@ def test_language_service_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -418,6 +419,7 @@ def test_language_service_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -448,6 +450,7 @@ def test_language_service_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -478,6 +481,7 @@ def test_language_service_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -497,6 +501,7 @@ def test_language_service_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 9cf4a9f2..71d88d17 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -121,18 +121,6 @@ def test_language_service_client_from_service_account_info(client_class): assert client.transport._host == "language.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] -) -def test_language_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -140,7 +128,7 @@ def test_language_service_client_service_account_always_use_jwt(client_class): (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_language_service_client_service_account_always_use_jwt_true( +def test_language_service_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -150,6 +138,13 @@ def test_language_service_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize( "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] @@ -230,6 +225,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -246,6 +242,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -262,6 +259,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -290,6 +288,7 @@ def test_language_service_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -366,6 +365,7 @@ def test_language_service_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -399,6 +399,7 @@ def test_language_service_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -420,6 +421,7 @@ def test_language_service_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -450,6 +452,7 @@ def test_language_service_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -480,6 +483,7 @@ def test_language_service_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -499,6 +503,7 @@ def test_language_service_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) From 5c4bd4642bacd3a19104442a3b8a1ab8d79b254c Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 27 Jul 2021 12:58:17 +0200 Subject: [PATCH 047/254] chore(deps): update dependency google-api-python-client to v2.14.1 (#163) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 3e6cecbd..6274782d 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.13.0 +google-api-python-client==2.14.1 google-auth==1.33.0 google-auth-httplib2==0.1.0 From ed3538b5c445c156a76e134d67e9e2f6b3c48762 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 27 Jul 2021 13:32:53 +0200 Subject: [PATCH 048/254] chore(deps): update dependency google-auth to v1.33.1 (#164) Co-authored-by: Anthonios Partheniou --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 6274782d..cbc34d89 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.14.1 -google-auth==1.33.0 +google-auth==1.33.1 google-auth-httplib2==0.1.0 From 7c1cc6ba9cca4101fae3cc6cca8a1fb0561cd317 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 27 Jul 2021 13:33:13 +0200 Subject: [PATCH 049/254] chore(deps): update dependency google-cloud-language to v2.2.1 (#165) --- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 0020383c..fc435773 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.2.0 +google-cloud-language==2.2.1 numpy==1.20.1; python_version > '3.6' numpy==1.19.5; python_version <= '3.6' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 62e406fc..7e8a9a02 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.0 +google-cloud-language==2.2.1 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 62e406fc..7e8a9a02 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.0 +google-cloud-language==2.2.1 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 62e406fc..7e8a9a02 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.0 +google-cloud-language==2.2.1 From 327260e408f85b757185541288306fb09b90f0ac Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 27 Jul 2021 13:42:19 +0200 Subject: [PATCH 050/254] chore(deps): update dependency google-api-python-client to v2.15.0 (#169) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index cbc34d89..59994db0 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.14.1 +google-api-python-client==2.15.0 google-auth==1.33.1 google-auth-httplib2==0.1.0 From 89acb62ea8f1f0f82fc080bbfbde39d43294e0c4 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 28 Jul 2021 12:59:27 +0200 Subject: [PATCH 051/254] chore(deps): update dependency google-auth to v1.34.0 (#171) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 59994db0..bb55768a 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.15.0 -google-auth==1.33.1 +google-auth==1.34.0 google-auth-httplib2==0.1.0 From 4d400539508ec81cbc76e3f6166e3ec86054ed65 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 28 Jul 2021 06:59:40 -0400 Subject: [PATCH 052/254] chore: release as 2.2.2 (#170) Release-As: 2.2.2 From 9a22c3dc547ab221a0179c962b17c86912ca82b5 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 28 Jul 2021 11:10:16 +0000 Subject: [PATCH 053/254] chore: release 2.2.2 (#172) :robot: I have created a release \*beep\* \*boop\* --- ### [2.2.2](https://www.github.com/googleapis/python-language/compare/v2.2.1...v2.2.2) (2021-07-28) ### Bug Fixes * enable self signed jwt for grpc ([#168](https://www.github.com/googleapis/python-language/issues/168)) ([4249607](https://www.github.com/googleapis/python-language/commit/4249607b20905b54b14e84d313838e46727bad54)) ### Documentation * add Samples section to CONTRIBUTING.rst ([#161](https://www.github.com/googleapis/python-language/issues/161)) ([5c28a16](https://www.github.com/googleapis/python-language/commit/5c28a169c9723fec23fac8bb5e2aa9e0dd420c66)) ### Miscellaneous Chores * release as 2.2.2 ([#170](https://www.github.com/googleapis/python-language/issues/170)) ([4d40053](https://www.github.com/googleapis/python-language/commit/4d400539508ec81cbc76e3f6166e3ec86054ed65)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 17 +++++++++++++++++ setup.py | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2a51aa1..0214571a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ [1]: https://pypi.org/project/google-cloud-language/#history +### [2.2.2](https://www.github.com/googleapis/python-language/compare/v2.2.1...v2.2.2) (2021-07-28) + + +### Bug Fixes + +* enable self signed jwt for grpc ([#168](https://www.github.com/googleapis/python-language/issues/168)) ([4249607](https://www.github.com/googleapis/python-language/commit/4249607b20905b54b14e84d313838e46727bad54)) + + +### Documentation + +* add Samples section to CONTRIBUTING.rst ([#161](https://www.github.com/googleapis/python-language/issues/161)) ([5c28a16](https://www.github.com/googleapis/python-language/commit/5c28a169c9723fec23fac8bb5e2aa9e0dd420c66)) + + +### Miscellaneous Chores + +* release as 2.2.2 ([#170](https://www.github.com/googleapis/python-language/issues/170)) ([4d40053](https://www.github.com/googleapis/python-language/commit/4d400539508ec81cbc76e3f6166e3ec86054ed65)) + ### [2.2.1](https://www.github.com/googleapis/python-language/compare/v2.2.0...v2.2.1) (2021-07-20) diff --git a/setup.py b/setup.py index 331d926b..6d7a1acb 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.2.1" +version = "2.2.2" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From c952f272109d8ae8b70f66f0f887c86c56831537 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 28 Jul 2021 16:52:52 +0200 Subject: [PATCH 054/254] chore(deps): update dependency google-cloud-language to v2.2.2 (#173) --- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index fc435773..2323f5be 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.2.1 +google-cloud-language==2.2.2 numpy==1.20.1; python_version > '3.6' numpy==1.19.5; python_version <= '3.6' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 7e8a9a02..fc0ee401 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.1 +google-cloud-language==2.2.2 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 7e8a9a02..fc0ee401 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.1 +google-cloud-language==2.2.2 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 7e8a9a02..fc0ee401 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.1 +google-cloud-language==2.2.2 From 9723fac252b88982694ff78eee19491e7d285708 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Mon, 2 Aug 2021 16:42:50 -0600 Subject: [PATCH 055/254] chore: require CODEOWNER review and up to date branches (#174) These two lines bring the rules on this repo in line with the defaults: https://github.com/googleapis/repo-automation-bots/blob/63c858e539e1f4d9bb8ea66e12f9c0a0de5fef55/packages/sync-repo-settings/src/required-checks.json#L40-L50 --- .github/sync-repo-settings.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index af599353..0ddb512d 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -4,6 +4,8 @@ branchProtectionRules: # Identifies the protection rule pattern. Name of the branch to be protected. # Defaults to `master` - pattern: master + requiresCodeOwnerReviews: true + requiresStrictStatusChecks: true requiredStatusCheckContexts: - 'Kokoro' - 'cla/google' From 12fa21fb2024f6f9acde094f410d30ed5ea994e5 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 11 Aug 2021 16:32:30 +0000 Subject: [PATCH 056/254] chore: fix INSTALL_LIBRARY_FROM_SOURCE in noxfile.py (#175) Source-Link: https://github.com/googleapis/synthtool/commit/6252f2cd074c38f37b44abe5e96d128733eb1b61 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:50e35228649c47b6ca82aa0be3ff9eb2afce51c82b66c4a03fe4afeb5ff6c0fc --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 2 +- samples/snippets/classify_text/noxfile.py | 2 +- samples/snippets/cloud-client/v1/noxfile.py | 2 +- samples/snippets/generated-samples/v1/noxfile.py | 2 +- samples/snippets/sentiment/noxfile.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 9ee60f7e..649877dc 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:aea14a583128771ae8aefa364e1652f3c56070168ef31beb203534222d842b8b + digest: sha256:50e35228649c47b6ca82aa0be3ff9eb2afce51c82b66c4a03fe4afeb5ff6c0fc diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 6a8ccdae..125bb619 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -96,7 +96,7 @@ def get_pytest_env_vars() -> Dict[str, str]: TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") # # Style Checks # diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 6a8ccdae..125bb619 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -96,7 +96,7 @@ def get_pytest_env_vars() -> Dict[str, str]: TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") # # Style Checks # diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 6a8ccdae..125bb619 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -96,7 +96,7 @@ def get_pytest_env_vars() -> Dict[str, str]: TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") # # Style Checks # diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 6a8ccdae..125bb619 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -96,7 +96,7 @@ def get_pytest_env_vars() -> Dict[str, str]: TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") # # Style Checks # diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 6a8ccdae..125bb619 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -96,7 +96,7 @@ def get_pytest_env_vars() -> Dict[str, str]: TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") # # Style Checks # From 559e48ee1e4f7fa19f277b3a86ac1e0ee17118cf Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 12 Aug 2021 16:40:13 +0000 Subject: [PATCH 057/254] chore(python): avoid `.nox` directories when building docs (#176) Source-Link: https://github.com/googleapis/synthtool/commit/7e1f6da50524b5d98eb67adbf6dd0805df54233d Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:a1a891041baa4ffbe1a809ac1b8b9b4a71887293c9101c88e8e255943c5aec2d --- .github/.OwlBot.lock.yaml | 2 +- docs/conf.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 649877dc..b771c37c 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:50e35228649c47b6ca82aa0be3ff9eb2afce51c82b66c4a03fe4afeb5ff6c0fc + digest: sha256:a1a891041baa4ffbe1a809ac1b8b9b4a71887293c9101c88e8e255943c5aec2d diff --git a/docs/conf.py b/docs/conf.py index 30faa8d1..3510885d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -110,6 +110,7 @@ # directories to ignore when looking for source files. exclude_patterns = [ "_build", + "**/.nox/**/*", "samples/AUTHORING_GUIDE.md", "samples/CONTRIBUTING.md", "samples/snippets/README.rst", From b6860cab59e5e92d8a2700f2a3eed409da5f050a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 13 Aug 2021 11:44:44 -0400 Subject: [PATCH 058/254] chore: drop mention of Python 2.7 from templates (#177) Source-Link: https://github.com/googleapis/synthtool/commit/facee4cc1ea096cd8bcc008bb85929daa7c414c0 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:9743664022bd63a8084be67f144898314c7ca12f0a03e422ac17c733c129d803 Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- noxfile.py | 12 +++++++++--- samples/snippets/api/noxfile.py | 6 +++--- samples/snippets/classify_text/noxfile.py | 6 +++--- samples/snippets/cloud-client/v1/noxfile.py | 6 +++--- samples/snippets/generated-samples/v1/noxfile.py | 6 +++--- samples/snippets/sentiment/noxfile.py | 6 +++--- scripts/readme-gen/templates/install_deps.tmpl.rst | 2 +- 8 files changed, 26 insertions(+), 20 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index b771c37c..a9fcd07c 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:a1a891041baa4ffbe1a809ac1b8b9b4a71887293c9101c88e8e255943c5aec2d + digest: sha256:9743664022bd63a8084be67f144898314c7ca12f0a03e422ac17c733c129d803 diff --git a/noxfile.py b/noxfile.py index 03aa2f58..2bf3ffd7 100644 --- a/noxfile.py +++ b/noxfile.py @@ -84,9 +84,15 @@ def default(session): constraints_path = str( CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) - session.install("asyncmock", "pytest-asyncio", "-c", constraints_path) - - session.install("mock", "pytest", "pytest-cov", "-c", constraints_path) + session.install( + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", + "-c", + constraints_path, + ) session.install("-e", ".", "-c", constraints_path) diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 125bb619..e73436a1 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -39,7 +39,7 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], + 'ignored_versions': [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them @@ -88,8 +88,8 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. -# All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] +# All versions used to test samples. +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 125bb619..e73436a1 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -39,7 +39,7 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], + 'ignored_versions': [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them @@ -88,8 +88,8 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. -# All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] +# All versions used to test samples. +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 125bb619..e73436a1 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -39,7 +39,7 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], + 'ignored_versions': [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them @@ -88,8 +88,8 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. -# All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] +# All versions used to test samples. +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 125bb619..e73436a1 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -39,7 +39,7 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], + 'ignored_versions': [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them @@ -88,8 +88,8 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. -# All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] +# All versions used to test samples. +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 125bb619..e73436a1 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -39,7 +39,7 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], + 'ignored_versions': [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them @@ -88,8 +88,8 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. -# All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] +# All versions used to test samples. +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst index a0406dba..275d6498 100644 --- a/scripts/readme-gen/templates/install_deps.tmpl.rst +++ b/scripts/readme-gen/templates/install_deps.tmpl.rst @@ -12,7 +12,7 @@ Install Dependencies .. _Python Development Environment Setup Guide: https://cloud.google.com/python/setup -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. +#. Create a virtualenv. Samples are compatible with Python 3.6+. .. code-block:: bash From 25e24ed8995f0b6a2ae0d77d584e3c50e2799dee Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 17 Aug 2021 17:58:57 +0200 Subject: [PATCH 059/254] chore(deps): update dependency google-auth to v1.35.0 (#178) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index bb55768a..04a91b44 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.15.0 -google-auth==1.34.0 +google-auth==1.35.0 google-auth-httplib2==0.1.0 From e4211cb29f09d1fef76475da5a45045b1fb3a9f7 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 25 Aug 2021 15:23:14 +0200 Subject: [PATCH 060/254] chore(deps): update dependency google-auth to v2 (#180) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 04a91b44..5328e947 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.15.0 -google-auth==1.35.0 +google-auth==2.0.1 google-auth-httplib2==0.1.0 From d2ff5dda767fd5b61d96f4f66e8fce7365089927 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 25 Aug 2021 15:47:19 +0200 Subject: [PATCH 061/254] chore(deps): update dependency google-api-python-client to v2.18.0 (#179) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 5328e947..a1c3b194 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.15.0 +google-api-python-client==2.18.0 google-auth==2.0.1 google-auth-httplib2==0.1.0 From f7b0d4e63826f65803b697aa9f2f447cd06202d4 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 30 Aug 2021 15:38:22 +0000 Subject: [PATCH 062/254] chore(python): disable dependency dashboard (#183) --- .github/.OwlBot.lock.yaml | 2 +- renovate.json | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index a9fcd07c..b75186cf 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:9743664022bd63a8084be67f144898314c7ca12f0a03e422ac17c733c129d803 + digest: sha256:d6761eec279244e57fe9d21f8343381a01d3632c034811a72f68b83119e58c69 diff --git a/renovate.json b/renovate.json index c0489556..9fa8816f 100644 --- a/renovate.json +++ b/renovate.json @@ -1,6 +1,8 @@ { "extends": [ - "config:base", ":preserveSemverRanges" + "config:base", + ":preserveSemverRanges", + ":disableDependencyDashboard" ], "ignorePaths": [".pre-commit-config.yaml"], "pip_requirements": { From 12c83a3597fb01334c08fe8fef62229aab8cdc62 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 31 Aug 2021 13:28:32 +0200 Subject: [PATCH 063/254] chore(deps): update dependency pytest to v6.2.5 (#184) --- samples/snippets/api/requirements-test.txt | 2 +- samples/snippets/classify_text/requirements-test.txt | 2 +- samples/snippets/cloud-client/v1/requirements-test.txt | 2 +- samples/snippets/generated-samples/v1/requirements-test.txt | 2 +- samples/snippets/sentiment/requirements-test.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt index 95ea1e6a..92709451 100644 --- a/samples/snippets/api/requirements-test.txt +++ b/samples/snippets/api/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.4 +pytest==6.2.5 diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt index 95ea1e6a..92709451 100644 --- a/samples/snippets/classify_text/requirements-test.txt +++ b/samples/snippets/classify_text/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.4 +pytest==6.2.5 diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt index 95ea1e6a..92709451 100644 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ b/samples/snippets/cloud-client/v1/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.4 +pytest==6.2.5 diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt index 95ea1e6a..92709451 100644 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ b/samples/snippets/generated-samples/v1/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.4 +pytest==6.2.5 diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt index 95ea1e6a..92709451 100644 --- a/samples/snippets/sentiment/requirements-test.txt +++ b/samples/snippets/sentiment/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.4 +pytest==6.2.5 From 3df4288d87dfb7090fad182feb303fdbe3b56664 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 31 Aug 2021 13:34:12 +0200 Subject: [PATCH 064/254] chore(deps): update dependency google-api-python-client to v2.19.0 (#185) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [google-api-python-client](https://togithub.com/googleapis/google-api-python-client) | `==2.18.0` -> `==2.19.0` | [![age](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.19.0/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.19.0/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.19.0/compatibility-slim/2.18.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/google-api-python-client/2.19.0/confidence-slim/2.18.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
googleapis/google-api-python-client ### [`v2.19.0`](https://togithub.com/googleapis/google-api-python-client/compare/v2.18.0...v2.19.0) [Compare Source](https://togithub.com/googleapis/google-api-python-client/compare/v2.18.0...v2.19.0)
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-language). --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index a1c3b194..0230ffad 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.18.0 +google-api-python-client==2.19.0 google-auth==2.0.1 google-auth-httplib2==0.1.0 From c7593d87d0dd76e98af0edbddb3910763d9f01f9 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 1 Sep 2021 13:21:11 +0200 Subject: [PATCH 065/254] chore(deps): update dependency google-auth to v2.0.2 (#186) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 0230ffad..7473ec53 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.19.0 -google-auth==2.0.1 +google-auth==2.0.2 google-auth-httplib2==0.1.0 From 5737303d7a24b26d32f2b1e316079ec1b75f6603 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 1 Sep 2021 15:42:51 +0000 Subject: [PATCH 066/254] chore(python): group renovate prs (#187) --- .github/.OwlBot.lock.yaml | 2 +- renovate.json | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index b75186cf..ef3cb34f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:d6761eec279244e57fe9d21f8343381a01d3632c034811a72f68b83119e58c69 + digest: sha256:1456ea2b3b523ccff5e13030acef56d1de28f21249c62aa0f196265880338fa7 diff --git a/renovate.json b/renovate.json index 9fa8816f..c21036d3 100644 --- a/renovate.json +++ b/renovate.json @@ -1,6 +1,7 @@ { "extends": [ "config:base", + "group:all", ":preserveSemverRanges", ":disableDependencyDashboard" ], From fdb80945251cda38a0321435e38a9320c008cb6d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 1 Sep 2021 16:24:47 -0400 Subject: [PATCH 067/254] chore(python): rename default branch to main (#188) Source-Link: https://github.com/googleapis/synthtool/commit/5c0fa62eea9c33ebe61e582424b659eb264e1ba4 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:0ffe3bdd6c7159692df5f7744da74e5ef19966288a6bf76023e8e04e0c424d7d Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/build.sh | 2 +- .kokoro/test-samples-impl.sh | 2 +- CONTRIBUTING.rst | 16 ++++++++-------- docs/conf.py | 10 +++++----- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index ef3cb34f..c07f148f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:1456ea2b3b523ccff5e13030acef56d1de28f21249c62aa0f196265880338fa7 + digest: sha256:0ffe3bdd6c7159692df5f7744da74e5ef19966288a6bf76023e8e04e0c424d7d diff --git a/.kokoro/build.sh b/.kokoro/build.sh index 3b4c35c7..739ab8d9 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -41,7 +41,7 @@ python3 -m pip install --upgrade --quiet nox python3 -m nox --version # If this is a continuous build, send the test log to the FlakyBot. -# See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. +# See https://github.com/googleapis/repo-automation-bots/tree/main/packages/flakybot. if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]]; then cleanup() { chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh index 311a8d54..8a324c9c 100755 --- a/.kokoro/test-samples-impl.sh +++ b/.kokoro/test-samples-impl.sh @@ -80,7 +80,7 @@ for file in samples/**/requirements.txt; do EXIT=$? # If this is a periodic build, send the test log to the FlakyBot. - # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. + # See https://github.com/googleapis/repo-automation-bots/tree/main/packages/flakybot. if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot $KOKORO_GFILE_DIR/linux_amd64/flakybot diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 755aea73..a6bf2b41 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -50,9 +50,9 @@ You'll have to create a development environment using a Git checkout: # Configure remotes such that you can pull changes from the googleapis/python-language # repository into your local repository. $ git remote add upstream git@github.com:googleapis/python-language.git - # fetch and merge changes from upstream into master + # fetch and merge changes from upstream into main $ git fetch upstream - $ git merge upstream/master + $ git merge upstream/main Now your local repo is set up such that you will push changes to your GitHub repo, from which you can submit a pull request. @@ -110,12 +110,12 @@ Coding Style variables:: export GOOGLE_CLOUD_TESTING_REMOTE="upstream" - export GOOGLE_CLOUD_TESTING_BRANCH="master" + export GOOGLE_CLOUD_TESTING_BRANCH="main" By doing this, you are specifying the location of the most up-to-date - version of ``python-language``. The the suggested remote name ``upstream`` - should point to the official ``googleapis`` checkout and the - the branch should be the main branch on that remote (``master``). + version of ``python-language``. The + remote name ``upstream`` should point to the official ``googleapis`` + checkout and the branch should be the default branch on that remote (``main``). - This repository contains configuration for the `pre-commit `__ tool, which automates checking @@ -209,7 +209,7 @@ The `description on PyPI`_ for the project comes directly from the ``README``. Due to the reStructuredText (``rst``) parser used by PyPI, relative links which will work on GitHub (e.g. ``CONTRIBUTING.rst`` instead of -``https://github.com/googleapis/python-language/blob/master/CONTRIBUTING.rst``) +``https://github.com/googleapis/python-language/blob/main/CONTRIBUTING.rst``) may cause problems creating links or rendering the description. .. _description on PyPI: https://pypi.org/project/google-cloud-language @@ -234,7 +234,7 @@ We support: Supported versions can be found in our ``noxfile.py`` `config`_. -.. _config: https://github.com/googleapis/python-language/blob/master/noxfile.py +.. _config: https://github.com/googleapis/python-language/blob/main/noxfile.py We also explicitly decided to support Python 3 beginning with version 3.6. diff --git a/docs/conf.py b/docs/conf.py index 3510885d..e780d1a1 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -76,8 +76,8 @@ # The encoding of source files. # source_encoding = 'utf-8-sig' -# The master toctree document. -master_doc = "index" +# The root toctree document. +root_doc = "index" # General information about the project. project = "google-cloud-language" @@ -280,7 +280,7 @@ # author, documentclass [howto, manual, or own class]). latex_documents = [ ( - master_doc, + root_doc, "google-cloud-language.tex", "google-cloud-language Documentation", author, @@ -315,7 +315,7 @@ # (source start file, name, description, authors, manual section). man_pages = [ ( - master_doc, + root_doc, "google-cloud-language", "google-cloud-language Documentation", [author], @@ -334,7 +334,7 @@ # dir menu entry, description, category) texinfo_documents = [ ( - master_doc, + root_doc, "google-cloud-language", "google-cloud-language Documentation", author, From 4a47bc7e42ac784e74240268a7c661f7b156cf6f Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 2 Sep 2021 12:39:15 +0200 Subject: [PATCH 068/254] chore(deps): update dependency google-api-python-client to v2.19.1 (#189) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 7473ec53..094c8e57 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.19.0 +google-api-python-client==2.19.1 google-auth==2.0.2 google-auth-httplib2==0.1.0 From a7198b52143cbb2df7b231f4df7cffd6f082423e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 17 Sep 2021 15:36:56 +0000 Subject: [PATCH 069/254] chore: blacken samples noxfile template (#193) --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 44 +++++++++++-------- samples/snippets/classify_text/noxfile.py | 44 +++++++++++-------- samples/snippets/cloud-client/v1/noxfile.py | 44 +++++++++++-------- .../snippets/generated-samples/v1/noxfile.py | 44 +++++++++++-------- samples/snippets/sentiment/noxfile.py | 44 +++++++++++-------- 6 files changed, 126 insertions(+), 96 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index c07f148f..e2c23777 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:0ffe3bdd6c7159692df5f7744da74e5ef19966288a6bf76023e8e04e0c424d7d + digest: sha256:0ccd9f4d714d36e311f60f407199dd460e43a99a125b5ca64b1d75f6e5f8581b diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index e73436a1..b008613f 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -39,17 +39,15 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': [], - + "ignored_versions": [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_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 @@ -57,13 +55,13 @@ "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': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -78,12 +76,12 @@ def get_pytest_env_vars() -> Dict[str, str]: ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret @@ -92,11 +90,14 @@ def get_pytest_env_vars() -> Dict[str, str]: ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) # # Style Checks # @@ -141,7 +142,7 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -150,9 +151,11 @@ def lint(session: nox.sessions.Session) -> None: args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # @@ -165,6 +168,7 @@ def blacken(session: nox.sessions.Session) -> None: session.run("black", *python_files) + # # Sample Tests # @@ -173,7 +177,9 @@ def blacken(session: nox.sessions.Session) -> None: PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> 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}") @@ -203,7 +209,7 @@ def _session_tests(session: nox.sessions.Session, post_install: Callable = None) # on travis where slow and flaky tests are excluded. # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html success_codes=[0, 5], - env=get_pytest_env_vars() + env=get_pytest_env_vars(), ) @@ -213,9 +219,9 @@ def py(session: nox.sessions.Session) -> None: if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) # diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index e73436a1..b008613f 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -39,17 +39,15 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': [], - + "ignored_versions": [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_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 @@ -57,13 +55,13 @@ "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': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -78,12 +76,12 @@ def get_pytest_env_vars() -> Dict[str, str]: ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret @@ -92,11 +90,14 @@ def get_pytest_env_vars() -> Dict[str, str]: ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) # # Style Checks # @@ -141,7 +142,7 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -150,9 +151,11 @@ def lint(session: nox.sessions.Session) -> None: args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # @@ -165,6 +168,7 @@ def blacken(session: nox.sessions.Session) -> None: session.run("black", *python_files) + # # Sample Tests # @@ -173,7 +177,9 @@ def blacken(session: nox.sessions.Session) -> None: PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> 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}") @@ -203,7 +209,7 @@ def _session_tests(session: nox.sessions.Session, post_install: Callable = None) # on travis where slow and flaky tests are excluded. # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html success_codes=[0, 5], - env=get_pytest_env_vars() + env=get_pytest_env_vars(), ) @@ -213,9 +219,9 @@ def py(session: nox.sessions.Session) -> None: if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) # diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index e73436a1..b008613f 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -39,17 +39,15 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': [], - + "ignored_versions": [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_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 @@ -57,13 +55,13 @@ "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': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -78,12 +76,12 @@ def get_pytest_env_vars() -> Dict[str, str]: ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret @@ -92,11 +90,14 @@ def get_pytest_env_vars() -> Dict[str, str]: ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) # # Style Checks # @@ -141,7 +142,7 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -150,9 +151,11 @@ def lint(session: nox.sessions.Session) -> None: args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # @@ -165,6 +168,7 @@ def blacken(session: nox.sessions.Session) -> None: session.run("black", *python_files) + # # Sample Tests # @@ -173,7 +177,9 @@ def blacken(session: nox.sessions.Session) -> None: PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> 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}") @@ -203,7 +209,7 @@ def _session_tests(session: nox.sessions.Session, post_install: Callable = None) # on travis where slow and flaky tests are excluded. # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html success_codes=[0, 5], - env=get_pytest_env_vars() + env=get_pytest_env_vars(), ) @@ -213,9 +219,9 @@ def py(session: nox.sessions.Session) -> None: if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) # diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index e73436a1..b008613f 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -39,17 +39,15 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': [], - + "ignored_versions": [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_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 @@ -57,13 +55,13 @@ "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': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -78,12 +76,12 @@ def get_pytest_env_vars() -> Dict[str, str]: ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret @@ -92,11 +90,14 @@ def get_pytest_env_vars() -> Dict[str, str]: ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) # # Style Checks # @@ -141,7 +142,7 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -150,9 +151,11 @@ def lint(session: nox.sessions.Session) -> None: args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # @@ -165,6 +168,7 @@ def blacken(session: nox.sessions.Session) -> None: session.run("black", *python_files) + # # Sample Tests # @@ -173,7 +177,9 @@ def blacken(session: nox.sessions.Session) -> None: PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> 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}") @@ -203,7 +209,7 @@ def _session_tests(session: nox.sessions.Session, post_install: Callable = None) # on travis where slow and flaky tests are excluded. # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html success_codes=[0, 5], - env=get_pytest_env_vars() + env=get_pytest_env_vars(), ) @@ -213,9 +219,9 @@ def py(session: nox.sessions.Session) -> None: if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) # diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index e73436a1..b008613f 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -39,17 +39,15 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': [], - + "ignored_versions": [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_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 @@ -57,13 +55,13 @@ "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': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -78,12 +76,12 @@ def get_pytest_env_vars() -> Dict[str, str]: ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret @@ -92,11 +90,14 @@ def get_pytest_env_vars() -> Dict[str, str]: ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) # # Style Checks # @@ -141,7 +142,7 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -150,9 +151,11 @@ def lint(session: nox.sessions.Session) -> None: args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # @@ -165,6 +168,7 @@ def blacken(session: nox.sessions.Session) -> None: session.run("black", *python_files) + # # Sample Tests # @@ -173,7 +177,9 @@ def blacken(session: nox.sessions.Session) -> None: PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> 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}") @@ -203,7 +209,7 @@ def _session_tests(session: nox.sessions.Session, post_install: Callable = None) # on travis where slow and flaky tests are excluded. # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html success_codes=[0, 5], - env=get_pytest_env_vars() + env=get_pytest_env_vars(), ) @@ -213,9 +219,9 @@ def py(session: nox.sessions.Session) -> None: if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) # From d853c6bcf66ce7fea12f8565e1fa956e8b23061d Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 21 Sep 2021 21:29:36 +0200 Subject: [PATCH 070/254] chore(deps): update all dependencies (#192) --- samples/snippets/api/requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 094c8e57..d02277db 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.19.1 -google-auth==2.0.2 +google-api-python-client==2.22.0 +google-auth==2.1.0 google-auth-httplib2==0.1.0 From 81c512310dcbecfba518387ab8ea95aded556c01 Mon Sep 17 00:00:00 2001 From: Jeffrey Rennie Date: Tue, 21 Sep 2021 12:52:28 -0700 Subject: [PATCH 071/254] chore: relocate owl bot post processor (#195) chore: relocate owl bot post processor --- .github/.OwlBot.lock.yaml | 4 ++-- .github/.OwlBot.yaml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index e2c23777..2567653c 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: - image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:0ccd9f4d714d36e311f60f407199dd460e43a99a125b5ca64b1d75f6e5f8581b + image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest + digest: sha256:87eee22d276554e4e52863ec9b1cb6a7245815dfae20439712bf644348215a5a diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml index df80b945..88452d4a 100644 --- a/.github/.OwlBot.yaml +++ b/.github/.OwlBot.yaml @@ -13,7 +13,7 @@ # limitations under the License. docker: - image: gcr.io/repo-automation-bots/owlbot-python:latest + image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest deep-remove-regex: - /owl-bot-staging From 09741ac11f3d9fbcaabb075748c31004bdc6a3a6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 24 Sep 2021 09:02:34 -0600 Subject: [PATCH 072/254] chore: use gapic-generator-python 0.51.2 (#196) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: use gapic-generator-python 0.51.2 fix: add 'dict' annotation type to 'request' Committer: @busunkim96 PiperOrigin-RevId: 398509016 Source-Link: https://github.com/googleapis/googleapis/commit/b224dfa52642a733ea64849d4e06d15c274bc08f Source-Link: https://github.com/googleapis/googleapis-gen/commit/63a1db7a38d74b9639592f521ed1daaf7299ad9a Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjNhMWRiN2EzOGQ3NGI5NjM5NTkyZjUyMWVkMWRhYWY3Mjk5YWQ5YSJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- .../services/language_service/client.py | 26 +++++++++---------- .../language_service/transports/base.py | 2 +- .../language_service/transports/grpc.py | 6 ++--- .../transports/grpc_asyncio.py | 6 ++--- .../services/language_service/client.py | 26 +++++++++---------- .../language_service/transports/base.py | 2 +- .../language_service/transports/grpc.py | 6 ++--- .../transports/grpc_asyncio.py | 6 ++--- scripts/fixup_language_v1_keywords.py | 14 +++++----- scripts/fixup_language_v1beta2_keywords.py | 14 +++++----- 10 files changed, 54 insertions(+), 54 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index eb724c09..70a51e1a 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -17,7 +17,7 @@ from distutils import util import os import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -337,7 +337,7 @@ def __init__( def analyze_sentiment( self, - request: language_service.AnalyzeSentimentRequest = None, + request: Union[language_service.AnalyzeSentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -348,7 +348,7 @@ def analyze_sentiment( r"""Analyzes the sentiment of the provided text. Args: - request (google.cloud.language_v1.types.AnalyzeSentimentRequest): + request (Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request message. document (google.cloud.language_v1.types.Document): @@ -410,7 +410,7 @@ def analyze_sentiment( def analyze_entities( self, - request: language_service.AnalyzeEntitiesRequest = None, + request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -424,7 +424,7 @@ def analyze_entities( properties. Args: - request (google.cloud.language_v1.types.AnalyzeEntitiesRequest): + request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. document (google.cloud.language_v1.types.Document): Input document. @@ -483,7 +483,7 @@ def analyze_entities( def analyze_entity_sentiment( self, - request: language_service.AnalyzeEntitySentimentRequest = None, + request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -497,7 +497,7 @@ def analyze_entity_sentiment( and its mentions. Args: - request (google.cloud.language_v1.types.AnalyzeEntitySentimentRequest): + request (Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis request message. document (google.cloud.language_v1.types.Document): @@ -559,7 +559,7 @@ def analyze_entity_sentiment( def analyze_syntax( self, - request: language_service.AnalyzeSyntaxRequest = None, + request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -572,7 +572,7 @@ def analyze_syntax( tags, dependency trees, and other properties. Args: - request (google.cloud.language_v1.types.AnalyzeSyntaxRequest): + request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. document (google.cloud.language_v1.types.Document): Input document. @@ -631,7 +631,7 @@ def analyze_syntax( def classify_text( self, - request: language_service.ClassifyTextRequest = None, + request: Union[language_service.ClassifyTextRequest, dict] = None, *, document: language_service.Document = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -641,7 +641,7 @@ def classify_text( r"""Classifies a document into categories. Args: - request (google.cloud.language_v1.types.ClassifyTextRequest): + request (Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]): The request object. The document classification request message. document (google.cloud.language_v1.types.Document): @@ -694,7 +694,7 @@ def classify_text( def annotate_text( self, - request: language_service.AnnotateTextRequest = None, + request: Union[language_service.AnnotateTextRequest, dict] = None, *, document: language_service.Document = None, features: language_service.AnnotateTextRequest.Features = None, @@ -708,7 +708,7 @@ def annotate_text( analyzeSyntax provide in one call. Args: - request (google.cloud.language_v1.types.AnnotateTextRequest): + request (Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]): The request object. The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 42537ea4..3592b976 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -118,7 +118,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # If the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index a059ea93..19f76ed3 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -81,16 +81,16 @@ def __init__( api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. + ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 4f849e85..4bf29805 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -128,16 +128,16 @@ def __init__( api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. + ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 70fc8afc..41ad7081 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -17,7 +17,7 @@ from distutils import util import os import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -337,7 +337,7 @@ def __init__( def analyze_sentiment( self, - request: language_service.AnalyzeSentimentRequest = None, + request: Union[language_service.AnalyzeSentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -348,7 +348,7 @@ def analyze_sentiment( r"""Analyzes the sentiment of the provided text. Args: - request (google.cloud.language_v1beta2.types.AnalyzeSentimentRequest): + request (Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request message. document (google.cloud.language_v1beta2.types.Document): @@ -411,7 +411,7 @@ def analyze_sentiment( def analyze_entities( self, - request: language_service.AnalyzeEntitiesRequest = None, + request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -425,7 +425,7 @@ def analyze_entities( properties. Args: - request (google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest): + request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -484,7 +484,7 @@ def analyze_entities( def analyze_entity_sentiment( self, - request: language_service.AnalyzeEntitySentimentRequest = None, + request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -498,7 +498,7 @@ def analyze_entity_sentiment( and its mentions. Args: - request (google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest): + request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis request message. document (google.cloud.language_v1beta2.types.Document): @@ -560,7 +560,7 @@ def analyze_entity_sentiment( def analyze_syntax( self, - request: language_service.AnalyzeSyntaxRequest = None, + request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, @@ -573,7 +573,7 @@ def analyze_syntax( tags, dependency trees, and other properties. Args: - request (google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest): + request (Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -632,7 +632,7 @@ def analyze_syntax( def classify_text( self, - request: language_service.ClassifyTextRequest = None, + request: Union[language_service.ClassifyTextRequest, dict] = None, *, document: language_service.Document = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -642,7 +642,7 @@ def classify_text( r"""Classifies a document into categories. Args: - request (google.cloud.language_v1beta2.types.ClassifyTextRequest): + request (Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]): The request object. The document classification request message. document (google.cloud.language_v1beta2.types.Document): @@ -695,7 +695,7 @@ def classify_text( def annotate_text( self, - request: language_service.AnnotateTextRequest = None, + request: Union[language_service.AnnotateTextRequest, dict] = None, *, document: language_service.Document = None, features: language_service.AnnotateTextRequest.Features = None, @@ -709,7 +709,7 @@ def annotate_text( call. Args: - request (google.cloud.language_v1beta2.types.AnnotateTextRequest): + request (Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]): The request object. The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 38f98b34..933211f6 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -118,7 +118,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # If the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index ad25eaa4..9ddd31ac 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -81,16 +81,16 @@ def __init__( api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. + ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index a141b4cb..b67c823a 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -128,16 +128,16 @@ def __init__( api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. + ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is + both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. diff --git a/scripts/fixup_language_v1_keywords.py b/scripts/fixup_language_v1_keywords.py index 99d05077..aac999b1 100644 --- a/scripts/fixup_language_v1_keywords.py +++ b/scripts/fixup_language_v1_keywords.py @@ -39,12 +39,12 @@ def partition( class languageCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_entities': ('document', 'encoding_type', ), - 'analyze_entity_sentiment': ('document', 'encoding_type', ), - 'analyze_sentiment': ('document', 'encoding_type', ), - 'analyze_syntax': ('document', 'encoding_type', ), - 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', ), + 'analyze_entities': ('document', 'encoding_type', ), + 'analyze_entity_sentiment': ('document', 'encoding_type', ), + 'analyze_sentiment': ('document', 'encoding_type', ), + 'analyze_syntax': ('document', 'encoding_type', ), + 'annotate_text': ('document', 'features', 'encoding_type', ), + 'classify_text': ('document', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -63,7 +63,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) diff --git a/scripts/fixup_language_v1beta2_keywords.py b/scripts/fixup_language_v1beta2_keywords.py index 99d05077..aac999b1 100644 --- a/scripts/fixup_language_v1beta2_keywords.py +++ b/scripts/fixup_language_v1beta2_keywords.py @@ -39,12 +39,12 @@ def partition( class languageCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_entities': ('document', 'encoding_type', ), - 'analyze_entity_sentiment': ('document', 'encoding_type', ), - 'analyze_sentiment': ('document', 'encoding_type', ), - 'analyze_syntax': ('document', 'encoding_type', ), - 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', ), + 'analyze_entities': ('document', 'encoding_type', ), + 'analyze_entity_sentiment': ('document', 'encoding_type', ), + 'analyze_sentiment': ('document', 'encoding_type', ), + 'analyze_syntax': ('document', 'encoding_type', ), + 'annotate_text': ('document', 'features', 'encoding_type', ), + 'classify_text': ('document', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -63,7 +63,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) From 17cedeca6a334d1876fca1726c8b51ac515f8a4c Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Mon, 27 Sep 2021 19:45:30 +0200 Subject: [PATCH 073/254] chore(deps): update dependency google-auth to v2.2.0 (#197) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index d02277db..7e4bd82d 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.22.0 -google-auth==2.1.0 +google-auth==2.2.0 google-auth-httplib2==0.1.0 From 75403dd9bf5aeb7d2a447964396ddba3fbe7ed85 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Mon, 27 Sep 2021 15:45:52 -0600 Subject: [PATCH 074/254] chore: reference main branch of google-cloud-python (#191) Co-authored-by: Anthonios Partheniou --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 96dd41fc..958246b4 100644 --- a/README.rst +++ b/README.rst @@ -17,7 +17,7 @@ with your document storage on Google Cloud Storage. - `Product Documentation`_ .. |GA| image:: https://img.shields.io/badge/support-GA-gold.svg - :target: https://github.com/googleapis/google-cloud-python/blob/master/README.rst#general-availability + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#general-availability .. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-language.svg :target: https://pypi.org/project/google-cloud-language/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-language.svg From 93e01c59d328d0fd74d43ee64f97415796f1236b Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 28 Sep 2021 17:46:14 +0200 Subject: [PATCH 075/254] chore(deps): update dependency google-api-python-client to v2.23.0 (#198) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 7e4bd82d..84c3927d 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.22.0 +google-api-python-client==2.23.0 google-auth==2.2.0 google-auth-httplib2==0.1.0 From 5b93a68c11c2bcff459130f022af08f31a306acd Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 29 Sep 2021 16:53:57 +0200 Subject: [PATCH 076/254] chore(deps): update dependency google-auth to v2.2.1 (#199) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 84c3927d..2bf9babb 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.23.0 -google-auth==2.2.0 +google-auth==2.2.1 google-auth-httplib2==0.1.0 From eb294698cdc11d3f29dd7356e60cbb249c23c73e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 30 Sep 2021 15:44:41 +0000 Subject: [PATCH 077/254] chore: fail samples nox session if python version is missing (#200) --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 4 ++++ samples/snippets/classify_text/noxfile.py | 4 ++++ samples/snippets/cloud-client/v1/noxfile.py | 4 ++++ samples/snippets/generated-samples/v1/noxfile.py | 4 ++++ samples/snippets/sentiment/noxfile.py | 4 ++++ 6 files changed, 21 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 2567653c..ae6c57fa 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:87eee22d276554e4e52863ec9b1cb6a7245815dfae20439712bf644348215a5a + digest: sha256:82b12321da4446a73cb11bcb6812fbec8c105abda3946d46e6394e5fbfb64c0f diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index b008613f..1fd8956f 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -98,6 +98,10 @@ def get_pytest_env_vars() -> Dict[str, str]: "True", "true", ) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + # # Style Checks # diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index b008613f..1fd8956f 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -98,6 +98,10 @@ def get_pytest_env_vars() -> Dict[str, str]: "True", "true", ) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + # # Style Checks # diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index b008613f..1fd8956f 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -98,6 +98,10 @@ def get_pytest_env_vars() -> Dict[str, str]: "True", "true", ) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + # # Style Checks # diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index b008613f..1fd8956f 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -98,6 +98,10 @@ def get_pytest_env_vars() -> Dict[str, str]: "True", "true", ) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + # # Style Checks # diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index b008613f..1fd8956f 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -98,6 +98,10 @@ def get_pytest_env_vars() -> Dict[str, str]: "True", "true", ) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + # # Style Checks # From c3c9a81039f3e065841ed0acc7569bb04f3dfc7e Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 5 Oct 2021 16:53:12 +0200 Subject: [PATCH 078/254] chore(deps): update dependency google-api-python-client to v2.24.0 (#201) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 2bf9babb..2d206082 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.23.0 +google-api-python-client==2.24.0 google-auth==2.2.1 google-auth-httplib2==0.1.0 From 185309d81cfff637e62b2d9a8bdbb32952765f8e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 5 Oct 2021 11:25:36 -0600 Subject: [PATCH 079/254] build: use trampoline_v2 for python samples and allow custom dockerfile (#202) Source-Link: https://github.com/googleapis/synthtool/commit/a7ed11ec0863c422ba2e73aafa75eab22c32b33d Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:6e7328583be8edd3ba8f35311c76a1ecbc823010279ccb6ab46b7a76e25eafcc Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/samples/lint/common.cfg | 2 +- .kokoro/samples/python3.6/common.cfg | 2 +- .kokoro/samples/python3.6/periodic.cfg | 2 +- .kokoro/samples/python3.7/common.cfg | 2 +- .kokoro/samples/python3.7/periodic.cfg | 2 +- .kokoro/samples/python3.8/common.cfg | 2 +- .kokoro/samples/python3.8/periodic.cfg | 2 +- .kokoro/samples/python3.9/common.cfg | 2 +- .kokoro/samples/python3.9/periodic.cfg | 2 +- .kokoro/test-samples-against-head.sh | 2 -- .kokoro/test-samples.sh | 2 -- .trampolinerc | 17 ++++++++++++++--- 13 files changed, 24 insertions(+), 17 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index ae6c57fa..ee94722a 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:82b12321da4446a73cb11bcb6812fbec8c105abda3946d46e6394e5fbfb64c0f + digest: sha256:6e7328583be8edd3ba8f35311c76a1ecbc823010279ccb6ab46b7a76e25eafcc diff --git a/.kokoro/samples/lint/common.cfg b/.kokoro/samples/lint/common.cfg index f3f92a93..a9caf408 100644 --- a/.kokoro/samples/lint/common.cfg +++ b/.kokoro/samples/lint/common.cfg @@ -31,4 +31,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg index aa92ff73..3d32e6ed 100644 --- a/.kokoro/samples/python3.6/common.cfg +++ b/.kokoro/samples/python3.6/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.6/periodic.cfg b/.kokoro/samples/python3.6/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.6/periodic.cfg +++ b/.kokoro/samples/python3.6/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index aa64611c..71cf69f9 100644 --- a/.kokoro/samples/python3.7/common.cfg +++ b/.kokoro/samples/python3.7/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.7/periodic.cfg b/.kokoro/samples/python3.7/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.7/periodic.cfg +++ b/.kokoro/samples/python3.7/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index 8fd22150..086547f2 100644 --- a/.kokoro/samples/python3.8/common.cfg +++ b/.kokoro/samples/python3.8/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.8/periodic.cfg b/.kokoro/samples/python3.8/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.8/periodic.cfg +++ b/.kokoro/samples/python3.8/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/samples/python3.9/common.cfg b/.kokoro/samples/python3.9/common.cfg index 38c3cc08..f1b3c2c0 100644 --- a/.kokoro/samples/python3.9/common.cfg +++ b/.kokoro/samples/python3.9/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.9/periodic.cfg b/.kokoro/samples/python3.9/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.9/periodic.cfg +++ b/.kokoro/samples/python3.9/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/test-samples-against-head.sh b/.kokoro/test-samples-against-head.sh index 2a7db027..ba3a707b 100755 --- a/.kokoro/test-samples-against-head.sh +++ b/.kokoro/test-samples-against-head.sh @@ -23,6 +23,4 @@ set -eo pipefail # Enables `**` to include files nested inside sub-folders shopt -s globstar -cd github/python-language - exec .kokoro/test-samples-impl.sh diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index 801c16f4..11c042d3 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -24,8 +24,6 @@ set -eo pipefail # Enables `**` to include files nested inside sub-folders shopt -s globstar -cd github/python-language - # Run periodic samples tests at latest release if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then # preserving the test runner implementation. diff --git a/.trampolinerc b/.trampolinerc index 383b6ec8..0eee72ab 100644 --- a/.trampolinerc +++ b/.trampolinerc @@ -16,15 +16,26 @@ # Add required env vars here. required_envvars+=( - "STAGING_BUCKET" - "V2_STAGING_BUCKET" ) # Add env vars which are passed down into the container here. pass_down_envvars+=( + "NOX_SESSION" + ############### + # Docs builds + ############### "STAGING_BUCKET" "V2_STAGING_BUCKET" - "NOX_SESSION" + ################## + # Samples builds + ################## + "INSTALL_LIBRARY_FROM_SOURCE" + "RUN_TESTS_SESSION" + "BUILD_SPECIFIC_GCLOUD_PROJECT" + # Target directories. + "RUN_TESTS_DIRS" + # The nox session to run. + "RUN_TESTS_SESSION" ) # Prevent unintentional override on the default image. From 91d48a8fee63b8279b235b70921d018206084b50 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 7 Oct 2021 00:34:39 +0000 Subject: [PATCH 080/254] feat: add context manager support in client (#203) - [ ] Regenerate this pull request now. chore: fix docstring for first attribute of protos committer: @busunkim96 PiperOrigin-RevId: 401271153 Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10 Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9 --- .../services/language_service/async_client.py | 6 +++ .../services/language_service/client.py | 18 +++++-- .../language_service/transports/base.py | 9 ++++ .../language_service/transports/grpc.py | 3 ++ .../transports/grpc_asyncio.py | 3 ++ .../language_v1/types/language_service.py | 15 ++++++ .../services/language_service/async_client.py | 6 +++ .../services/language_service/client.py | 18 +++++-- .../language_service/transports/base.py | 9 ++++ .../language_service/transports/grpc.py | 3 ++ .../transports/grpc_asyncio.py | 3 ++ .../types/language_service.py | 17 +++++++ .../language_v1/test_language_service.py | 50 +++++++++++++++++++ .../language_v1beta2/test_language_service.py | 50 +++++++++++++++++++ 14 files changed, 202 insertions(+), 8 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index eb800802..86d98569 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -661,6 +661,12 @@ async def annotate_text( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 70a51e1a..7d4846ec 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -329,10 +329,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def analyze_sentiment( @@ -776,6 +773,19 @@ def annotate_text( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 3592b976..0e4917a5 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -247,6 +247,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def analyze_sentiment( self, diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 19f76ed3..4a85b2e2 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -407,5 +407,8 @@ def annotate_text( ) return self._stubs["annotate_text"] + def close(self): + self.grpc_channel.close() + __all__ = ("LanguageServiceGrpcTransport",) diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 4bf29805..46294075 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -413,5 +413,8 @@ def annotate_text( ) return self._stubs["annotate_text"] + def close(self): + return self.grpc_channel.close() + __all__ = ("LanguageServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 1138d63e..e4ee8e53 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -101,6 +101,7 @@ class Type(proto.Enum): class Sentence(proto.Message): r"""Represents a sentence in the input document. + Attributes: text (google.cloud.language_v1.types.TextSpan): The sentence text. @@ -182,6 +183,7 @@ class Type(proto.Enum): class Token(proto.Message): r"""Represents the smallest syntactic building block of the text. + Attributes: text (google.cloud.language_v1.types.TextSpan): The token text. @@ -538,6 +540,7 @@ class Type(proto.Enum): class TextSpan(proto.Message): r"""Represents an output piece of text. + Attributes: content (str): The content of the output text. @@ -554,6 +557,7 @@ class TextSpan(proto.Message): class ClassificationCategory(proto.Message): r"""Represents a category returned from the text classifier. + Attributes: name (str): The name of the category representing the document, from the @@ -571,6 +575,7 @@ class ClassificationCategory(proto.Message): class AnalyzeSentimentRequest(proto.Message): r"""The sentiment analysis request message. + Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -585,6 +590,7 @@ class AnalyzeSentimentRequest(proto.Message): class AnalyzeSentimentResponse(proto.Message): r"""The sentiment analysis response message. + Attributes: document_sentiment (google.cloud.language_v1.types.Sentiment): The overall sentiment of the input document. @@ -606,6 +612,7 @@ class AnalyzeSentimentResponse(proto.Message): class AnalyzeEntitySentimentRequest(proto.Message): r"""The entity-level sentiment analysis request message. + Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -620,6 +627,7 @@ class AnalyzeEntitySentimentRequest(proto.Message): class AnalyzeEntitySentimentResponse(proto.Message): r"""The entity-level sentiment analysis response message. + Attributes: entities (Sequence[google.cloud.language_v1.types.Entity]): The recognized entities in the input document @@ -638,6 +646,7 @@ class AnalyzeEntitySentimentResponse(proto.Message): class AnalyzeEntitiesRequest(proto.Message): r"""The entity analysis request message. + Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -652,6 +661,7 @@ class AnalyzeEntitiesRequest(proto.Message): class AnalyzeEntitiesResponse(proto.Message): r"""The entity analysis response message. + Attributes: entities (Sequence[google.cloud.language_v1.types.Entity]): The recognized entities in the input @@ -670,6 +680,7 @@ class AnalyzeEntitiesResponse(proto.Message): class AnalyzeSyntaxRequest(proto.Message): r"""The syntax analysis request message. + Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -684,6 +695,7 @@ class AnalyzeSyntaxRequest(proto.Message): class AnalyzeSyntaxResponse(proto.Message): r"""The syntax analysis response message. + Attributes: sentences (Sequence[google.cloud.language_v1.types.Sentence]): Sentences in the input document. @@ -705,6 +717,7 @@ class AnalyzeSyntaxResponse(proto.Message): class ClassifyTextRequest(proto.Message): r"""The document classification request message. + Attributes: document (google.cloud.language_v1.types.Document): Input document. @@ -715,6 +728,7 @@ class ClassifyTextRequest(proto.Message): class ClassifyTextResponse(proto.Message): r"""The document classification response message. + Attributes: categories (Sequence[google.cloud.language_v1.types.ClassificationCategory]): Categories representing the input document. @@ -772,6 +786,7 @@ class Features(proto.Message): class AnnotateTextResponse(proto.Message): r"""The text annotations response message. + Attributes: sentences (Sequence[google.cloud.language_v1.types.Sentence]): Sentences in the input document. Populated if the user diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 711bc55c..c95d4083 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -662,6 +662,12 @@ async def annotate_text( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 41ad7081..3ed65bb6 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -329,10 +329,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def analyze_sentiment( @@ -777,6 +774,19 @@ def annotate_text( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 933211f6..59be86ca 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -247,6 +247,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def analyze_sentiment( self, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 9ddd31ac..7f7c7b2d 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -407,5 +407,8 @@ def annotate_text( ) return self._stubs["annotate_text"] + def close(self): + self.grpc_channel.close() + __all__ = ("LanguageServiceGrpcTransport",) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index b67c823a..2c48f9bc 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -413,5 +413,8 @@ def annotate_text( ) return self._stubs["annotate_text"] + def close(self): + return self.grpc_channel.close() + __all__ = ("LanguageServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 631b8fad..0aabe4a9 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -101,6 +101,7 @@ class Type(proto.Enum): class Sentence(proto.Message): r"""Represents a sentence in the input document. + Attributes: text (google.cloud.language_v1beta2.types.TextSpan): The sentence text. @@ -182,6 +183,7 @@ class Type(proto.Enum): class Token(proto.Message): r"""Represents the smallest syntactic building block of the text. + Attributes: text (google.cloud.language_v1beta2.types.TextSpan): The token text. @@ -221,6 +223,7 @@ class Sentiment(proto.Message): class PartOfSpeech(proto.Message): r"""Represents part of speech information for a token. + Attributes: tag (google.cloud.language_v1beta2.types.PartOfSpeech.Tag): The part of speech tag. @@ -401,6 +404,7 @@ class Voice(proto.Enum): class DependencyEdge(proto.Message): r"""Represents dependency parse tree information for a token. + Attributes: head_token_index (int): Represents the head of this token in the dependency tree. @@ -533,6 +537,7 @@ class Type(proto.Enum): class TextSpan(proto.Message): r"""Represents an output piece of text. + Attributes: content (str): The content of the output text. @@ -549,6 +554,7 @@ class TextSpan(proto.Message): class ClassificationCategory(proto.Message): r"""Represents a category returned from the text classifier. + Attributes: name (str): The name of the category representing the document, from the @@ -566,6 +572,7 @@ class ClassificationCategory(proto.Message): class AnalyzeSentimentRequest(proto.Message): r"""The sentiment analysis request message. + Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -581,6 +588,7 @@ class AnalyzeSentimentRequest(proto.Message): class AnalyzeSentimentResponse(proto.Message): r"""The sentiment analysis response message. + Attributes: document_sentiment (google.cloud.language_v1beta2.types.Sentiment): The overall sentiment of the input document. @@ -602,6 +610,7 @@ class AnalyzeSentimentResponse(proto.Message): class AnalyzeEntitySentimentRequest(proto.Message): r"""The entity-level sentiment analysis request message. + Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -616,6 +625,7 @@ class AnalyzeEntitySentimentRequest(proto.Message): class AnalyzeEntitySentimentResponse(proto.Message): r"""The entity-level sentiment analysis response message. + Attributes: entities (Sequence[google.cloud.language_v1beta2.types.Entity]): The recognized entities in the input document @@ -634,6 +644,7 @@ class AnalyzeEntitySentimentResponse(proto.Message): class AnalyzeEntitiesRequest(proto.Message): r"""The entity analysis request message. + Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -648,6 +659,7 @@ class AnalyzeEntitiesRequest(proto.Message): class AnalyzeEntitiesResponse(proto.Message): r"""The entity analysis response message. + Attributes: entities (Sequence[google.cloud.language_v1beta2.types.Entity]): The recognized entities in the input @@ -666,6 +678,7 @@ class AnalyzeEntitiesResponse(proto.Message): class AnalyzeSyntaxRequest(proto.Message): r"""The syntax analysis request message. + Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -680,6 +693,7 @@ class AnalyzeSyntaxRequest(proto.Message): class AnalyzeSyntaxResponse(proto.Message): r"""The syntax analysis response message. + Attributes: sentences (Sequence[google.cloud.language_v1beta2.types.Sentence]): Sentences in the input document. @@ -701,6 +715,7 @@ class AnalyzeSyntaxResponse(proto.Message): class ClassifyTextRequest(proto.Message): r"""The document classification request message. + Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. @@ -711,6 +726,7 @@ class ClassifyTextRequest(proto.Message): class ClassifyTextResponse(proto.Message): r"""The document classification response message. + Attributes: categories (Sequence[google.cloud.language_v1beta2.types.ClassificationCategory]): Categories representing the input document. @@ -771,6 +787,7 @@ class Features(proto.Message): class AnnotateTextResponse(proto.Message): r"""The text annotations response message. + Attributes: sentences (Sequence[google.cloud.language_v1beta2.types.Sentence]): Sentences in the input document. Populated if the user diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 1f4dcf06..a2a061a3 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -29,6 +29,7 @@ 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 path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.language_v1.services.language_service import ( @@ -1686,6 +1687,9 @@ def test_language_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_language_service_base_transport_with_credentials_file(): @@ -2165,3 +2169,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 71d88d17..729ad8c1 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -29,6 +29,7 @@ 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 path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.language_v1beta2.services.language_service import ( @@ -1688,6 +1689,9 @@ def test_language_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_language_service_base_transport_with_credentials_file(): @@ -2167,3 +2171,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() From 543fe82f7bab45434c5d5bd212cbf499d74c77e7 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 9 Oct 2021 10:54:50 -0400 Subject: [PATCH 081/254] chore(python): Add kokoro configs for python 3.10 samples testing (#207) * chore(python): Add kokoro configs for python 3.10 samples testing Source-Link: https://github.com/googleapis/synthtool/commit/c6e69c4726a233ad8d496961ec265d29e54010b7 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:58f73ba196b5414782605236dd0712a73541b44ff2ff4d3a36ec41092dd6fa5b * add constraints files for py3.10 and py3.11 Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/samples/python3.10/common.cfg | 40 +++++++++++++++++++ .kokoro/samples/python3.10/continuous.cfg | 6 +++ .kokoro/samples/python3.10/periodic-head.cfg | 11 +++++ .kokoro/samples/python3.10/periodic.cfg | 6 +++ .kokoro/samples/python3.10/presubmit.cfg | 6 +++ CONTRIBUTING.rst | 6 ++- noxfile.py | 2 +- samples/snippets/api/noxfile.py | 2 +- samples/snippets/classify_text/noxfile.py | 2 +- samples/snippets/cloud-client/v1/noxfile.py | 2 +- .../snippets/generated-samples/v1/noxfile.py | 2 +- samples/snippets/sentiment/noxfile.py | 2 +- testing/constraints-3.10.txt | 0 testing/constraints-3.11.txt | 0 15 files changed, 80 insertions(+), 9 deletions(-) create mode 100644 .kokoro/samples/python3.10/common.cfg create mode 100644 .kokoro/samples/python3.10/continuous.cfg create mode 100644 .kokoro/samples/python3.10/periodic-head.cfg create mode 100644 .kokoro/samples/python3.10/periodic.cfg create mode 100644 .kokoro/samples/python3.10/presubmit.cfg create mode 100644 testing/constraints-3.10.txt create mode 100644 testing/constraints-3.11.txt diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index ee94722a..7d98291c 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:6e7328583be8edd3ba8f35311c76a1ecbc823010279ccb6ab46b7a76e25eafcc + digest: sha256:58f73ba196b5414782605236dd0712a73541b44ff2ff4d3a36ec41092dd6fa5b diff --git a/.kokoro/samples/python3.10/common.cfg b/.kokoro/samples/python3.10/common.cfg new file mode 100644 index 00000000..27547f0a --- /dev/null +++ b/.kokoro/samples/python3.10/common.cfg @@ -0,0 +1,40 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Specify which tests to run +env_vars: { + key: "RUN_TESTS_SESSION" + value: "py-3.10" +} + +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-310" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-language/.kokoro/test-samples.sh" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" +} + +# Download secrets for samples +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.10/continuous.cfg b/.kokoro/samples/python3.10/continuous.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.10/continuous.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.10/periodic-head.cfg b/.kokoro/samples/python3.10/periodic-head.cfg new file mode 100644 index 00000000..676f8aa8 --- /dev/null +++ b/.kokoro/samples/python3.10/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-language/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.10/periodic.cfg b/.kokoro/samples/python3.10/periodic.cfg new file mode 100644 index 00000000..71cd1e59 --- /dev/null +++ b/.kokoro/samples/python3.10/periodic.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "False" +} diff --git a/.kokoro/samples/python3.10/presubmit.cfg b/.kokoro/samples/python3.10/presubmit.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.10/presubmit.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index a6bf2b41..adf8f81c 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.6, 3.7, 3.8 and 3.9 on both UNIX and Windows. + 3.6, 3.7, 3.8, 3.9 and 3.10 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.9 -- -k + $ nox -s unit-3.10 -- -k .. note:: @@ -225,11 +225,13 @@ We support: - `Python 3.7`_ - `Python 3.8`_ - `Python 3.9`_ +- `Python 3.10`_ .. _Python 3.6: https://docs.python.org/3.6/ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ .. _Python 3.9: https://docs.python.org/3.9/ +.. _Python 3.10: https://docs.python.org/3.10/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/noxfile.py b/noxfile.py index 2bf3ffd7..672b28d6 100644 --- a/noxfile.py +++ b/noxfile.py @@ -29,7 +29,7 @@ DEFAULT_PYTHON_VERSION = "3.8" SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 1fd8956f..93a9122c 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -87,7 +87,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 1fd8956f..93a9122c 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -87,7 +87,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 1fd8956f..93a9122c 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -87,7 +87,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 1fd8956f..93a9122c 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -87,7 +87,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 1fd8956f..93a9122c 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -87,7 +87,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt new file mode 100644 index 00000000..e69de29b diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt new file mode 100644 index 00000000..e69de29b From 96434105552fb0ce8a9c9332374fcc8d58739d1d Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Tue, 12 Oct 2021 13:32:56 -0600 Subject: [PATCH 082/254] chore: release 2.3.0 (#204) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 7 +++++++ setup.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0214571a..646b0782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.3.0](https://www.github.com/googleapis/python-language/compare/v2.2.2...v2.3.0) (2021-10-09) + + +### Features + +* add context manager support in client ([#203](https://www.github.com/googleapis/python-language/issues/203)) ([91d48a8](https://www.github.com/googleapis/python-language/commit/91d48a8fee63b8279b235b70921d018206084b50)) + ### [2.2.2](https://www.github.com/googleapis/python-language/compare/v2.2.1...v2.2.2) (2021-07-28) diff --git a/setup.py b/setup.py index 6d7a1acb..708e6149 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.2.2" +version = "2.3.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 47cd16f36e8801aeb75d8a9dfb106bb9177996f2 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 21 Oct 2021 10:59:14 -0400 Subject: [PATCH 083/254] chore: add default_version and codeowner_team to .repo-metadata.json (#210) * chore: add default_version and codeowner_team to .repo-metadata.json * update default_version --- .repo-metadata.json | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index 8e7854be..24d5ceb2 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -1,14 +1,16 @@ { - "name": "language", - "name_pretty": "Natural Language", - "product_documentation": "https://cloud.google.com/natural-language/docs/", - "client_documentation": "https://googleapis.dev/python/language/latest", - "issue_tracker": "https://issuetracker.google.com/savedsearches/559753", - "release_level": "ga", - "language": "python", - "library_type": "GAPIC_AUTO", - "repo": "googleapis/python-language", - "distribution_name": "google-cloud-language", - "api_id": "language.googleapis.com", - "requires_billing": true + "name": "language", + "name_pretty": "Natural Language", + "product_documentation": "https://cloud.google.com/natural-language/docs/", + "client_documentation": "https://googleapis.dev/python/language/latest", + "issue_tracker": "https://issuetracker.google.com/savedsearches/559753", + "release_level": "ga", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/python-language", + "distribution_name": "google-cloud-language", + "api_id": "language.googleapis.com", + "requires_billing": true, + "default_version": "v1", + "codeowner_team": "" } From 20babb6c017315d344452dbaaf50b47629d11606 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 25 Oct 2021 21:38:19 -0400 Subject: [PATCH 084/254] chore(python): push cloud library docs to Cloud RAD (#212) Source-Link: https://github.com/googleapis/synthtool/commit/694118b039b09551fb5d445fceb361a7dbb06400 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:ec49167c606648a063d1222220b48119c912562849a0528f35bfb592a9f72737 Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/docs/common.cfg | 1 + noxfile.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 7d98291c..cb89b2e3 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:58f73ba196b5414782605236dd0712a73541b44ff2ff4d3a36ec41092dd6fa5b + digest: sha256:ec49167c606648a063d1222220b48119c912562849a0528f35bfb592a9f72737 diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 7c5d93f2..520ba420 100644 --- a/.kokoro/docs/common.cfg +++ b/.kokoro/docs/common.cfg @@ -30,6 +30,7 @@ env_vars: { env_vars: { key: "V2_STAGING_BUCKET" + # Push google cloud library docs to the Cloud RAD bucket `docs-staging-v2` value: "docs-staging-v2" } diff --git a/noxfile.py b/noxfile.py index 672b28d6..f041f1f5 100644 --- a/noxfile.py +++ b/noxfile.py @@ -101,7 +101,7 @@ def default(session): "py.test", "--quiet", f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google/cloud", + "--cov=google", "--cov=tests/unit", "--cov-append", "--cov-config=.coveragerc", From 6374e7fc497897fc44c02cd86f57759874c29e82 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 1 Nov 2021 11:34:11 +0000 Subject: [PATCH 085/254] chore: use gapic-generator-python 0.53.4 (#214) - [ ] Regenerate this pull request now. docs: list oneofs in docstring fix(deps): require google-api-core >= 1.28.0 fix(deps): drop packaging dependency committer: busunkim96@ PiperOrigin-RevId: 406468269 Source-Link: https://github.com/googleapis/googleapis/commit/83d81b0c8fc22291a13398d6d77f02dc97a5b6f4 Source-Link: https://github.com/googleapis/googleapis-gen/commit/2ff001fbacb9e77e71d734de5f955c05fdae8526 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMmZmMDAxZmJhY2I5ZTc3ZTcxZDczNGRlNWY5NTVjMDVmZGFlODUyNiJ9 --- .../services/language_service/async_client.py | 40 +++---- .../services/language_service/client.py | 14 +-- .../language_service/transports/base.py | 35 +----- .../transports/grpc_asyncio.py | 1 - .../language_v1/types/language_service.py | 9 ++ .../services/language_service/async_client.py | 40 +++---- .../services/language_service/client.py | 14 +-- .../language_service/transports/base.py | 35 +----- .../transports/grpc_asyncio.py | 1 - .../types/language_service.py | 9 ++ setup.py | 3 +- testing/constraints-3.6.txt | 4 +- .../language_v1/test_language_service.py | 100 ++---------------- .../language_v1beta2/test_language_service.py | 100 ++---------------- 14 files changed, 98 insertions(+), 307 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 86d98569..04146200 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -19,13 +19,15 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core.client_options import ClientOptions # 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 as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.language_v1.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport @@ -162,18 +164,18 @@ def __init__( async def analyze_sentiment( self, - request: language_service.AnalyzeSentimentRequest = None, + request: Union[language_service.AnalyzeSentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. Args: - request (:class:`google.cloud.language_v1.types.AnalyzeSentimentRequest`): + request (Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request message. document (:class:`google.cloud.language_v1.types.Document`): @@ -245,11 +247,11 @@ async def analyze_sentiment( async def analyze_entities( self, - request: language_service.AnalyzeEntitiesRequest = None, + request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: @@ -259,7 +261,7 @@ async def analyze_entities( properties. Args: - request (:class:`google.cloud.language_v1.types.AnalyzeEntitiesRequest`): + request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. document (:class:`google.cloud.language_v1.types.Document`): Input document. @@ -328,11 +330,11 @@ async def analyze_entities( async def analyze_entity_sentiment( self, - request: language_service.AnalyzeEntitySentimentRequest = None, + request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: @@ -342,7 +344,7 @@ async def analyze_entity_sentiment( and its mentions. Args: - request (:class:`google.cloud.language_v1.types.AnalyzeEntitySentimentRequest`): + request (Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis request message. document (:class:`google.cloud.language_v1.types.Document`): @@ -414,11 +416,11 @@ async def analyze_entity_sentiment( async def analyze_syntax( self, - request: language_service.AnalyzeSyntaxRequest = None, + request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: @@ -427,7 +429,7 @@ async def analyze_syntax( tags, dependency trees, and other properties. Args: - request (:class:`google.cloud.language_v1.types.AnalyzeSyntaxRequest`): + request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. document (:class:`google.cloud.language_v1.types.Document`): Input document. @@ -496,17 +498,17 @@ async def analyze_syntax( async def classify_text( self, - request: language_service.ClassifyTextRequest = None, + request: Union[language_service.ClassifyTextRequest, dict] = None, *, document: language_service.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. Args: - request (:class:`google.cloud.language_v1.types.ClassifyTextRequest`): + request (Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]): The request object. The document classification request message. document (:class:`google.cloud.language_v1.types.Document`): @@ -569,12 +571,12 @@ async def classify_text( async def annotate_text( self, - request: language_service.AnnotateTextRequest = None, + request: Union[language_service.AnnotateTextRequest, dict] = None, *, document: language_service.Document = None, features: language_service.AnnotateTextRequest.Features = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: @@ -583,7 +585,7 @@ async def annotate_text( analyzeSyntax provide in one call. Args: - request (:class:`google.cloud.language_v1.types.AnnotateTextRequest`): + request (Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]): The request object. The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 7d4846ec..d2ec0b8e 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.language_v1.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LanguageServiceGrpcTransport @@ -338,7 +340,7 @@ def analyze_sentiment( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: @@ -411,7 +413,7 @@ def analyze_entities( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: @@ -484,7 +486,7 @@ def analyze_entity_sentiment( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: @@ -560,7 +562,7 @@ def analyze_syntax( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: @@ -631,7 +633,7 @@ def classify_text( request: Union[language_service.ClassifyTextRequest, dict] = None, *, document: language_service.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: @@ -696,7 +698,7 @@ def annotate_text( document: language_service.Document = None, features: language_service.AnnotateTextRequest.Features = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 0e4917a5..b38a9acf 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -35,15 +34,6 @@ 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 - class LanguageServiceTransport(abc.ABC): """Abstract transport class for LanguageService.""" @@ -96,7 +86,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -129,29 +119,6 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is 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 - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 46294075..a9292306 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ from google.api_core import grpc_helpers_async # 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 diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index e4ee8e53..c8beb931 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -62,6 +62,13 @@ class EncodingType(proto.Enum): class Document(proto.Message): r"""Represents the input to API methods. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: type_ (google.cloud.language_v1.types.Document.Type): Required. If the type is not set or is ``TYPE_UNSPECIFIED``, @@ -70,12 +77,14 @@ class Document(proto.Message): The content of the input in string format. Cloud audit logging exempt since it is based on user data. + This field is a member of `oneof`_ ``source``. gcs_content_uri (str): The Google Cloud Storage URI where the file content is located. This URI must be of the form: gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. NOTE: Cloud Storage object versioning is not supported. + This field is a member of `oneof`_ ``source``. language (str): The language of the document (if not specified, the language is automatically detected). Both ISO and BCP-47 language diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index c95d4083..c3b06047 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -19,13 +19,15 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core.client_options import ClientOptions # 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 as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.language_v1beta2.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport @@ -162,18 +164,18 @@ def __init__( async def analyze_sentiment( self, - request: language_service.AnalyzeSentimentRequest = None, + request: Union[language_service.AnalyzeSentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. Args: - request (:class:`google.cloud.language_v1beta2.types.AnalyzeSentimentRequest`): + request (Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): @@ -246,11 +248,11 @@ async def analyze_sentiment( async def analyze_entities( self, - request: language_service.AnalyzeEntitiesRequest = None, + request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: @@ -260,7 +262,7 @@ async def analyze_entities( properties. Args: - request (:class:`google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest`): + request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): Required. Input document. @@ -329,11 +331,11 @@ async def analyze_entities( async def analyze_entity_sentiment( self, - request: language_service.AnalyzeEntitySentimentRequest = None, + request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: @@ -343,7 +345,7 @@ async def analyze_entity_sentiment( and its mentions. Args: - request (:class:`google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest`): + request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): @@ -415,11 +417,11 @@ async def analyze_entity_sentiment( async def analyze_syntax( self, - request: language_service.AnalyzeSyntaxRequest = None, + request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: @@ -428,7 +430,7 @@ async def analyze_syntax( tags, dependency trees, and other properties. Args: - request (:class:`google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest`): + request (Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): Required. Input document. @@ -497,17 +499,17 @@ async def analyze_syntax( async def classify_text( self, - request: language_service.ClassifyTextRequest = None, + request: Union[language_service.ClassifyTextRequest, dict] = None, *, document: language_service.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. Args: - request (:class:`google.cloud.language_v1beta2.types.ClassifyTextRequest`): + request (Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]): The request object. The document classification request message. document (:class:`google.cloud.language_v1beta2.types.Document`): @@ -570,12 +572,12 @@ async def classify_text( async def annotate_text( self, - request: language_service.AnnotateTextRequest = None, + request: Union[language_service.AnnotateTextRequest, dict] = None, *, document: language_service.Document = None, features: language_service.AnnotateTextRequest.Features = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: @@ -584,7 +586,7 @@ async def annotate_text( call. Args: - request (:class:`google.cloud.language_v1beta2.types.AnnotateTextRequest`): + request (Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]): The request object. The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 3ed65bb6..e2a0de6e 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -30,6 +30,8 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +OptionalRetry = Union[retries.Retry, object] + from google.cloud.language_v1beta2.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LanguageServiceGrpcTransport @@ -338,7 +340,7 @@ def analyze_sentiment( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: @@ -412,7 +414,7 @@ def analyze_entities( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: @@ -485,7 +487,7 @@ def analyze_entity_sentiment( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: @@ -561,7 +563,7 @@ def analyze_syntax( *, document: language_service.Document = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: @@ -632,7 +634,7 @@ def classify_text( request: Union[language_service.ClassifyTextRequest, dict] = None, *, document: language_service.Document = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: @@ -697,7 +699,7 @@ def annotate_text( document: language_service.Document = None, features: language_service.AnnotateTextRequest.Features = None, encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 59be86ca..99b2bd55 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -15,7 +15,6 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version import pkg_resources import google.auth # type: ignore @@ -35,15 +34,6 @@ 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 - class LanguageServiceTransport(abc.ABC): """Abstract transport class for LanguageService.""" @@ -96,7 +86,7 @@ def __init__( host += ":443" self._host = host - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes @@ -129,29 +119,6 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is 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 - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 2c48f9bc..331a9b1b 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -20,7 +20,6 @@ from google.api_core import grpc_helpers_async # 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 diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 0aabe4a9..840ae888 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -62,6 +62,13 @@ class EncodingType(proto.Enum): class Document(proto.Message): r"""Represents the input to API methods. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: type_ (google.cloud.language_v1beta2.types.Document.Type): Required. If the type is not set or is ``TYPE_UNSPECIFIED``, @@ -70,12 +77,14 @@ class Document(proto.Message): The content of the input in string format. Cloud audit logging exempt since it is based on user data. + This field is a member of `oneof`_ ``source``. gcs_content_uri (str): The Google Cloud Storage URI where the file content is located. This URI must be of the form: gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. NOTE: Cloud Storage object versioning is not supported. + This field is a member of `oneof`_ ``source``. language (str): The language of the document (if not specified, the language is automatically detected). Both ISO and BCP-47 language diff --git a/setup.py b/setup.py index 708e6149..26da52c8 100644 --- a/setup.py +++ b/setup.py @@ -32,9 +32,8 @@ # NOTE: Maintainers, please do not require google-api-core>=2.x.x # Until this issue is closed # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-api-core[grpc] >= 1.26.0, <3.0.0dev", + "google-api-core[grpc] >= 1.28.0, <3.0.0dev", "proto-plus >= 1.10.0", - "packaging >= 14.3", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 90b6c319..9e0fb5ad 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -4,8 +4,6 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.26.0 +google-api-core==1.28.0 proto-plus==1.10.0 libcst==0.2.5 -packaging==14.3 -google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 si transitively required through google-api-core diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index a2a061a3..9be55b98 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -37,28 +36,11 @@ ) from google.cloud.language_v1.services.language_service import LanguageServiceClient from google.cloud.language_v1.services.language_service import transports -from google.cloud.language_v1.services.language_service.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.language_v1.types import language_service from google.oauth2 import service_account import google.auth -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the 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", -) - - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -215,7 +197,7 @@ def test_language_service_client_client_options( options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -232,7 +214,7 @@ def test_language_service_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -249,7 +231,7 @@ def test_language_service_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -278,7 +260,7 @@ def test_language_service_client_client_options( options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -347,7 +329,7 @@ def test_language_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -389,7 +371,7 @@ def test_language_service_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -411,7 +393,7 @@ def test_language_service_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -442,7 +424,7 @@ def test_language_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -473,7 +455,7 @@ def test_language_service_client_client_options_credentials_file( options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1691,7 +1673,6 @@ def test_language_service_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_language_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1715,29 +1696,6 @@ def test_language_service_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_language_service_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.language_v1.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - def test_language_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( @@ -1749,7 +1707,6 @@ def test_language_service_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_language_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1765,21 +1722,6 @@ def test_language_service_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_language_service_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) - LanguageServiceClient() - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id=None, - ) - - @pytest.mark.parametrize( "transport_class", [ @@ -1787,7 +1729,6 @@ def test_language_service_auth_adc_old_google_auth(): transports.LanguageServiceGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_language_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1804,29 +1745,6 @@ def test_language_service_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_language_service_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-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - @pytest.mark.parametrize( "transport_class,grpc_helpers", [ diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 729ad8c1..5b0fd659 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -15,7 +15,6 @@ # import os import mock -import packaging.version import grpc from grpc.experimental import aio @@ -39,28 +38,11 @@ LanguageServiceClient, ) from google.cloud.language_v1beta2.services.language_service import transports -from google.cloud.language_v1beta2.services.language_service.transports.base import ( - _GOOGLE_AUTH_VERSION, -) from google.cloud.language_v1beta2.types import language_service from google.oauth2 import service_account import google.auth -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the 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", -) - - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -217,7 +199,7 @@ def test_language_service_client_client_options( options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -234,7 +216,7 @@ def test_language_service_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -251,7 +233,7 @@ def test_language_service_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -280,7 +262,7 @@ def test_language_service_client_client_options( options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -349,7 +331,7 @@ def test_language_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) if use_client_cert_env == "false": expected_client_cert_source = None @@ -391,7 +373,7 @@ def test_language_service_client_mtls_env_auto( expected_client_cert_source = client_cert_source_callback patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -413,7 +395,7 @@ def test_language_service_client_mtls_env_auto( return_value=False, ): patched.return_value = None - client = client_class() + client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -444,7 +426,7 @@ def test_language_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -475,7 +457,7 @@ def test_language_service_client_client_options_credentials_file( options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(client_options=options) + client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -1693,7 +1675,6 @@ def test_language_service_base_transport(): transport.close() -@requires_google_auth_gte_1_25_0 def test_language_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( @@ -1717,29 +1698,6 @@ def test_language_service_base_transport_with_credentials_file(): ) -@requires_google_auth_lt_1_25_0 -def test_language_service_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.language_v1beta2.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - def test_language_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( @@ -1751,7 +1709,6 @@ def test_language_service_base_transport_with_adc(): adc.assert_called_once() -@requires_google_auth_gte_1_25_0 def test_language_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: @@ -1767,21 +1724,6 @@ def test_language_service_auth_adc(): ) -@requires_google_auth_lt_1_25_0 -def test_language_service_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) - LanguageServiceClient() - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id=None, - ) - - @pytest.mark.parametrize( "transport_class", [ @@ -1789,7 +1731,6 @@ def test_language_service_auth_adc_old_google_auth(): transports.LanguageServiceGrpcAsyncIOTransport, ], ) -@requires_google_auth_gte_1_25_0 def test_language_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1806,29 +1747,6 @@ def test_language_service_transport_auth_adc(transport_class): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_language_service_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-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - @pytest.mark.parametrize( "transport_class,grpc_helpers", [ From 26eac17a20767f354c06da5485e36c9f51d66f92 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Tue, 2 Nov 2021 17:44:14 +0000 Subject: [PATCH 086/254] chore: release 2.3.1 (#215) :robot: I have created a release \*beep\* \*boop\* --- ### [2.3.1](https://www.github.com/googleapis/python-language/compare/v2.3.0...v2.3.1) (2021-11-01) ### Bug Fixes * **deps:** drop packaging dependency ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) * **deps:** require google-api-core >= 1.28.0 ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) ### Documentation * list oneofs in docstring ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 13 +++++++++++++ setup.py | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 646b0782..1a9bbfab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ [1]: https://pypi.org/project/google-cloud-language/#history +### [2.3.1](https://www.github.com/googleapis/python-language/compare/v2.3.0...v2.3.1) (2021-11-01) + + +### Bug Fixes + +* **deps:** drop packaging dependency ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) +* **deps:** require google-api-core >= 1.28.0 ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) + + +### Documentation + +* list oneofs in docstring ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) + ## [2.3.0](https://www.github.com/googleapis/python-language/compare/v2.2.2...v2.3.0) (2021-10-09) diff --git a/setup.py b/setup.py index 26da52c8..04e3a675 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.3.0" +version = "2.3.1" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 295caa17dbc5a871e1f1ac07ca0f783873ac5c47 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 2 Nov 2021 20:31:07 +0100 Subject: [PATCH 087/254] chore(deps): update dependency google-auth to v2.3.0 (#206) Co-authored-by: Anthonios Partheniou --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 2d206082..7e4f4a6b 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.24.0 -google-auth==2.2.1 +google-auth==2.3.0 google-auth-httplib2==0.1.0 From 81bdc0cbba57c601481c55201dd17f307340a817 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 3 Nov 2021 12:31:21 +0100 Subject: [PATCH 088/254] chore(deps): update all dependencies (#216) --- samples/snippets/api/requirements.txt | 4 ++-- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 7e4f4a6b..39362509 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.24.0 -google-auth==2.3.0 +google-api-python-client==2.29.0 +google-auth==2.3.3 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 2323f5be..0a0e0056 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.2.2 +google-cloud-language==2.3.1 numpy==1.20.1; python_version > '3.6' numpy==1.19.5; python_version <= '3.6' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index fc0ee401..d2b8f2f0 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.2 +google-cloud-language==2.3.1 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index fc0ee401..d2b8f2f0 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.2 +google-cloud-language==2.3.1 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index fc0ee401..d2b8f2f0 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.2.2 +google-cloud-language==2.3.1 From 2b9e261e80277ade8f97ea63755608a75bce00d5 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 9 Nov 2021 17:00:26 +0100 Subject: [PATCH 089/254] chore(deps): update dependency google-api-python-client to v2.30.0 (#218) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 39362509..decb2aef 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.29.0 +google-api-python-client==2.30.0 google-auth==2.3.3 google-auth-httplib2==0.1.0 From 9d8e5dea389d603ff254dbb5e0bae2f8c50814a6 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 9 Nov 2021 13:05:46 -0500 Subject: [PATCH 090/254] chore: delete owlbot.py (#213) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: delete owlbot.py * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * remove redundant docs Co-authored-by: Owl Bot --- docs/api.rst | 40 ---------- docs/index.rst | 42 ++++++++++- docs/usage.rst | 199 ------------------------------------------------- noxfile.py | 2 +- owlbot.py | 51 ------------- 5 files changed, 39 insertions(+), 295 deletions(-) delete mode 100644 docs/api.rst delete mode 100644 docs/usage.rst delete mode 100644 owlbot.py diff --git a/docs/api.rst b/docs/api.rst deleted file mode 100644 index 8720e9fa..00000000 --- a/docs/api.rst +++ /dev/null @@ -1,40 +0,0 @@ -Language Client API Reference -============================= - -This package includes clients for multiple versions of the Natural Language -API. By default, you will get ``v1``, the latest GA version. - -.. toctree:: - :maxdepth: 2 - - language_v1/services - language_v1/types - -If you are interested in beta features ahead of the latest GA, you may -opt-in to the v1.1 beta, which is spelled ``v1beta2``. In order to do this, -you will want to import from ``google.cloud.language_v1beta2`` in lieu of -``google.cloud.language``. - -An API and type reference is provided for the v1.1 beta also: - -.. toctree:: - :maxdepth: 2 - - language_v1beta2/services - language_v1beta2/types - -Migration Guide ---------------- - -See the guide below for instructions on migrating to the 2.x release of this library. - -.. toctree:: - :maxdepth: 2 - - UPGRADING - -.. note:: - - The client for the beta API is provided on a provisional basis. The API - surface is subject to change, and it is possible that this client will be - deprecated or removed after its features become GA. diff --git a/docs/index.rst b/docs/index.rst index 368f811d..524632b7 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -2,10 +2,44 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Natural Language. +By default, you will get version ``language_v1``. + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + language_v1/services + language_v1/types + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + language_v1beta2/services + language_v1beta2/types + + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the latest version. + +.. toctree:: + :maxdepth: 2 + +  UPGRADING + + +Changelog +--------- + +For a list of all ``google-cloud-language`` releases: .. toctree:: - :maxdepth: 2 + :maxdepth: 2 - usage - api - changelog + changelog diff --git a/docs/usage.rst b/docs/usage.rst deleted file mode 100644 index f2e45934..00000000 --- a/docs/usage.rst +++ /dev/null @@ -1,199 +0,0 @@ -Using the Language Client -========================= - -Documents -********* - -The Google Natural Language API has the following supported methods: - -- `analyzeEntities`_ -- `analyzeSentiment`_ -- `analyzeEntitySentiment`_ -- `annotateText`_ -- `classifyText`_ - -and each method uses a :class:`~.language_v1.types.Document` for representing -text. - - .. code-block:: python - - >>> document = language.types.Document( - ... content='Google, headquartered in Mountain View, unveiled the ' - ... 'new Android phone at the Consumer Electronic Show. ' - ... 'Sundar Pichai said in his keynote that users love ' - ... 'their new Android phones.', - ... language='en', - ... type='PLAIN_TEXT', - ... ) - - -The document's language defaults to ``None``, which will cause the API to -auto-detect the language. - -In addition, you can construct an HTML document: - - .. code-block:: python - - >>> html_content = """\ - ... - ... - ... El Tiempo de las Historias</time> - ... </head> - ... <body> - ... <p>La vaca saltó sobre la luna.</p> - ... </body> - ... </html> - ... """ - >>> document = language.types.Document( - ... content=html_content, - ... language='es', - ... type='HTML', - ... ) - -The ``language`` argument can be either ISO-639-1 or BCP-47 language -codes. The API reference page contains the full list of `supported languages`_. - -.. _supported languages: https://cloud.google.com/natural-language/docs/languages - - -In addition to supplying the text / HTML content, a document can refer -to content stored in `Google Cloud Storage`_. - - .. code-block:: python - - >>> document = language.types.Document( - ... gcs_content_uri='gs://my-text-bucket/sentiment-me.txt', - ... type=language.enums.HTML, - ... ) - -.. _analyzeEntities: https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/analyzeEntities -.. _analyzeSentiment: https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/analyzeSentiment -.. _analyzeEntitySentiment: https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/analyzeEntitySentiment -.. _annotateText: https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/annotateText -.. _classifyText: https://cloud.google.com/natural-language/docs/reference/rest/v1/documents/classifyText -.. _Google Cloud Storage: https://cloud.google.com/storage/ - -Analyze Entities -**************** - -The :meth:`~.language_v1.LanguageServiceClient.analyze_entities` -method finds named entities (i.e. proper names) in the text. This method -returns a :class:`~.language_v1.types.AnalyzeEntitiesResponse`. - - .. code-block:: python - - >>> document = language.types.Document( - ... content='Michelangelo Caravaggio, Italian painter, is ' - ... 'known for "The Calling of Saint Matthew".', - ... type=language.enums.Document.Type.PLAIN_TEXT, - ... ) - >>> response = client.analyze_entities( - ... document=document, - ... encoding_type='UTF32', - ... ) - >>> for entity in response.entities: - ... print('=' * 20) - ... print(' name: {0}'.format(entity.name)) - ... print(' type: {0}'.format(entity.type)) - ... print(' metadata: {0}'.format(entity.metadata)) - ... print(' salience: {0}'.format(entity.salience)) - ==================== - name: Michelangelo Caravaggio - type: PERSON - metadata: {'wikipedia_url': 'https://en.wikipedia.org/wiki/Caravaggio'} - salience: 0.7615959 - ==================== - name: Italian - type: LOCATION - metadata: {'wikipedia_url': 'https://en.wikipedia.org/wiki/Italy'} - salience: 0.19960518 - ==================== - name: The Calling of Saint Matthew - type: EVENT - metadata: {'wikipedia_url': 'https://en.wikipedia.org/wiki/The_Calling_of_St_Matthew_(Caravaggio)'} - salience: 0.038798928 - -.. note:: - - It is recommended to send an ``encoding_type`` argument to Natural - Language methods, so they provide useful offsets for the data they return. - While the correct value varies by environment, in Python you *usually* - want ``UTF32``. - - -Analyze Sentiment -***************** - -The :meth:`~.language_v1.LanguageServiceClient.analyze_sentiment` method -analyzes the sentiment of the provided text. This method returns a -:class:`~.language_v1.types.AnalyzeSentimentResponse`. - - .. code-block:: python - - >>> document = language.types.Document( - ... content='Jogging is not very fun.', - ... type='PLAIN_TEXT', - ... ) - >>> response = client.analyze_sentiment( - ... document=document, - ... encoding_type='UTF32', - ... ) - >>> sentiment = response.document_sentiment - >>> print(sentiment.score) - -1 - >>> print(sentiment.magnitude) - 0.8 - -.. note:: - - It is recommended to send an ``encoding_type`` argument to Natural - Language methods, so they provide useful offsets for the data they return. - While the correct value varies by environment, in Python you *usually* - want ``UTF32``. - - -Analyze Entity Sentiment -************************ - -The :meth:`~.language_v1.LanguageServiceClient.analyze_entity_sentiment` -method is effectively the amalgamation of -:meth:`~.language_v1.LanguageServiceClient.analyze_entities` and -:meth:`~.language_v1.LanguageServiceClient.analyze_sentiment`. -This method returns a -:class:`~.language_v1.types.AnalyzeEntitySentimentResponse`. - -.. code-block:: python - - >>> document = language.types.Document( - ... content='Mona said that jogging is very fun.', - ... type='PLAIN_TEXT', - ... ) - >>> response = client.analyze_entity_sentiment( - ... document=document, - ... encoding_type='UTF32', - ... ) - >>> entities = response.entities - >>> entities[0].name - 'Mona' - >>> entities[1].name - 'jogging' - >>> entities[1].sentiment.magnitude - 0.8 - >>> entities[1].sentiment.score - 0.8 - -.. note:: - - It is recommended to send an ``encoding_type`` argument to Natural - Language methods, so they provide useful offsets for the data they return. - While the correct value varies by environment, in Python you *usually* - want ``UTF32``. - - -Annotate Text -************* - -The :meth:`~.language_v1.LanguageServiceClient.annotate_text` method -analyzes a document and is intended for users who are familiar with -machine learning and need in-depth text features to build upon. This method -returns a :class:`~.language_v1.types.AnnotateTextResponse`. diff --git a/noxfile.py b/noxfile.py index f041f1f5..2a2001c4 100644 --- a/noxfile.py +++ b/noxfile.py @@ -175,7 +175,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=98") + session.run("coverage", "report", "--show-missing", "--fail-under=100") session.run("coverage", "erase") diff --git a/owlbot.py b/owlbot.py deleted file mode 100644 index 11b0c990..00000000 --- a/owlbot.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2018 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. - -"""This script is used to synthesize generated parts of this library.""" - -import synthtool as s -from synthtool import gcp -from synthtool.languages import python - -common = gcp.CommonTemplates() -default_version = "v1" - -for library in s.get_staging_dirs(default_version): - # Work around generator issue https://github.com/googleapis/gapic-generator-python/issues/902 - s.replace(library / f"google/cloud/language_{library.name}/types/language_service.py", - r"""Represents the input to API methods. - Attributes:""", - r"""Represents the input to API methods.\n - Attributes:""") - - s.move(library, excludes=["docs/index.rst", "README.rst", "setup.py"]) - -s.remove_staging_dirs() - -# ---------------------------------------------------------------------------- -# Add templated files -# ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=98, samples=True, microgenerator=True,) - -s.move(templated_files, excludes=['.coveragerc']) - -s.shell.run(["nox", "-s", "blacken"], hide_output=False) - -# ---------------------------------------------------------------------------- -# Samples templates -# ---------------------------------------------------------------------------- - -python.py_samples(skip_readmes=True) - -s.shell.run(["nox", "-s", "blacken"], hide_output=False) From 711a028d5a82259e266081c9edba04bff731970f Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 9 Nov 2021 19:14:26 -0500 Subject: [PATCH 091/254] chore: use gapic-generator-python 0.56.2 (#219) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: update Java and Python dependencies PiperOrigin-RevId: 408420890 Source-Link: https://github.com/googleapis/googleapis/commit/2921f9fb3bfbd16f6b2da0104373e2b47a80a65e Source-Link: https://github.com/googleapis/googleapis-gen/commit/6598ca8cbbf5226733a099c4506518a5af6ff74c Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjU5OGNhOGNiYmY1MjI2NzMzYTA5OWM0NTA2NTE4YTVhZjZmZjc0YyJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../services/language_service/async_client.py | 13 ++- .../services/language_service/client.py | 25 +++-- .../language_service/transports/base.py | 8 +- .../language_service/transports/grpc.py | 4 +- .../transports/grpc_asyncio.py | 4 +- .../language_v1/types/language_service.py | 2 + .../services/language_service/async_client.py | 13 ++- .../services/language_service/client.py | 25 +++-- .../language_service/transports/base.py | 8 +- .../language_service/transports/grpc.py | 4 +- .../transports/grpc_asyncio.py | 4 +- .../types/language_service.py | 2 + .../language_v1/test_language_service.py | 100 +++++++++++++----- .../language_v1beta2/test_language_service.py | 100 +++++++++++++----- 14 files changed, 214 insertions(+), 98 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 04146200..8121cc51 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -19,14 +19,17 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # 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.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index d2ec0b8e..ea4653b1 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions 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 client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries 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 -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO @@ -268,8 +270,15 @@ def __init__( client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ( + "true", + "false", + ): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + use_client_cert = ( + os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" ) client_cert_source_func = None diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index b38a9acf..8aedbe77 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -18,10 +18,10 @@ import pkg_resources 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 +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 4a85b2e2..94941e4e 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -16,8 +16,8 @@ import warnings 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.api_core import grpc_helpers +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index a9292306..681336e2 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -16,8 +16,8 @@ import warnings 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 gapic_v1 +from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index c8beb931..25a6fff4 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -77,6 +77,7 @@ class Document(proto.Message): The content of the input in string format. Cloud audit logging exempt since it is based on user data. + This field is a member of `oneof`_ ``source``. gcs_content_uri (str): The Google Cloud Storage URI where the file content is @@ -84,6 +85,7 @@ class Document(proto.Message): gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. NOTE: Cloud Storage object versioning is not supported. + This field is a member of `oneof`_ ``source``. language (str): The language of the document (if not specified, the language diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index c3b06047..366e2acf 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -19,14 +19,17 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # 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.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1beta2.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index e2a0de6e..29fd4df7 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions 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 client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries 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 -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1beta2.types import language_service from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO @@ -268,8 +270,15 @@ def __init__( client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ( + "true", + "false", + ): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + use_client_cert = ( + os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" ) client_cert_source_func = None diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 99b2bd55..5a7f54c7 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -18,10 +18,10 @@ import pkg_resources 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 +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 7f7c7b2d..2936db35 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -16,8 +16,8 @@ import warnings 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.api_core import grpc_helpers +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 331a9b1b..5e7e6213 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -16,8 +16,8 @@ import warnings 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 gapic_v1 +from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 840ae888..68f9297b 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -77,6 +77,7 @@ class Document(proto.Message): The content of the input in string format. Cloud audit logging exempt since it is based on user data. + This field is a member of `oneof`_ ``source``. gcs_content_uri (str): The Google Cloud Storage URI where the file content is @@ -84,6 +85,7 @@ class Document(proto.Message): gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. NOTE: Cloud Storage object versioning is not supported. + This field is a member of `oneof`_ ``source``. language (str): The language of the document (if not specified, the language diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 9be55b98..2956a9c1 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -600,10 +600,14 @@ def test_analyze_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_sentiment_flattened_error(): @@ -650,10 +654,14 @@ async def test_analyze_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -778,10 +786,14 @@ def test_analyze_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_entities_flattened_error(): @@ -826,10 +838,14 @@ async def test_analyze_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -962,10 +978,14 @@ def test_analyze_entity_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_entity_sentiment_flattened_error(): @@ -1012,10 +1032,14 @@ async def test_analyze_entity_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -1139,10 +1163,14 @@ def test_analyze_syntax_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_syntax_flattened_error(): @@ -1187,10 +1215,14 @@ async def test_analyze_syntax_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -1309,9 +1341,11 @@ def test_classify_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) + assert arg == mock_val def test_classify_text_flattened_error(): @@ -1354,9 +1388,11 @@ async def test_classify_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) + assert arg == mock_val @pytest.mark.asyncio @@ -1480,13 +1516,17 @@ def test_annotate_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( - extract_syntax=True - ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].features + mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_annotate_text_flattened_error(): @@ -1533,13 +1573,17 @@ async def test_annotate_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( - extract_syntax=True - ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].features + mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 5b0fd659..703d778f 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -602,10 +602,14 @@ def test_analyze_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_sentiment_flattened_error(): @@ -652,10 +656,14 @@ async def test_analyze_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -780,10 +788,14 @@ def test_analyze_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_entities_flattened_error(): @@ -828,10 +840,14 @@ async def test_analyze_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -964,10 +980,14 @@ def test_analyze_entity_sentiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_entity_sentiment_flattened_error(): @@ -1014,10 +1034,14 @@ async def test_analyze_entity_sentiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -1141,10 +1165,14 @@ def test_analyze_syntax_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_analyze_syntax_flattened_error(): @@ -1189,10 +1217,14 @@ async def test_analyze_syntax_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio @@ -1311,9 +1343,11 @@ def test_classify_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) + assert arg == mock_val def test_classify_text_flattened_error(): @@ -1356,9 +1390,11 @@ async def test_classify_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) + assert arg == mock_val @pytest.mark.asyncio @@ -1482,13 +1518,17 @@ def test_annotate_text_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( - extract_syntax=True - ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].features + mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val def test_annotate_text_flattened_error(): @@ -1535,13 +1575,17 @@ async def test_annotate_text_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].document == language_service.Document( + arg = args[0].document + mock_val = language_service.Document( type_=language_service.Document.Type.PLAIN_TEXT ) - assert args[0].features == language_service.AnnotateTextRequest.Features( - extract_syntax=True - ) - assert args[0].encoding_type == language_service.EncodingType.UTF8 + assert arg == mock_val + arg = args[0].features + mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) + assert arg == mock_val + arg = args[0].encoding_type + mock_val = language_service.EncodingType.UTF8 + assert arg == mock_val @pytest.mark.asyncio From 9e03bdad63c67c0a931c5769db686b407dbf9340 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 10 Nov 2021 20:37:03 -0500 Subject: [PATCH 092/254] chore(python): run blacken session for all directories with a noxfile (#220) Source-Link: https://github.com/googleapis/synthtool/commit/bc0de6ee2489da6fb8eafd021a8c58b5cc30c947 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:39ad8c0570e4f5d2d3124a509de4fe975e799e2b97e0f58aed88f8880d5a8b60 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/classify_text/classify_text_tutorial.py | 2 +- samples/snippets/cloud-client/v1/quickstart.py | 8 ++++++-- samples/snippets/cloud-client/v1/set_endpoint.py | 4 +++- .../generated-samples/v1/language_sentiment_text.py | 2 +- samples/snippets/sentiment/sentiment_analysis.py | 6 ++++-- 6 files changed, 16 insertions(+), 8 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index cb89b2e3..63bf76ea 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ec49167c606648a063d1222220b48119c912562849a0528f35bfb592a9f72737 + digest: sha256:39ad8c0570e4f5d2d3124a509de4fe975e799e2b97e0f58aed88f8880d5a8b60 diff --git a/samples/snippets/classify_text/classify_text_tutorial.py b/samples/snippets/classify_text/classify_text_tutorial.py index 9c05b83f..675f8499 100644 --- a/samples/snippets/classify_text/classify_text_tutorial.py +++ b/samples/snippets/classify_text/classify_text_tutorial.py @@ -42,7 +42,7 @@ def classify(text, verbose=True): document = language_v1.Document( content=text, type_=language_v1.Document.Type.PLAIN_TEXT ) - response = language_client.classify_text(request={'document': document}) + response = language_client.classify_text(request={"document": document}) categories = response.categories result = {} diff --git a/samples/snippets/cloud-client/v1/quickstart.py b/samples/snippets/cloud-client/v1/quickstart.py index 4c4b06b5..b9b0e96c 100644 --- a/samples/snippets/cloud-client/v1/quickstart.py +++ b/samples/snippets/cloud-client/v1/quickstart.py @@ -30,10 +30,14 @@ def run_quickstart(): # The text to analyze text = u"Hello, world!" - document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT) + document = language_v1.Document( + content=text, type_=language_v1.Document.Type.PLAIN_TEXT + ) # Detects the sentiment of the text - sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment + sentiment = client.analyze_sentiment( + request={"document": document} + ).document_sentiment print("Text: {}".format(text)) print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude)) diff --git a/samples/snippets/cloud-client/v1/set_endpoint.py b/samples/snippets/cloud-client/v1/set_endpoint.py index e9ad97d3..c49537a5 100644 --- a/samples/snippets/cloud-client/v1/set_endpoint.py +++ b/samples/snippets/cloud-client/v1/set_endpoint.py @@ -31,7 +31,9 @@ def set_endpoint(): ) # Detects the sentiment of the text - sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment + sentiment = client.analyze_sentiment( + request={"document": document} + ).document_sentiment print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude)) diff --git a/samples/snippets/generated-samples/v1/language_sentiment_text.py b/samples/snippets/generated-samples/v1/language_sentiment_text.py index 9f975023..4170ddbc 100644 --- a/samples/snippets/generated-samples/v1/language_sentiment_text.py +++ b/samples/snippets/generated-samples/v1/language_sentiment_text.py @@ -39,7 +39,7 @@ def sample_analyze_sentiment(content): type_ = language_v1.Document.Type.PLAIN_TEXT document = {"type_": type_, "content": content} - response = client.analyze_sentiment(request={'document': document}) + response = client.analyze_sentiment(request={"document": document}) sentiment = response.document_sentiment print("Score: {}".format(sentiment.score)) print("Magnitude: {}".format(sentiment.magnitude)) diff --git a/samples/snippets/sentiment/sentiment_analysis.py b/samples/snippets/sentiment/sentiment_analysis.py index 2333bf82..e82c3a68 100644 --- a/samples/snippets/sentiment/sentiment_analysis.py +++ b/samples/snippets/sentiment/sentiment_analysis.py @@ -51,8 +51,10 @@ def analyze(movie_review_filename): # Instantiates a plain text document. content = review_file.read() - document = language_v1.Document(content=content, type_=language_v1.Document.Type.PLAIN_TEXT) - annotations = client.analyze_sentiment(request={'document': document}) + document = language_v1.Document( + content=content, type_=language_v1.Document.Type.PLAIN_TEXT + ) + annotations = client.analyze_sentiment(request={"document": document}) # Print the results print_result(annotations) From 94588c95c09107a2b72fb5a6303e2f82010c9ac3 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Thu, 11 Nov 2021 11:24:54 -0500 Subject: [PATCH 093/254] chore: assign googleapis/cdpe-cloudai as codeowner (#221) assign @googleapis/cdpe-cloudai as codeowner --- .repo-metadata.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index 24d5ceb2..0007b27f 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -12,5 +12,5 @@ "api_id": "language.googleapis.com", "requires_billing": true, "default_version": "v1", - "codeowner_team": "" + "codeowner_team": "@googleapis/cdpe-cloudai" } From 6f1957c7c3989e96670bc43b41b575ef948c00ad Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 11 Nov 2021 12:25:33 -0500 Subject: [PATCH 094/254] chore(python): add .github/CODEOWNERS as a templated file (#222) Source-Link: https://github.com/googleapis/synthtool/commit/c5026b3217973a8db55db8ee85feee0e9a65e295 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:0e18b9475fbeb12d9ad4302283171edebb6baf2dfca1bd215ee3b34ed79d95d7 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 2 +- .github/CODEOWNERS | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 63bf76ea..7519fa3a 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:39ad8c0570e4f5d2d3124a509de4fe975e799e2b97e0f58aed88f8880d5a8b60 + digest: sha256:0e18b9475fbeb12d9ad4302283171edebb6baf2dfca1bd215ee3b34ed79d95d7 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 3319f86b..b26afefd 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,9 +3,10 @@ # # For syntax help see: # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax +# Note: This file is autogenerated. To make changes to the codeowner team, please update .repo-metadata.json. -# The @googleapis/yoshi-python is the default owner for changes in this repo -* @googleapis/yoshi-python +# @googleapis/yoshi-python @googleapis/cdpe-cloudai are the default owners for changes in this repo +* @googleapis/yoshi-python @googleapis/cdpe-cloudai -# The python-samples-reviewers team is the default owner for samples changes -/samples/ @telpirion @sirtorry @lucaswadedavis @googleapis/python-samples-owners +# @googleapis/python-samples-owners @googleapis/cdpe-cloudai are the default owners for samples changes +/samples/ @googleapis/python-samples-owners @googleapis/cdpe-cloudai From 13ef54ba67e518e9cf8fb7c2324487d6bfc45b13 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Thu, 18 Nov 2021 18:56:29 +0100 Subject: [PATCH 095/254] chore(deps): update dependency google-api-python-client to v2.31.0 (#224) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index decb2aef..f324442a 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.30.0 +google-api-python-client==2.31.0 google-auth==2.3.3 google-auth-httplib2==0.1.0 From 51eaded4535113168d610eed77c8068a7e52e972 Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Thu, 18 Nov 2021 16:32:01 -0500 Subject: [PATCH 096/254] chore: update doc links from googleapis.dev to cloud.google.com (#223) Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .repo-metadata.json | 2 +- README.rst | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index 0007b27f..1239a649 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -2,7 +2,7 @@ "name": "language", "name_pretty": "Natural Language", "product_documentation": "https://cloud.google.com/natural-language/docs/", - "client_documentation": "https://googleapis.dev/python/language/latest", + "client_documentation": "https://cloud.google.com/python/docs/reference/language/latest", "issue_tracker": "https://issuetracker.google.com/savedsearches/559753", "release_level": "ga", "language": "python", diff --git a/README.rst b/README.rst index 958246b4..1311cd55 100644 --- a/README.rst +++ b/README.rst @@ -24,7 +24,7 @@ with your document storage on Google Cloud Storage. :target: https://pypi.org/project/google-cloud-language/ .. _Google Cloud Natural Language: https://cloud.google.com/natural-language/ .. _Product Documentation: https://cloud.google.com/natural-language/docs -.. _Client Library Documentation: https://googleapis.dev/python/language/latest +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/language/latest .. note:: @@ -101,4 +101,4 @@ Next Steps - Read the `Product documentation`_ to learn more about the product and see How-to Guides. -.. _Usage documentation: https://googleapis.dev/python/language/latest +.. _Usage documentation: https://cloud.google.com/python/docs/reference/language/latest From 258269d6cf4945576fa57f2f89baafe7ad8551de Mon Sep 17 00:00:00 2001 From: Dina Graves Portman <dinagraves@google.com> Date: Fri, 3 Dec 2021 13:44:55 -0500 Subject: [PATCH 097/254] chore: updating numpy (#226) * Testing if numpy works for 3.10 yet Does numpy work for 3.10? * Update requirements.txt * Update requirements.txt * Update requirements.txt * Update requirements.txt --- samples/snippets/classify_text/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 0a0e0056..b4f8763f 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ google-cloud-language==2.3.1 -numpy==1.20.1; python_version > '3.6' +numpy==1.21.4; python_version > '3.6' numpy==1.19.5; python_version <= '3.6' From 27518ff4dbe9b41a07e6989292f9d246b35db594 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Fri, 3 Dec 2021 19:51:46 +0100 Subject: [PATCH 098/254] chore(deps): update dependency google-api-python-client to v2.32.0 (#225) Co-authored-by: Dina Graves Portman <dinagraves@google.com> --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index f324442a..83ea01b0 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.31.0 +google-api-python-client==2.32.0 google-auth==2.3.3 google-auth-httplib2==0.1.0 From f5ffec6f4eec2d50701bc9c28a99e2a5a536e0b6 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 7 Dec 2021 19:34:55 +0100 Subject: [PATCH 099/254] chore(deps): update dependency google-api-python-client to v2.33.0 (#229) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 83ea01b0..56e7e8e2 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.32.0 +google-api-python-client==2.33.0 google-auth==2.3.3 google-auth-httplib2==0.1.0 From 01367d7b1e0ddba6e6b920f125730aa97d51ada0 Mon Sep 17 00:00:00 2001 From: Andrew Ferlitsch <aferlitsch@google.com> Date: Tue, 7 Dec 2021 14:08:58 -0800 Subject: [PATCH 100/254] fix: Document -> types.Document (#227) --- samples/v1/language_entity_sentiment_text.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/v1/language_entity_sentiment_text.py b/samples/v1/language_entity_sentiment_text.py index b28434df..4e1341d5 100644 --- a/samples/v1/language_entity_sentiment_text.py +++ b/samples/v1/language_entity_sentiment_text.py @@ -40,7 +40,7 @@ def sample_analyze_entity_sentiment(text_content): # text_content = 'Grapes are good. Bananas are bad.' # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT + type_ = language_v1.types.Document.Type.PLAIN_TEXT # Optional. If not specified, the language is automatically detected. # For list of supported languages: From 9f523eef3a558e309d24b75a1753d6d1adf5ce9b Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Tue, 28 Dec 2021 13:18:11 -0500 Subject: [PATCH 101/254] chore: update .repo-metadata.json (#233) --- .repo-metadata.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index 1239a649..2997cbdb 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -4,7 +4,7 @@ "product_documentation": "https://cloud.google.com/natural-language/docs/", "client_documentation": "https://cloud.google.com/python/docs/reference/language/latest", "issue_tracker": "https://issuetracker.google.com/savedsearches/559753", - "release_level": "ga", + "release_level": "stable", "language": "python", "library_type": "GAPIC_AUTO", "repo": "googleapis/python-language", @@ -12,5 +12,6 @@ "api_id": "language.googleapis.com", "requires_billing": true, "default_version": "v1", - "codeowner_team": "@googleapis/cdpe-cloudai" + "codeowner_team": "@googleapis/cdpe-cloudai", + "api_shortname": "language" } From 6d32f36fd4e3ff9c48f08a1ac64daa5e19532d48 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 17:08:23 +0000 Subject: [PATCH 102/254] chore: use python-samples-reviewers (#237) --- .github/.OwlBot.lock.yaml | 2 +- .github/CODEOWNERS | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 7519fa3a..f33299dd 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:0e18b9475fbeb12d9ad4302283171edebb6baf2dfca1bd215ee3b34ed79d95d7 + digest: sha256:899d5d7cc340fa8ef9d8ae1a8cfba362c6898584f779e156f25ee828ba824610 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index b26afefd..62aced93 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,5 +8,5 @@ # @googleapis/yoshi-python @googleapis/cdpe-cloudai are the default owners for changes in this repo * @googleapis/yoshi-python @googleapis/cdpe-cloudai -# @googleapis/python-samples-owners @googleapis/cdpe-cloudai are the default owners for samples changes -/samples/ @googleapis/python-samples-owners @googleapis/cdpe-cloudai +# @googleapis/python-samples-reviewers @googleapis/cdpe-cloudai are the default owners for samples changes +/samples/ @googleapis/python-samples-reviewers @googleapis/cdpe-cloudai From f5b164cc97bc6ec863403a03c1da7244267dbb57 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Sat, 8 Jan 2022 01:39:03 +0100 Subject: [PATCH 103/254] chore(deps): update dependency google-api-python-client to v2.34.0 (#236) Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 56e7e8e2..2802f988 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.33.0 +google-api-python-client==2.34.0 google-auth==2.3.3 google-auth-httplib2==0.1.0 From 3a97d07003ea418cdd5dc16c30e3a111b2067b26 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 8 Jan 2022 06:14:07 -0500 Subject: [PATCH 104/254] chore: use gapic-generator-python 0.58.4 (#235) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: use gapic-generator-python 0.58.4 fix: provide appropriate mock values for message body fields committer: dovs PiperOrigin-RevId: 419025932 Source-Link: https://github.com/googleapis/googleapis/commit/73da6697f598f1ba30618924936a59f8e457ec89 Source-Link: https://github.com/googleapis/googleapis-gen/commit/46df624a54b9ed47c1a7eefb7a49413cf7b82f98 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDZkZjYyNGE1NGI5ZWQ0N2MxYTdlZWZiN2E0OTQxM2NmN2I4MmY5OCJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .../language_service/transports/base.py | 1 - .../language_service/transports/base.py | 1 - .../language_v1/test_language_service.py | 74 +++++++------------ .../language_v1beta2/test_language_service.py | 74 +++++++------------ 4 files changed, 50 insertions(+), 100 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 8aedbe77..5d147fc1 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -102,7 +102,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 5a7f54c7..ea3aba83 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -102,7 +102,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 2956a9c1..3304ab5e 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -247,20 +247,20 @@ def test_language_service_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -329,7 +329,7 @@ def test_language_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -424,7 +424,7 @@ def test_language_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -455,7 +455,7 @@ def test_language_service_client_client_options_credentials_file( options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -488,9 +488,10 @@ def test_language_service_client_client_options_from_dict(): ) -def test_analyze_sentiment( - transport: str = "grpc", request_type=language_service.AnalyzeSentimentRequest -): +@pytest.mark.parametrize( + "request_type", [language_service.AnalyzeSentimentRequest, dict,] +) +def test_analyze_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -519,10 +520,6 @@ def test_analyze_sentiment( assert response.language == "language_value" -def test_analyze_sentiment_from_dict(): - test_analyze_sentiment(request_type=dict) - - def test_analyze_sentiment_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. @@ -682,9 +679,10 @@ async def test_analyze_sentiment_flattened_error_async(): ) -def test_analyze_entities( - transport: str = "grpc", request_type=language_service.AnalyzeEntitiesRequest -): +@pytest.mark.parametrize( + "request_type", [language_service.AnalyzeEntitiesRequest, dict,] +) +def test_analyze_entities(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -711,10 +709,6 @@ def test_analyze_entities( assert response.language == "language_value" -def test_analyze_entities_from_dict(): - test_analyze_entities(request_type=dict) - - def test_analyze_entities_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. @@ -866,9 +860,10 @@ async def test_analyze_entities_flattened_error_async(): ) -def test_analyze_entity_sentiment( - transport: str = "grpc", request_type=language_service.AnalyzeEntitySentimentRequest -): +@pytest.mark.parametrize( + "request_type", [language_service.AnalyzeEntitySentimentRequest, dict,] +) +def test_analyze_entity_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -897,10 +892,6 @@ def test_analyze_entity_sentiment( assert response.language == "language_value" -def test_analyze_entity_sentiment_from_dict(): - test_analyze_entity_sentiment(request_type=dict) - - def test_analyze_entity_sentiment_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. @@ -1060,9 +1051,8 @@ async def test_analyze_entity_sentiment_flattened_error_async(): ) -def test_analyze_syntax( - transport: str = "grpc", request_type=language_service.AnalyzeSyntaxRequest -): +@pytest.mark.parametrize("request_type", [language_service.AnalyzeSyntaxRequest, dict,]) +def test_analyze_syntax(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1089,10 +1079,6 @@ def test_analyze_syntax( assert response.language == "language_value" -def test_analyze_syntax_from_dict(): - test_analyze_syntax(request_type=dict) - - def test_analyze_syntax_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. @@ -1243,9 +1229,8 @@ async def test_analyze_syntax_flattened_error_async(): ) -def test_classify_text( - transport: str = "grpc", request_type=language_service.ClassifyTextRequest -): +@pytest.mark.parametrize("request_type", [language_service.ClassifyTextRequest, dict,]) +def test_classify_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1269,10 +1254,6 @@ def test_classify_text( assert isinstance(response, language_service.ClassifyTextResponse) -def test_classify_text_from_dict(): - test_classify_text(request_type=dict) - - def test_classify_text_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. @@ -1412,9 +1393,8 @@ async def test_classify_text_flattened_error_async(): ) -def test_annotate_text( - transport: str = "grpc", request_type=language_service.AnnotateTextRequest -): +@pytest.mark.parametrize("request_type", [language_service.AnnotateTextRequest, dict,]) +def test_annotate_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1441,10 +1421,6 @@ def test_annotate_text( assert response.language == "language_value" -def test_annotate_text_from_dict(): - test_annotate_text(request_type=dict) - - def test_annotate_text_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. @@ -2112,7 +2088,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 703d778f..b12fd591 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -249,20 +249,20 @@ def test_language_service_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -331,7 +331,7 @@ def test_language_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -426,7 +426,7 @@ def test_language_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -457,7 +457,7 @@ def test_language_service_client_client_options_credentials_file( options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -490,9 +490,10 @@ def test_language_service_client_client_options_from_dict(): ) -def test_analyze_sentiment( - transport: str = "grpc", request_type=language_service.AnalyzeSentimentRequest -): +@pytest.mark.parametrize( + "request_type", [language_service.AnalyzeSentimentRequest, dict,] +) +def test_analyze_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -521,10 +522,6 @@ def test_analyze_sentiment( assert response.language == "language_value" -def test_analyze_sentiment_from_dict(): - test_analyze_sentiment(request_type=dict) - - def test_analyze_sentiment_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. @@ -684,9 +681,10 @@ async def test_analyze_sentiment_flattened_error_async(): ) -def test_analyze_entities( - transport: str = "grpc", request_type=language_service.AnalyzeEntitiesRequest -): +@pytest.mark.parametrize( + "request_type", [language_service.AnalyzeEntitiesRequest, dict,] +) +def test_analyze_entities(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -713,10 +711,6 @@ def test_analyze_entities( assert response.language == "language_value" -def test_analyze_entities_from_dict(): - test_analyze_entities(request_type=dict) - - def test_analyze_entities_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. @@ -868,9 +862,10 @@ async def test_analyze_entities_flattened_error_async(): ) -def test_analyze_entity_sentiment( - transport: str = "grpc", request_type=language_service.AnalyzeEntitySentimentRequest -): +@pytest.mark.parametrize( + "request_type", [language_service.AnalyzeEntitySentimentRequest, dict,] +) +def test_analyze_entity_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -899,10 +894,6 @@ def test_analyze_entity_sentiment( assert response.language == "language_value" -def test_analyze_entity_sentiment_from_dict(): - test_analyze_entity_sentiment(request_type=dict) - - def test_analyze_entity_sentiment_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. @@ -1062,9 +1053,8 @@ async def test_analyze_entity_sentiment_flattened_error_async(): ) -def test_analyze_syntax( - transport: str = "grpc", request_type=language_service.AnalyzeSyntaxRequest -): +@pytest.mark.parametrize("request_type", [language_service.AnalyzeSyntaxRequest, dict,]) +def test_analyze_syntax(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1091,10 +1081,6 @@ def test_analyze_syntax( assert response.language == "language_value" -def test_analyze_syntax_from_dict(): - test_analyze_syntax(request_type=dict) - - def test_analyze_syntax_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. @@ -1245,9 +1231,8 @@ async def test_analyze_syntax_flattened_error_async(): ) -def test_classify_text( - transport: str = "grpc", request_type=language_service.ClassifyTextRequest -): +@pytest.mark.parametrize("request_type", [language_service.ClassifyTextRequest, dict,]) +def test_classify_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1271,10 +1256,6 @@ def test_classify_text( assert isinstance(response, language_service.ClassifyTextResponse) -def test_classify_text_from_dict(): - test_classify_text(request_type=dict) - - def test_classify_text_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. @@ -1414,9 +1395,8 @@ async def test_classify_text_flattened_error_async(): ) -def test_annotate_text( - transport: str = "grpc", request_type=language_service.AnnotateTextRequest -): +@pytest.mark.parametrize("request_type", [language_service.AnnotateTextRequest, dict,]) +def test_annotate_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1443,10 +1423,6 @@ def test_annotate_text( assert response.language == "language_value" -def test_annotate_text_from_dict(): - test_annotate_text(request_type=dict) - - def test_annotate_text_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. @@ -2114,7 +2090,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( From d623b3aad308eae738cdce317a60f35ded0cfff9 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 11 Jan 2022 07:46:10 -0500 Subject: [PATCH 105/254] chore(samples): Add check for tests in directory (#240) Source-Link: https://github.com/googleapis/synthtool/commit/52aef91f8d25223d9dbdb4aebd94ba8eea2101f3 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:36a95b8f494e4674dc9eee9af98961293b51b86b3649942aac800ae6c1f796d4 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 70 +++++++++++-------- samples/snippets/classify_text/noxfile.py | 70 +++++++++++-------- samples/snippets/cloud-client/v1/noxfile.py | 70 +++++++++++-------- .../snippets/generated-samples/v1/noxfile.py | 70 +++++++++++-------- samples/snippets/sentiment/noxfile.py | 70 +++++++++++-------- 6 files changed, 196 insertions(+), 156 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index f33299dd..6b8a73b3 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:899d5d7cc340fa8ef9d8ae1a8cfba362c6898584f779e156f25ee828ba824610 + digest: sha256:36a95b8f494e4674dc9eee9af98961293b51b86b3649942aac800ae6c1f796d4 diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 93a9122c..3bbef5d5 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -14,6 +14,7 @@ from __future__ import print_function +import glob import os from pathlib import Path import sys @@ -184,37 +185,44 @@ 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + # check for presence of tests + test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + if len(test_list) == 0: + print("No tests found, skipping directory.") + else: + 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"): + 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"): + 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()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 93a9122c..3bbef5d5 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -14,6 +14,7 @@ from __future__ import print_function +import glob import os from pathlib import Path import sys @@ -184,37 +185,44 @@ 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + # check for presence of tests + test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + if len(test_list) == 0: + print("No tests found, skipping directory.") + else: + 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"): + 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"): + 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()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 93a9122c..3bbef5d5 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -14,6 +14,7 @@ from __future__ import print_function +import glob import os from pathlib import Path import sys @@ -184,37 +185,44 @@ 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + # check for presence of tests + test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + if len(test_list) == 0: + print("No tests found, skipping directory.") + else: + 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"): + 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"): + 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()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 93a9122c..3bbef5d5 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -14,6 +14,7 @@ from __future__ import print_function +import glob import os from pathlib import Path import sys @@ -184,37 +185,44 @@ 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + # check for presence of tests + test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + if len(test_list) == 0: + print("No tests found, skipping directory.") + else: + 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"): + 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"): + 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()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 93a9122c..3bbef5d5 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -14,6 +14,7 @@ from __future__ import print_function +import glob import os from pathlib import Path import sys @@ -184,37 +185,44 @@ 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + # check for presence of tests + test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + if len(test_list) == 0: + print("No tests found, skipping directory.") + else: + 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"): + 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"): + 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()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) From 69a693ef33b202bbb1c44542bb7fea77af98ffe1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 14 Jan 2022 07:41:50 -0500 Subject: [PATCH 106/254] build: switch to release-please for tagging (#242) Source-Link: https://github.com/googleapis/synthtool/commit/f8077d237e0df2cb0066dfc6e09fc41e1c59646a Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:dfa9b663b32de8b5b327e32c1da665a80de48876558dd58091d8160c60ad7355 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 2 +- .github/release-please.yml | 1 + .github/release-trigger.yml | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 .github/release-trigger.yml diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 6b8a73b3..ff5126c1 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:36a95b8f494e4674dc9eee9af98961293b51b86b3649942aac800ae6c1f796d4 + digest: sha256:dfa9b663b32de8b5b327e32c1da665a80de48876558dd58091d8160c60ad7355 diff --git a/.github/release-please.yml b/.github/release-please.yml index 4507ad05..466597e5 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1 +1,2 @@ releaseType: python +handleGHRelease: true diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml new file mode 100644 index 00000000..d4ca9418 --- /dev/null +++ b/.github/release-trigger.yml @@ -0,0 +1 @@ +enabled: true From 1dabab4bc7f4b65230e18c44ffc0424c6626751c Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 14 Jan 2022 09:09:11 -0500 Subject: [PATCH 107/254] chore(python): update release.sh to use keystore (#243) Source-Link: https://github.com/googleapis/synthtool/commit/69fda12e2994f0b595a397e8bb6e3e9f380524eb Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:ae600f36b6bc972b368367b6f83a1d91ec2c82a4a116b383d67d547c56fe6de3 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/release.sh | 2 +- .kokoro/release/common.cfg | 12 +++++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index ff5126c1..eecb84c2 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:dfa9b663b32de8b5b327e32c1da665a80de48876558dd58091d8160c60ad7355 + digest: sha256:ae600f36b6bc972b368367b6f83a1d91ec2c82a4a116b383d67d547c56fe6de3 diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 4a4c3e42..9db53208 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_GFILE_DIR}/secret_manager/google-cloud-pypi-token") +TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google-cloud-pypi-token-keystore-1") cd github/python-language python3 setup.py sdist bdist_wheel twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 44a63ec8..6c908a55 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,8 +23,18 @@ env_vars: { value: "github/python-language/.kokoro/release.sh" } +# Fetch PyPI password +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google-cloud-pypi-token-keystore-1" + } + } +} + # 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,google-cloud-pypi-token" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" } From e345d8f3aa103c59ea7c9f1d6b8d7e17c9415dd9 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Mon, 17 Jan 2022 17:31:44 +0100 Subject: [PATCH 108/254] chore(deps): update all dependencies (#238) * chore(deps): update all dependencies * revert numpy update for python_version <= '3.6' * pin numpy 1.21.4 for python 3.7 samples * fix typo Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- samples/snippets/classify_text/requirements.txt | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 2802f988..7c7432b2 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.34.0 +google-api-python-client==2.35.0 google-auth==2.3.3 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index b4f8763f..8ebc429c 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,4 @@ google-cloud-language==2.3.1 -numpy==1.21.4; python_version > '3.6' +numpy==1.22.1; python_version > '3.7' +numpy==1.21.4; python_version == '3.7' numpy==1.19.5; python_version <= '3.6' From 16034703eb4e97634481eca591774591e70f7a99 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 20:27:37 -0500 Subject: [PATCH 109/254] chore(python): Noxfile recognizes that tests can live in a folder (#246) Source-Link: https://github.com/googleapis/synthtool/commit/4760d8dce1351d93658cb11d02a1b7ceb23ae5d7 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f0e4b51deef56bed74d3e2359c583fc104a8d6367da3984fc5c66938db738828 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 1 + samples/snippets/classify_text/noxfile.py | 1 + samples/snippets/cloud-client/v1/noxfile.py | 1 + samples/snippets/generated-samples/v1/noxfile.py | 1 + samples/snippets/sentiment/noxfile.py | 1 + 6 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index eecb84c2..52d79c11 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ae600f36b6bc972b368367b6f83a1d91ec2c82a4a116b383d67d547c56fe6de3 + digest: sha256:f0e4b51deef56bed74d3e2359c583fc104a8d6367da3984fc5c66938db738828 diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 3bbef5d5..20cdfc62 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -187,6 +187,7 @@ def _session_tests( ) -> None: # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + test_list.extend(glob.glob("tests")) if len(test_list) == 0: print("No tests found, skipping directory.") else: diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 3bbef5d5..20cdfc62 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -187,6 +187,7 @@ def _session_tests( ) -> None: # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + test_list.extend(glob.glob("tests")) if len(test_list) == 0: print("No tests found, skipping directory.") else: diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 3bbef5d5..20cdfc62 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -187,6 +187,7 @@ def _session_tests( ) -> None: # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + test_list.extend(glob.glob("tests")) if len(test_list) == 0: print("No tests found, skipping directory.") else: diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 3bbef5d5..20cdfc62 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -187,6 +187,7 @@ def _session_tests( ) -> None: # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + test_list.extend(glob.glob("tests")) if len(test_list) == 0: print("No tests found, skipping directory.") else: diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 3bbef5d5..20cdfc62 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -187,6 +187,7 @@ def _session_tests( ) -> None: # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + test_list.extend(glob.glob("tests")) if len(test_list) == 0: print("No tests found, skipping directory.") else: From 19987146fdff81dcc5f57a8713e376f4c0ac7e1a Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 19 Jan 2022 02:50:55 +0100 Subject: [PATCH 110/254] chore(deps): update all dependencies (#247) * chore(deps): update all dependencies * revert pin changes for python <= 3.7 Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 7c7432b2..c86677b3 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.35.0 +google-api-python-client==2.36.0 google-auth==2.3.3 google-auth-httplib2==0.1.0 From d9da234c9c71ffbf19f5ad473bf2782176fde1b2 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 20 Jan 2022 18:04:37 -0500 Subject: [PATCH 111/254] ci(python): run lint / unit tests / docs as GH actions (#250) * ci(python): run lint / unit tests / docs as GH actions Source-Link: https://github.com/googleapis/synthtool/commit/57be0cdb0b94e1669cee0ca38d790de1dfdbcd44 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:ed1f9983d5a935a89fe8085e8bb97d94e41015252c5b6c9771257cf8624367e6 * add commit to trigger gh actions Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 16 +++++++++- .github/workflows/docs.yml | 38 +++++++++++++++++++++++ .github/workflows/lint.yml | 25 +++++++++++++++ .github/workflows/unittest.yml | 57 ++++++++++++++++++++++++++++++++++ 4 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/docs.yml create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/unittest.yml diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 52d79c11..b668c04d 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,17 @@ +# Copyright 2022 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/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f0e4b51deef56bed74d3e2359c583fc104a8d6367da3984fc5c66938db738828 + digest: sha256:ed1f9983d5a935a89fe8085e8bb97d94e41015252c5b6c9771257cf8624367e6 + diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..f7b8344c --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,38 @@ +on: + pull_request: + branches: + - main +name: docs +jobs: + docs: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docs + run: | + nox -s docs + docfx: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docfx + run: | + nox -s docfx diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..1e8b05c3 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,25 @@ +on: + pull_request: + branches: + - main +name: lint +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run lint + run: | + nox -s lint + - name: Run lint_setup_py + run: | + nox -s lint_setup_py diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml new file mode 100644 index 00000000..074ee250 --- /dev/null +++ b/.github/workflows/unittest.yml @@ -0,0 +1,57 @@ +on: + pull_request: + branches: + - main +name: unittest +jobs: + unit: + runs-on: ubuntu-latest + strategy: + matrix: + python: ['3.6', '3.7', '3.8', '3.9', '3.10'] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run unit tests + env: + COVERAGE_FILE: .coverage-${{ matrix.python }} + run: | + nox -s unit-${{ matrix.python }} + - name: Upload coverage results + uses: actions/upload-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-${{ matrix.python }} + + cover: + runs-on: ubuntu-latest + needs: + - unit + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install coverage + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install coverage + - name: Download coverage results + uses: actions/download-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-results/ + - name: Report coverage results + run: | + coverage combine .coverage-results/.coverage* + coverage report --show-missing --fail-under=100 From 105be7bed2c5865e5208ea555e591e1d01d2ad36 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 20 Jan 2022 23:20:13 +0000 Subject: [PATCH 112/254] chore(main): release 2.3.2 (#252) :robot: I have created a release *beep* *boop* --- ### [2.3.2](https://github.com/googleapis/python-language/compare/v2.3.1...v2.3.2) (2022-01-20) ### Documentation * **samples:** Document -> types.Document ([#227](https://github.com/googleapis/python-language/issues/227)) ([01367d7](https://github.com/googleapis/python-language/commit/01367d7b1e0ddba6e6b920f125730aa97d51ada0)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 7 +++++++ setup.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a9bbfab..d6fe8a06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +### [2.3.2](https://github.com/googleapis/python-language/compare/v2.3.1...v2.3.2) (2022-01-20) + + +### Documentation + +* **samples:** Document -> types.Document ([#227](https://github.com/googleapis/python-language/issues/227)) ([01367d7](https://github.com/googleapis/python-language/commit/01367d7b1e0ddba6e6b920f125730aa97d51ada0)) + ### [2.3.1](https://www.github.com/googleapis/python-language/compare/v2.3.0...v2.3.1) (2021-11-01) diff --git a/setup.py b/setup.py index 04e3a675..cd04169e 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.3.1" +version = "2.3.2" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 2e11d77b372c222a2fa208a6cb4dc607a435a28e Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Mon, 24 Jan 2022 13:08:20 -0700 Subject: [PATCH 113/254] chore: make samples 3.6 check optional (#255) --- .github/sync-repo-settings.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index 0ddb512d..c60c5300 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -10,6 +10,5 @@ branchProtectionRules: - 'Kokoro' - 'cla/google' - 'Samples - Lint' - - 'Samples - Python 3.6' - 'Samples - Python 3.7' - 'Samples - Python 3.8' From 593ec8a998c612b3a87b4b9a53bd166c0b2c10f6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 25 Jan 2022 10:09:34 -0500 Subject: [PATCH 114/254] feat: add api key support (#256) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: upgrade gapic-generator-java, gax-java and gapic-generator-python PiperOrigin-RevId: 423842556 Source-Link: https://github.com/googleapis/googleapis/commit/a616ca08f4b1416abbac7bc5dd6d61c791756a81 Source-Link: https://github.com/googleapis/googleapis-gen/commit/29b938c58c1e51d019f2ee539d55dc0a3c86a905 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMjliOTM4YzU4YzFlNTFkMDE5ZjJlZTUzOWQ1NWRjMGEzYzg2YTkwNSJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../services/language_service/async_client.py | 38 +++++- .../services/language_service/client.py | 127 +++++++++++------ .../services/language_service/async_client.py | 38 +++++- .../services/language_service/client.py | 127 +++++++++++------ .../language_v1/test_language_service.py | 128 ++++++++++++++++++ .../language_v1beta2/test_language_service.py | 128 ++++++++++++++++++ 6 files changed, 498 insertions(+), 88 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 8121cc51..e5cf9d94 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions @@ -105,6 +105,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LanguageServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> LanguageServiceTransport: """Returns the transport used by the client instance. diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index ea4653b1..15f08651 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -219,6 +219,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -269,57 +336,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ( - "true", - "false", - ): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - use_client_cert = ( - os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - 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: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - 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" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, LanguageServiceTransport): # transport is a LanguageServiceTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -331,6 +363,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 366e2acf..28a5b0fe 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions @@ -105,6 +105,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return LanguageServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> LanguageServiceTransport: """Returns the transport used by the client instance. diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 29fd4df7..b0c93282 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -219,6 +219,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -269,57 +336,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ( - "true", - "false", - ): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - use_client_cert = ( - os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - 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: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - 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" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, LanguageServiceTransport): # transport is a LanguageServiceTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -331,6 +363,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 3304ab5e..996eea97 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -406,6 +406,87 @@ def test_language_service_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [LanguageServiceClient, LanguageServiceAsyncClient] +) +@mock.patch.object( + LanguageServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LanguageServiceClient), +) +@mock.patch.object( + LanguageServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LanguageServiceAsyncClient), +) +def test_language_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -1601,6 +1682,23 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient(client_options=options, transport=transport,) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.LanguageServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2153,3 +2251,33 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (LanguageServiceClient, transports.LanguageServiceGrpcTransport), + (LanguageServiceAsyncClient, transports.LanguageServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index b12fd591..17ed8c27 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -408,6 +408,87 @@ def test_language_service_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [LanguageServiceClient, LanguageServiceAsyncClient] +) +@mock.patch.object( + LanguageServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LanguageServiceClient), +) +@mock.patch.object( + LanguageServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LanguageServiceAsyncClient), +) +def test_language_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -1603,6 +1684,23 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient(client_options=options, transport=transport,) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.LanguageServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2155,3 +2253,33 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (LanguageServiceClient, transports.LanguageServiceGrpcTransport), + (LanguageServiceAsyncClient, transports.LanguageServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) From 3e7c96410914d9080ecd0325c61bdc624adf08e1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 3 Feb 2022 15:58:59 +0000 Subject: [PATCH 115/254] chore: use gapic-generator-python 0.62.1 (#260) - [ ] Regenerate this pull request now. fix: resolve DuplicateCredentialArgs error when using credentials_file committer: parthea PiperOrigin-RevId: 425964861 Source-Link: https://github.com/googleapis/googleapis/commit/84b1a5a4f6fb2d04905be58e586b8a7a4310a8cf Source-Link: https://github.com/googleapis/googleapis-gen/commit/4fb761bbd8506ac156f49bac5f18306aa8eb3aa8 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNGZiNzYxYmJkODUwNmFjMTU2ZjQ5YmFjNWYxODMwNmFhOGViM2FhOCJ9 Closes #259 --- .../services/language_service/async_client.py | 12 +-- .../services/language_service/client.py | 12 +-- .../language_service/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- .../services/language_service/async_client.py | 12 +-- .../services/language_service/client.py | 12 +-- .../language_service/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- .../snippets/classify_text/requirements.txt | 1 - .../language_v1/test_language_service.py | 82 ++++++++++++++++++- .../language_v1beta2/test_language_service.py | 82 ++++++++++++++++++- 11 files changed, 198 insertions(+), 35 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index e5cf9d94..e830dad3 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -242,7 +242,7 @@ async def analyze_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -325,7 +325,7 @@ async def analyze_entities( The entity analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -411,7 +411,7 @@ async def analyze_entity_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -493,7 +493,7 @@ async def analyze_syntax( The syntax analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -568,7 +568,7 @@ async def classify_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document]) if request is not None and has_flattened_params: @@ -658,7 +658,7 @@ async def annotate_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, features, encoding_type]) if request is not None and has_flattened_params: diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 15f08651..c3bc0fbc 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -425,7 +425,7 @@ def analyze_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -498,7 +498,7 @@ def analyze_entities( The entity analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -574,7 +574,7 @@ def analyze_entity_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -646,7 +646,7 @@ def analyze_syntax( The syntax analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -711,7 +711,7 @@ def classify_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document]) if request is not None and has_flattened_params: @@ -791,7 +791,7 @@ def annotate_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, features, encoding_type]) if request is not None and has_flattened_params: diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 94941e4e..5657b6a1 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -159,8 +159,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 681336e2..4490dab8 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -204,8 +204,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 28a5b0fe..a74c38d4 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -243,7 +243,7 @@ async def analyze_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -326,7 +326,7 @@ async def analyze_entities( The entity analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -412,7 +412,7 @@ async def analyze_entity_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -494,7 +494,7 @@ async def analyze_syntax( The syntax analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -569,7 +569,7 @@ async def classify_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document]) if request is not None and has_flattened_params: @@ -659,7 +659,7 @@ async def annotate_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, features, encoding_type]) if request is not None and has_flattened_params: diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index b0c93282..8b29f11b 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -426,7 +426,7 @@ def analyze_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -499,7 +499,7 @@ def analyze_entities( The entity analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -575,7 +575,7 @@ def analyze_entity_sentiment( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -647,7 +647,7 @@ def analyze_syntax( The syntax analysis response message. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, encoding_type]) if request is not None and has_flattened_params: @@ -712,7 +712,7 @@ def classify_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document]) if request is not None and has_flattened_params: @@ -792,7 +792,7 @@ def annotate_text( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([document, features, encoding_type]) if request is not None and has_flattened_params: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 2936db35..f962d7dc 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -159,8 +159,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 5e7e6213..ca6b00b3 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -204,8 +204,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 8ebc429c..b562bb86 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,4 +1,3 @@ google-cloud-language==2.3.1 numpy==1.22.1; python_version > '3.7' numpy==1.21.4; python_version == '3.7' -numpy==1.19.5; python_version <= '3.6' diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 996eea97..e322b5db 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -519,21 +519,28 @@ def test_language_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport, "grpc"), + ( + LanguageServiceClient, + transports.LanguageServiceGrpcTransport, + "grpc", + grpc_helpers, + ), ( LanguageServiceAsyncClient, transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_language_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) @@ -569,6 +576,75 @@ def test_language_service_client_client_options_from_dict(): ) +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + LanguageServiceClient, + transports.LanguageServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + LanguageServiceAsyncClient, + transports.LanguageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_language_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "language.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="language.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "request_type", [language_service.AnalyzeSentimentRequest, dict,] ) diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 17ed8c27..d3462f23 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -521,21 +521,28 @@ def test_language_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport, "grpc"), + ( + LanguageServiceClient, + transports.LanguageServiceGrpcTransport, + "grpc", + grpc_helpers, + ), ( LanguageServiceAsyncClient, transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_language_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) @@ -571,6 +578,75 @@ def test_language_service_client_client_options_from_dict(): ) +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + LanguageServiceClient, + transports.LanguageServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + LanguageServiceAsyncClient, + transports.LanguageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_language_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "language.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-language", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="language.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "request_type", [language_service.AnalyzeSentimentRequest, dict,] ) From 1a50160418f17c3d8d8c18ec995e20955b8da2e9 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 11 Feb 2022 09:36:04 -0700 Subject: [PATCH 116/254] chore: use gapic-generator-python 0.63.2 (#262) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: use gapic-generator-python 0.63.2 docs: add generated snippets PiperOrigin-RevId: 427792504 Source-Link: https://github.com/googleapis/googleapis/commit/55b9e1e0b3106c850d13958352bc0751147b6b15 Source-Link: https://github.com/googleapis/googleapis-gen/commit/bf4e86b753f42cb0edb1fd51fbe840d7da0a1cde Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYmY0ZTg2Yjc1M2Y0MmNiMGVkYjFmZDUxZmJlODQwZDdkYTBhMWNkZSJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../services/language_service/async_client.py | 136 +++++ .../services/language_service/client.py | 142 +++++ .../services/language_service/async_client.py | 136 +++++ .../services/language_service/client.py | 142 +++++ ...language_service_analyze_entities_async.py | 48 ++ ..._language_service_analyze_entities_sync.py | 48 ++ ..._service_analyze_entity_sentiment_async.py | 48 ++ ...e_service_analyze_entity_sentiment_sync.py | 48 ++ ...anguage_service_analyze_sentiment_async.py | 48 ++ ...language_service_analyze_sentiment_sync.py | 48 ++ ...1_language_service_analyze_syntax_async.py | 48 ++ ...v1_language_service_analyze_syntax_sync.py | 48 ++ ...v1_language_service_annotate_text_async.py | 48 ++ ..._v1_language_service_annotate_text_sync.py | 48 ++ ...v1_language_service_classify_text_async.py | 48 ++ ..._v1_language_service_classify_text_sync.py | 48 ++ ...language_service_analyze_entities_async.py | 48 ++ ..._language_service_analyze_entities_sync.py | 48 ++ ..._service_analyze_entity_sentiment_async.py | 48 ++ ...e_service_analyze_entity_sentiment_sync.py | 48 ++ ...anguage_service_analyze_sentiment_async.py | 48 ++ ...language_service_analyze_sentiment_sync.py | 48 ++ ...2_language_service_analyze_syntax_async.py | 48 ++ ...a2_language_service_analyze_syntax_sync.py | 48 ++ ...a2_language_service_annotate_text_async.py | 48 ++ ...ta2_language_service_annotate_text_sync.py | 48 ++ ...a2_language_service_classify_text_async.py | 48 ++ ...ta2_language_service_classify_text_sync.py | 48 ++ .../snippet_metadata_language_v1.json | 538 ++++++++++++++++++ .../snippet_metadata_language_v1beta2.json | 538 ++++++++++++++++++ 30 files changed, 2784 insertions(+) create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_async.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_async.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_async.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_async.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_annotate_text_async.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_annotate_text_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_classify_text_async.py create mode 100644 samples/generated_samples/language_generated_language_v1_language_service_classify_text_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_async.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_async.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_async.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_async.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_sync.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_async.py create mode 100644 samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_sync.py create mode 100644 samples/generated_samples/snippet_metadata_language_v1.json create mode 100644 samples/generated_samples/snippet_metadata_language_v1beta2.json diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index e830dad3..53bc2c78 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -213,6 +213,28 @@ async def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_sentiment(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request @@ -299,6 +321,29 @@ async def analyze_entities( salience, mentions for each entity, and other properties. + + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_entities(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = client.analyze_entities(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. @@ -382,6 +427,29 @@ async def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. + + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis @@ -467,6 +535,29 @@ async def analyze_syntax( boundaries and tokenization along with part of speech tags, dependency trees, and other properties. + + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_syntax(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = client.analyze_syntax(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. @@ -546,6 +637,28 @@ async def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. + .. code-block:: + + from google.cloud import language_v1 + + def sample_classify_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = client.classify_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]): The request object. The document classification request @@ -623,6 +736,29 @@ async def annotate_text( that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call. + + .. code-block:: + + from google.cloud import language_v1 + + def sample_annotate_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = client.annotate_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]): The request object. The request message for the text diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index c3bc0fbc..9134e527 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -396,6 +396,29 @@ def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. + + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_sentiment(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request @@ -472,6 +495,30 @@ def analyze_entities( salience, mentions for each entity, and other properties. + + + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_entities(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = client.analyze_entities(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. @@ -545,6 +592,30 @@ def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. + + + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis @@ -620,6 +691,30 @@ def analyze_syntax( boundaries and tokenization along with part of speech tags, dependency trees, and other properties. + + + .. code-block:: + + from google.cloud import language_v1 + + def sample_analyze_syntax(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = client.analyze_syntax(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. @@ -689,6 +784,29 @@ def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. + + .. code-block:: + + from google.cloud import language_v1 + + def sample_classify_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = client.classify_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]): The request object. The document classification request @@ -756,6 +874,30 @@ def annotate_text( that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call. + + + .. code-block:: + + from google.cloud import language_v1 + + def sample_annotate_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = client.annotate_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]): The request object. The request message for the text diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index a74c38d4..293021a8 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -213,6 +213,28 @@ async def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request @@ -300,6 +322,29 @@ async def analyze_entities( salience, mentions for each entity, and other properties. + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_entities(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = client.analyze_entities(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. @@ -383,6 +428,29 @@ async def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis @@ -468,6 +536,29 @@ async def analyze_syntax( boundaries and tokenization along with part-of-speech tags, dependency trees, and other properties. + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_syntax(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = client.analyze_syntax(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. @@ -547,6 +638,28 @@ async def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_classify_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = client.classify_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]): The request object. The document classification request @@ -624,6 +737,29 @@ async def annotate_text( sentiment, entity, and classification features in one call. + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_annotate_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = client.annotate_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]): The request object. The request message for the text diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 8b29f11b..c5da1c42 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -396,6 +396,29 @@ def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]): The request object. The sentiment analysis request @@ -473,6 +496,30 @@ def analyze_entities( salience, mentions for each entity, and other properties. + + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_entities(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = client.analyze_entities(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. @@ -546,6 +593,30 @@ def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. + + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]): The request object. The entity-level sentiment analysis @@ -621,6 +692,30 @@ def analyze_syntax( boundaries and tokenization along with part-of-speech tags, dependency trees, and other properties. + + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_analyze_syntax(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = client.analyze_syntax(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. @@ -690,6 +785,29 @@ def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_classify_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = client.classify_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]): The request object. The document classification request @@ -757,6 +875,30 @@ def annotate_text( sentiment, entity, and classification features in one call. + + + .. code-block:: + + from google.cloud import language_v1beta2 + + def sample_annotate_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = client.annotate_text(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]): The request object. The request message for the text diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_async.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_async.py new file mode 100644 index 00000000..76d680ba --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntities +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeEntities_async] +from google.cloud import language_v1 + + +async def sample_analyze_entities(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = await client.analyze_entities(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeEntities_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_sync.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_sync.py new file mode 100644 index 00000000..13362deb --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntities +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeEntities_sync] +from google.cloud import language_v1 + + +def sample_analyze_entities(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = client.analyze_entities(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeEntities_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_async.py new file mode 100644 index 00000000..0b15bbbb --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntitySentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_async] +from google.cloud import language_v1 + + +async def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = await client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py new file mode 100644 index 00000000..d6ba37a4 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntitySentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_sync] +from google.cloud import language_v1 + + +def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_async.py new file mode 100644 index 00000000..93b29343 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeSentiment_async] +from google.cloud import language_v1 + + +async def sample_analyze_sentiment(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = await client.analyze_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeSentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_sync.py new file mode 100644 index 00000000..aee0a746 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeSentiment_sync] +from google.cloud import language_v1 + + +def sample_analyze_sentiment(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeSentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_async.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_async.py new file mode 100644 index 00000000..77c8c239 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSyntax +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeSyntax_async] +from google.cloud import language_v1 + + +async def sample_analyze_syntax(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = await client.analyze_syntax(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeSyntax_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_sync.py new file mode 100644 index 00000000..aa7ec47f --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSyntax +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnalyzeSyntax_sync] +from google.cloud import language_v1 + + +def sample_analyze_syntax(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = client.analyze_syntax(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnalyzeSyntax_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_async.py b/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_async.py new file mode 100644 index 00000000..5ae9ff97 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnnotateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnnotateText_async] +from google.cloud import language_v1 + + +async def sample_annotate_text(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = await client.annotate_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnnotateText_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_sync.py b/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_sync.py new file mode 100644 index 00000000..59e182e2 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnnotateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_AnnotateText_sync] +from google.cloud import language_v1 + + +def sample_annotate_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = client.annotate_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_AnnotateText_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_classify_text_async.py b/samples/generated_samples/language_generated_language_v1_language_service_classify_text_async.py new file mode 100644 index 00000000..47c93312 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_classify_text_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClassifyText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_ClassifyText_async] +from google.cloud import language_v1 + + +async def sample_classify_text(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = await client.classify_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_ClassifyText_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_classify_text_sync.py b/samples/generated_samples/language_generated_language_v1_language_service_classify_text_sync.py new file mode 100644 index 00000000..1c4c1796 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1_language_service_classify_text_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClassifyText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1_LanguageService_ClassifyText_sync] +from google.cloud import language_v1 + + +def sample_classify_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = client.classify_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1_LanguageService_ClassifyText_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_async.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_async.py new file mode 100644 index 00000000..42f6a383 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntities +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntities_async] +from google.cloud import language_v1beta2 + + +async def sample_analyze_entities(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = await client.analyze_entities(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntities_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_sync.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_sync.py new file mode 100644 index 00000000..cacaee20 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntities +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntities_sync] +from google.cloud import language_v1beta2 + + +def sample_analyze_entities(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitiesRequest( + document=document, + ) + + # Make the request + response = client.analyze_entities(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntities_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py new file mode 100644 index 00000000..d1af0e16 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntitySentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_async] +from google.cloud import language_v1beta2 + + +async def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = await client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py new file mode 100644 index 00000000..172d9e85 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeEntitySentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_sync] +from google.cloud import language_v1beta2 + + +def sample_analyze_entity_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeEntitySentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_entity_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_async.py new file mode 100644 index 00000000..f02f3641 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_async] +from google.cloud import language_v1beta2 + + +async def sample_analyze_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = await client.analyze_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py new file mode 100644 index 00000000..b600c188 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSentiment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_sync] +from google.cloud import language_v1beta2 + + +def sample_analyze_sentiment(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSentimentRequest( + document=document, + ) + + # Make the request + response = client.analyze_sentiment(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_async.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_async.py new file mode 100644 index 00000000..33d9637d --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSyntax +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_async] +from google.cloud import language_v1beta2 + + +async def sample_analyze_syntax(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = await client.analyze_syntax(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_sync.py new file mode 100644 index 00000000..2d9fc145 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeSyntax +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_sync] +from google.cloud import language_v1beta2 + + +def sample_analyze_syntax(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnalyzeSyntaxRequest( + document=document, + ) + + # Make the request + response = client.analyze_syntax(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_async.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_async.py new file mode 100644 index 00000000..f352aa75 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnnotateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnnotateText_async] +from google.cloud import language_v1beta2 + + +async def sample_annotate_text(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = await client.annotate_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnnotateText_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_sync.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_sync.py new file mode 100644 index 00000000..f1a0d007 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnnotateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_AnnotateText_sync] +from google.cloud import language_v1beta2 + + +def sample_annotate_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.AnnotateTextRequest( + document=document, + ) + + # Make the request + response = client.annotate_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_AnnotateText_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_async.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_async.py new file mode 100644 index 00000000..a9bfabfc --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClassifyText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_ClassifyText_async] +from google.cloud import language_v1beta2 + + +async def sample_classify_text(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = await client.classify_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_ClassifyText_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_sync.py b/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_sync.py new file mode 100644 index 00000000..abef8641 --- /dev/null +++ b/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClassifyText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_generated_language_v1beta2_LanguageService_ClassifyText_sync] +from google.cloud import language_v1beta2 + + +def sample_classify_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ClassifyTextRequest( + document=document, + ) + + # Make the request + response = client.classify_text(request=request) + + # Handle the response + print(response) + +# [END language_generated_language_v1beta2_LanguageService_ClassifyText_sync] diff --git a/samples/generated_samples/snippet_metadata_language_v1.json b/samples/generated_samples/snippet_metadata_language_v1.json new file mode 100644 index 00000000..a0805e26 --- /dev/null +++ b/samples/generated_samples/snippet_metadata_language_v1.json @@ -0,0 +1,538 @@ +{ + "snippets": [ + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntities" + } + }, + "file": "language_generated_language_v1_language_service_analyze_entities_async.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntities_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntities" + } + }, + "file": "language_generated_language_v1_language_service_analyze_entities_sync.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntities_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntitySentiment" + } + }, + "file": "language_generated_language_v1_language_service_analyze_entity_sentiment_async.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntitySentiment" + } + }, + "file": "language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSentiment" + } + }, + "file": "language_generated_language_v1_language_service_analyze_sentiment_async.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSentiment_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSentiment" + } + }, + "file": "language_generated_language_v1_language_service_analyze_sentiment_sync.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSentiment_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSyntax" + } + }, + "file": "language_generated_language_v1_language_service_analyze_syntax_async.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSyntax_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSyntax" + } + }, + "file": "language_generated_language_v1_language_service_analyze_syntax_sync.py", + "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSyntax_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnnotateText" + } + }, + "file": "language_generated_language_v1_language_service_annotate_text_async.py", + "regionTag": "language_generated_language_v1_LanguageService_AnnotateText_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnnotateText" + } + }, + "file": "language_generated_language_v1_language_service_annotate_text_sync.py", + "regionTag": "language_generated_language_v1_LanguageService_AnnotateText_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "ClassifyText" + } + }, + "file": "language_generated_language_v1_language_service_classify_text_async.py", + "regionTag": "language_generated_language_v1_LanguageService_ClassifyText_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "ClassifyText" + } + }, + "file": "language_generated_language_v1_language_service_classify_text_sync.py", + "regionTag": "language_generated_language_v1_LanguageService_ClassifyText_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + } + ] +} diff --git a/samples/generated_samples/snippet_metadata_language_v1beta2.json b/samples/generated_samples/snippet_metadata_language_v1beta2.json new file mode 100644 index 00000000..44e01853 --- /dev/null +++ b/samples/generated_samples/snippet_metadata_language_v1beta2.json @@ -0,0 +1,538 @@ +{ + "snippets": [ + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntities" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_entities_async.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntities_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntities" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_entities_sync.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntities_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntitySentiment" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeEntitySentiment" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSentiment" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_sentiment_async.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSentiment" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSyntax" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_syntax_async.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnalyzeSyntax" + } + }, + "file": "language_generated_language_v1beta2_language_service_analyze_syntax_sync.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnnotateText" + } + }, + "file": "language_generated_language_v1beta2_language_service_annotate_text_async.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnnotateText_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "AnnotateText" + } + }, + "file": "language_generated_language_v1beta2_language_service_annotate_text_sync.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_AnnotateText_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "ClassifyText" + } + }, + "file": "language_generated_language_v1beta2_language_service_classify_text_async.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_ClassifyText_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "LanguageService" + }, + "shortName": "ClassifyText" + } + }, + "file": "language_generated_language_v1beta2_language_service_classify_text_sync.py", + "regionTag": "language_generated_language_v1beta2_LanguageService_ClassifyText_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 41, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 42, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + } + ] +} From 19228bedaa5325fb30c831185617351daf22e12c Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 25 Feb 2022 10:40:38 -0700 Subject: [PATCH 117/254] chore: use gapic-generator-python 0.63.4 (#263) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: use gapic-generator-python 0.63.4 chore: fix snippet region tag format chore: fix docstring code block formatting PiperOrigin-RevId: 430730865 Source-Link: https://github.com/googleapis/googleapis/commit/ea5800229f73f94fd7204915a86ed09dcddf429a Source-Link: https://github.com/googleapis/googleapis-gen/commit/ca893ff8af25fc7fe001de1405a517d80446ecca Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiY2E4OTNmZjhhZjI1ZmM3ZmUwMDFkZTE0MDVhNTE3ZDgwNDQ2ZWNjYSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * chore: delete duplicates Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> --- .../services/language_service/async_client.py | 12 ++--- .../services/language_service/client.py | 18 +++---- .../services/language_service/async_client.py | 12 ++--- .../services/language_service/client.py | 18 +++---- ...anguage_service_analyze_entities_async.py} | 4 +- ...language_service_analyze_entities_sync.py} | 4 +- ...service_analyze_entity_sentiment_async.py} | 4 +- ..._service_analyze_entity_sentiment_sync.py} | 4 +- ...nguage_service_analyze_sentiment_async.py} | 4 +- ...anguage_service_analyze_sentiment_sync.py} | 4 +- ..._language_service_analyze_syntax_async.py} | 4 +- ...d_language_service_analyze_syntax_sync.py} | 4 +- ...d_language_service_annotate_text_async.py} | 4 +- ...ed_language_service_annotate_text_sync.py} | 4 +- ...d_language_service_classify_text_async.py} | 4 +- ...ed_language_service_classify_text_sync.py} | 4 +- ...anguage_service_analyze_entities_async.py} | 4 +- ...language_service_analyze_entities_sync.py} | 4 +- ...service_analyze_entity_sentiment_async.py} | 4 +- ..._service_analyze_entity_sentiment_sync.py} | 4 +- ...nguage_service_analyze_sentiment_async.py} | 4 +- ...anguage_service_analyze_sentiment_sync.py} | 4 +- ..._language_service_analyze_syntax_async.py} | 4 +- ...d_language_service_analyze_syntax_sync.py} | 4 +- ...d_language_service_annotate_text_async.py} | 4 +- ...ed_language_service_annotate_text_sync.py} | 4 +- ...d_language_service_classify_text_async.py} | 4 +- ...ed_language_service_classify_text_sync.py} | 4 +- .../snippet_metadata_language_v1.json | 48 +++++++++---------- .../snippet_metadata_language_v1beta2.json | 48 +++++++++---------- 30 files changed, 120 insertions(+), 132 deletions(-) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_entities_async.py => language_v1_generated_language_service_analyze_entities_async.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_entities_sync.py => language_v1_generated_language_service_analyze_entities_sync.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_entity_sentiment_async.py => language_v1_generated_language_service_analyze_entity_sentiment_async.py} (89%) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py => language_v1_generated_language_service_analyze_entity_sentiment_sync.py} (89%) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_sentiment_async.py => language_v1_generated_language_service_analyze_sentiment_async.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_sentiment_sync.py => language_v1_generated_language_service_analyze_sentiment_sync.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_syntax_async.py => language_v1_generated_language_service_analyze_syntax_async.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_analyze_syntax_sync.py => language_v1_generated_language_service_analyze_syntax_sync.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_annotate_text_async.py => language_v1_generated_language_service_annotate_text_async.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_annotate_text_sync.py => language_v1_generated_language_service_annotate_text_sync.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_classify_text_async.py => language_v1_generated_language_service_classify_text_async.py} (90%) rename samples/generated_samples/{language_generated_language_v1_language_service_classify_text_sync.py => language_v1_generated_language_service_classify_text_sync.py} (90%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_entities_async.py => language_v1beta2_generated_language_service_analyze_entities_async.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_entities_sync.py => language_v1beta2_generated_language_service_analyze_entities_sync.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py => language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py => language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_sentiment_async.py => language_v1beta2_generated_language_service_analyze_sentiment_async.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py => language_v1beta2_generated_language_service_analyze_sentiment_sync.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_syntax_async.py => language_v1beta2_generated_language_service_analyze_syntax_async.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_analyze_syntax_sync.py => language_v1beta2_generated_language_service_analyze_syntax_sync.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_annotate_text_async.py => language_v1beta2_generated_language_service_annotate_text_async.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_annotate_text_sync.py => language_v1beta2_generated_language_service_annotate_text_sync.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_classify_text_async.py => language_v1beta2_generated_language_service_classify_text_async.py} (89%) rename samples/generated_samples/{language_generated_language_v1beta2_language_service_classify_text_sync.py => language_v1beta2_generated_language_service_classify_text_sync.py} (89%) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 53bc2c78..f6435aa8 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -213,7 +213,7 @@ async def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -322,7 +322,7 @@ async def analyze_entities( properties. - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -428,7 +428,7 @@ async def analyze_entity_sentiment( and its mentions. - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -536,7 +536,7 @@ async def analyze_syntax( tags, dependency trees, and other properties. - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -637,7 +637,7 @@ async def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -737,7 +737,7 @@ async def annotate_text( analyzeSyntax provide in one call. - .. code-block:: + .. code-block:: python from google.cloud import language_v1 diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 9134e527..69f42618 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -396,8 +396,7 @@ def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -496,8 +495,7 @@ def analyze_entities( properties. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -593,8 +591,7 @@ def analyze_entity_sentiment( and its mentions. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -692,8 +689,7 @@ def analyze_syntax( tags, dependency trees, and other properties. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -784,8 +780,7 @@ def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1 @@ -875,8 +870,7 @@ def annotate_text( analyzeSyntax provide in one call. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1 diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 293021a8..3565d049 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -213,7 +213,7 @@ async def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -323,7 +323,7 @@ async def analyze_entities( properties. - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -429,7 +429,7 @@ async def analyze_entity_sentiment( and its mentions. - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -537,7 +537,7 @@ async def analyze_syntax( tags, dependency trees, and other properties. - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -638,7 +638,7 @@ async def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -738,7 +738,7 @@ async def annotate_text( call. - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index c5da1c42..00781271 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -396,8 +396,7 @@ def analyze_sentiment( ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -497,8 +496,7 @@ def analyze_entities( properties. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -594,8 +592,7 @@ def analyze_entity_sentiment( and its mentions. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -693,8 +690,7 @@ def analyze_syntax( tags, dependency trees, and other properties. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -785,8 +781,7 @@ def classify_text( ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 @@ -876,8 +871,7 @@ def annotate_text( call. - - .. code-block:: + .. code-block:: python from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_async.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py index 76d680ba..4425e700 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeEntities_async] +# [START language_v1_generated_LanguageService_AnalyzeEntities_async] from google.cloud import language_v1 @@ -45,4 +45,4 @@ async def sample_analyze_entities(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeEntities_async] +# [END language_v1_generated_LanguageService_AnalyzeEntities_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_sync.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py index 13362deb..b472cbb9 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entities_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeEntities_sync] +# [START language_v1_generated_LanguageService_AnalyzeEntities_sync] from google.cloud import language_v1 @@ -45,4 +45,4 @@ def sample_analyze_entities(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeEntities_sync] +# [END language_v1_generated_LanguageService_AnalyzeEntities_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_async.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py index 0b15bbbb..6877a933 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_async] +# [START language_v1_generated_LanguageService_AnalyzeEntitySentiment_async] from google.cloud import language_v1 @@ -45,4 +45,4 @@ async def sample_analyze_entity_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_async] +# [END language_v1_generated_LanguageService_AnalyzeEntitySentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py index d6ba37a4..717f6a26 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_sync] +# [START language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync] from google.cloud import language_v1 @@ -45,4 +45,4 @@ def sample_analyze_entity_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_sync] +# [END language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_async.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py index 93b29343..5ecddcea 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeSentiment_async] +# [START language_v1_generated_LanguageService_AnalyzeSentiment_async] from google.cloud import language_v1 @@ -45,4 +45,4 @@ async def sample_analyze_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeSentiment_async] +# [END language_v1_generated_LanguageService_AnalyzeSentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_sync.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py index aee0a746..4432bae8 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_sentiment_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeSentiment_sync] +# [START language_v1_generated_LanguageService_AnalyzeSentiment_sync] from google.cloud import language_v1 @@ -45,4 +45,4 @@ def sample_analyze_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeSentiment_sync] +# [END language_v1_generated_LanguageService_AnalyzeSentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_async.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py index 77c8c239..42ff7dc8 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeSyntax_async] +# [START language_v1_generated_LanguageService_AnalyzeSyntax_async] from google.cloud import language_v1 @@ -45,4 +45,4 @@ async def sample_analyze_syntax(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeSyntax_async] +# [END language_v1_generated_LanguageService_AnalyzeSyntax_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_sync.py rename to samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py index aa7ec47f..f6e60b25 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_analyze_syntax_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnalyzeSyntax_sync] +# [START language_v1_generated_LanguageService_AnalyzeSyntax_sync] from google.cloud import language_v1 @@ -45,4 +45,4 @@ def sample_analyze_syntax(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnalyzeSyntax_sync] +# [END language_v1_generated_LanguageService_AnalyzeSyntax_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_async.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_annotate_text_async.py rename to samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py index 5ae9ff97..5688624d 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnnotateText_async] +# [START language_v1_generated_LanguageService_AnnotateText_async] from google.cloud import language_v1 @@ -45,4 +45,4 @@ async def sample_annotate_text(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnnotateText_async] +# [END language_v1_generated_LanguageService_AnnotateText_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_annotate_text_sync.py rename to samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py index 59e182e2..fc25e29d 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_annotate_text_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_AnnotateText_sync] +# [START language_v1_generated_LanguageService_AnnotateText_sync] from google.cloud import language_v1 @@ -45,4 +45,4 @@ def sample_annotate_text(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_AnnotateText_sync] +# [END language_v1_generated_LanguageService_AnnotateText_sync] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_classify_text_async.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_classify_text_async.py rename to samples/generated_samples/language_v1_generated_language_service_classify_text_async.py index 47c93312..467ccf14 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_classify_text_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_ClassifyText_async] +# [START language_v1_generated_LanguageService_ClassifyText_async] from google.cloud import language_v1 @@ -45,4 +45,4 @@ async def sample_classify_text(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_ClassifyText_async] +# [END language_v1_generated_LanguageService_ClassifyText_async] diff --git a/samples/generated_samples/language_generated_language_v1_language_service_classify_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py similarity index 90% rename from samples/generated_samples/language_generated_language_v1_language_service_classify_text_sync.py rename to samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py index 1c4c1796..971ac522 100644 --- a/samples/generated_samples/language_generated_language_v1_language_service_classify_text_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1_LanguageService_ClassifyText_sync] +# [START language_v1_generated_LanguageService_ClassifyText_sync] from google.cloud import language_v1 @@ -45,4 +45,4 @@ def sample_classify_text(): # Handle the response print(response) -# [END language_generated_language_v1_LanguageService_ClassifyText_sync] +# [END language_v1_generated_LanguageService_ClassifyText_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_async.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py index 42f6a383..21dac6b8 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntities_async] +# [START language_v1beta2_generated_LanguageService_AnalyzeEntities_async] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ async def sample_analyze_entities(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntities_async] +# [END language_v1beta2_generated_LanguageService_AnalyzeEntities_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_sync.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py index cacaee20..6bd39eac 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entities_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntities_sync] +# [START language_v1beta2_generated_LanguageService_AnalyzeEntities_sync] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ def sample_analyze_entities(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntities_sync] +# [END language_v1beta2_generated_LanguageService_AnalyzeEntities_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py index d1af0e16..a4758665 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_async] +# [START language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ async def sample_analyze_entity_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_async] +# [END language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py index 172d9e85..ced33c17 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_sync] +# [START language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ def sample_analyze_entity_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_sync] +# [END language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_async.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py index f02f3641..83eb6498 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_async] +# [START language_v1beta2_generated_LanguageService_AnalyzeSentiment_async] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ async def sample_analyze_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_async] +# [END language_v1beta2_generated_LanguageService_AnalyzeSentiment_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py index b600c188..d8871001 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_sync] +# [START language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ def sample_analyze_sentiment(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_sync] +# [END language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_async.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py index 33d9637d..49075225 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_async] +# [START language_v1beta2_generated_LanguageService_AnalyzeSyntax_async] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ async def sample_analyze_syntax(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_async] +# [END language_v1beta2_generated_LanguageService_AnalyzeSyntax_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_sync.py rename to samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py index 2d9fc145..f1352edd 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_analyze_syntax_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_sync] +# [START language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ def sample_analyze_syntax(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_sync] +# [END language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_async.py rename to samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py index f352aa75..ac1d1519 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnnotateText_async] +# [START language_v1beta2_generated_LanguageService_AnnotateText_async] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ async def sample_annotate_text(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnnotateText_async] +# [END language_v1beta2_generated_LanguageService_AnnotateText_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_sync.py rename to samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py index f1a0d007..c14bfe11 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_annotate_text_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_AnnotateText_sync] +# [START language_v1beta2_generated_LanguageService_AnnotateText_sync] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ def sample_annotate_text(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_AnnotateText_sync] +# [END language_v1beta2_generated_LanguageService_AnnotateText_sync] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_async.py rename to samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py index a9bfabfc..dd669c0e 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_ClassifyText_async] +# [START language_v1beta2_generated_LanguageService_ClassifyText_async] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ async def sample_classify_text(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_ClassifyText_async] +# [END language_v1beta2_generated_LanguageService_ClassifyText_async] diff --git a/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py similarity index 89% rename from samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_sync.py rename to samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py index abef8641..bd2b3b7e 100644 --- a/samples/generated_samples/language_generated_language_v1beta2_language_service_classify_text_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-language -# [START language_generated_language_v1beta2_LanguageService_ClassifyText_sync] +# [START language_v1beta2_generated_LanguageService_ClassifyText_sync] from google.cloud import language_v1beta2 @@ -45,4 +45,4 @@ def sample_classify_text(): # Handle the response print(response) -# [END language_generated_language_v1beta2_LanguageService_ClassifyText_sync] +# [END language_v1beta2_generated_LanguageService_ClassifyText_sync] diff --git a/samples/generated_samples/snippet_metadata_language_v1.json b/samples/generated_samples/snippet_metadata_language_v1.json index a0805e26..ad0df512 100644 --- a/samples/generated_samples/snippet_metadata_language_v1.json +++ b/samples/generated_samples/snippet_metadata_language_v1.json @@ -10,8 +10,8 @@ "shortName": "AnalyzeEntities" } }, - "file": "language_generated_language_v1_language_service_analyze_entities_async.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntities_async", + "file": "language_v1_generated_language_service_analyze_entities_async.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_async", "segments": [ { "end": 47, @@ -54,8 +54,8 @@ "shortName": "AnalyzeEntities" } }, - "file": "language_generated_language_v1_language_service_analyze_entities_sync.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntities_sync", + "file": "language_v1_generated_language_service_analyze_entities_sync.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_sync", "segments": [ { "end": 47, @@ -99,8 +99,8 @@ "shortName": "AnalyzeEntitySentiment" } }, - "file": "language_generated_language_v1_language_service_analyze_entity_sentiment_async.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_async", + "file": "language_v1_generated_language_service_analyze_entity_sentiment_async.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_async", "segments": [ { "end": 47, @@ -143,8 +143,8 @@ "shortName": "AnalyzeEntitySentiment" } }, - "file": "language_generated_language_v1_language_service_analyze_entity_sentiment_sync.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeEntitySentiment_sync", + "file": "language_v1_generated_language_service_analyze_entity_sentiment_sync.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync", "segments": [ { "end": 47, @@ -188,8 +188,8 @@ "shortName": "AnalyzeSentiment" } }, - "file": "language_generated_language_v1_language_service_analyze_sentiment_async.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSentiment_async", + "file": "language_v1_generated_language_service_analyze_sentiment_async.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_async", "segments": [ { "end": 47, @@ -232,8 +232,8 @@ "shortName": "AnalyzeSentiment" } }, - "file": "language_generated_language_v1_language_service_analyze_sentiment_sync.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSentiment_sync", + "file": "language_v1_generated_language_service_analyze_sentiment_sync.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_sync", "segments": [ { "end": 47, @@ -277,8 +277,8 @@ "shortName": "AnalyzeSyntax" } }, - "file": "language_generated_language_v1_language_service_analyze_syntax_async.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSyntax_async", + "file": "language_v1_generated_language_service_analyze_syntax_async.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_async", "segments": [ { "end": 47, @@ -321,8 +321,8 @@ "shortName": "AnalyzeSyntax" } }, - "file": "language_generated_language_v1_language_service_analyze_syntax_sync.py", - "regionTag": "language_generated_language_v1_LanguageService_AnalyzeSyntax_sync", + "file": "language_v1_generated_language_service_analyze_syntax_sync.py", + "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_sync", "segments": [ { "end": 47, @@ -366,8 +366,8 @@ "shortName": "AnnotateText" } }, - "file": "language_generated_language_v1_language_service_annotate_text_async.py", - "regionTag": "language_generated_language_v1_LanguageService_AnnotateText_async", + "file": "language_v1_generated_language_service_annotate_text_async.py", + "regionTag": "language_v1_generated_LanguageService_AnnotateText_async", "segments": [ { "end": 47, @@ -410,8 +410,8 @@ "shortName": "AnnotateText" } }, - "file": "language_generated_language_v1_language_service_annotate_text_sync.py", - "regionTag": "language_generated_language_v1_LanguageService_AnnotateText_sync", + "file": "language_v1_generated_language_service_annotate_text_sync.py", + "regionTag": "language_v1_generated_LanguageService_AnnotateText_sync", "segments": [ { "end": 47, @@ -455,8 +455,8 @@ "shortName": "ClassifyText" } }, - "file": "language_generated_language_v1_language_service_classify_text_async.py", - "regionTag": "language_generated_language_v1_LanguageService_ClassifyText_async", + "file": "language_v1_generated_language_service_classify_text_async.py", + "regionTag": "language_v1_generated_LanguageService_ClassifyText_async", "segments": [ { "end": 47, @@ -499,8 +499,8 @@ "shortName": "ClassifyText" } }, - "file": "language_generated_language_v1_language_service_classify_text_sync.py", - "regionTag": "language_generated_language_v1_LanguageService_ClassifyText_sync", + "file": "language_v1_generated_language_service_classify_text_sync.py", + "regionTag": "language_v1_generated_LanguageService_ClassifyText_sync", "segments": [ { "end": 47, diff --git a/samples/generated_samples/snippet_metadata_language_v1beta2.json b/samples/generated_samples/snippet_metadata_language_v1beta2.json index 44e01853..68415e8e 100644 --- a/samples/generated_samples/snippet_metadata_language_v1beta2.json +++ b/samples/generated_samples/snippet_metadata_language_v1beta2.json @@ -10,8 +10,8 @@ "shortName": "AnalyzeEntities" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_entities_async.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntities_async", + "file": "language_v1beta2_generated_language_service_analyze_entities_async.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_async", "segments": [ { "end": 47, @@ -54,8 +54,8 @@ "shortName": "AnalyzeEntities" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_entities_sync.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntities_sync", + "file": "language_v1beta2_generated_language_service_analyze_entities_sync.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_sync", "segments": [ { "end": 47, @@ -99,8 +99,8 @@ "shortName": "AnalyzeEntitySentiment" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_entity_sentiment_async.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_async", + "file": "language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async", "segments": [ { "end": 47, @@ -143,8 +143,8 @@ "shortName": "AnalyzeEntitySentiment" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_entity_sentiment_sync.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeEntitySentiment_sync", + "file": "language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync", "segments": [ { "end": 47, @@ -188,8 +188,8 @@ "shortName": "AnalyzeSentiment" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_sentiment_async.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_async", + "file": "language_v1beta2_generated_language_service_analyze_sentiment_async.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_async", "segments": [ { "end": 47, @@ -232,8 +232,8 @@ "shortName": "AnalyzeSentiment" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_sentiment_sync.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSentiment_sync", + "file": "language_v1beta2_generated_language_service_analyze_sentiment_sync.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync", "segments": [ { "end": 47, @@ -277,8 +277,8 @@ "shortName": "AnalyzeSyntax" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_syntax_async.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_async", + "file": "language_v1beta2_generated_language_service_analyze_syntax_async.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_async", "segments": [ { "end": 47, @@ -321,8 +321,8 @@ "shortName": "AnalyzeSyntax" } }, - "file": "language_generated_language_v1beta2_language_service_analyze_syntax_sync.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnalyzeSyntax_sync", + "file": "language_v1beta2_generated_language_service_analyze_syntax_sync.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync", "segments": [ { "end": 47, @@ -366,8 +366,8 @@ "shortName": "AnnotateText" } }, - "file": "language_generated_language_v1beta2_language_service_annotate_text_async.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnnotateText_async", + "file": "language_v1beta2_generated_language_service_annotate_text_async.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_async", "segments": [ { "end": 47, @@ -410,8 +410,8 @@ "shortName": "AnnotateText" } }, - "file": "language_generated_language_v1beta2_language_service_annotate_text_sync.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_AnnotateText_sync", + "file": "language_v1beta2_generated_language_service_annotate_text_sync.py", + "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_sync", "segments": [ { "end": 47, @@ -455,8 +455,8 @@ "shortName": "ClassifyText" } }, - "file": "language_generated_language_v1beta2_language_service_classify_text_async.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_ClassifyText_async", + "file": "language_v1beta2_generated_language_service_classify_text_async.py", + "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_async", "segments": [ { "end": 47, @@ -499,8 +499,8 @@ "shortName": "ClassifyText" } }, - "file": "language_generated_language_v1beta2_language_service_classify_text_sync.py", - "regionTag": "language_generated_language_v1beta2_LanguageService_ClassifyText_sync", + "file": "language_v1beta2_generated_language_service_classify_text_sync.py", + "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_sync", "segments": [ { "end": 47, From 9f3c29d86e9dd8c4c9c8d4504a515b5e26a8b909 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 26 Feb 2022 05:27:16 -0500 Subject: [PATCH 118/254] chore: update copyright year to 2022 (#264) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: update copyright year to 2022 PiperOrigin-RevId: 431037888 Source-Link: https://github.com/googleapis/googleapis/commit/b3397f5febbf21dfc69b875ddabaf76bee765058 Source-Link: https://github.com/googleapis/googleapis-gen/commit/510b54e1cdefd53173984df16645081308fe897e Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTEwYjU0ZTFjZGVmZDUzMTczOTg0ZGYxNjY0NTA4MTMwOGZlODk3ZSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- google/cloud/language/__init__.py | 2 +- google/cloud/language_v1/__init__.py | 2 +- google/cloud/language_v1/services/__init__.py | 2 +- google/cloud/language_v1/services/language_service/__init__.py | 2 +- .../cloud/language_v1/services/language_service/async_client.py | 2 +- google/cloud/language_v1/services/language_service/client.py | 2 +- .../services/language_service/transports/__init__.py | 2 +- .../language_v1/services/language_service/transports/base.py | 2 +- .../language_v1/services/language_service/transports/grpc.py | 2 +- .../services/language_service/transports/grpc_asyncio.py | 2 +- google/cloud/language_v1/types/__init__.py | 2 +- google/cloud/language_v1/types/language_service.py | 2 +- google/cloud/language_v1beta2/__init__.py | 2 +- google/cloud/language_v1beta2/services/__init__.py | 2 +- .../language_v1beta2/services/language_service/__init__.py | 2 +- .../language_v1beta2/services/language_service/async_client.py | 2 +- .../cloud/language_v1beta2/services/language_service/client.py | 2 +- .../services/language_service/transports/__init__.py | 2 +- .../services/language_service/transports/base.py | 2 +- .../services/language_service/transports/grpc.py | 2 +- .../services/language_service/transports/grpc_asyncio.py | 2 +- google/cloud/language_v1beta2/types/__init__.py | 2 +- google/cloud/language_v1beta2/types/language_service.py | 2 +- ...uage_v1_generated_language_service_analyze_entities_async.py | 2 +- ...guage_v1_generated_language_service_analyze_entities_sync.py | 2 +- ...generated_language_service_analyze_entity_sentiment_async.py | 2 +- ..._generated_language_service_analyze_entity_sentiment_sync.py | 2 +- ...age_v1_generated_language_service_analyze_sentiment_async.py | 2 +- ...uage_v1_generated_language_service_analyze_sentiment_sync.py | 2 +- ...nguage_v1_generated_language_service_analyze_syntax_async.py | 2 +- ...anguage_v1_generated_language_service_analyze_syntax_sync.py | 2 +- ...anguage_v1_generated_language_service_annotate_text_async.py | 2 +- ...language_v1_generated_language_service_annotate_text_sync.py | 2 +- ...anguage_v1_generated_language_service_classify_text_async.py | 2 +- ...language_v1_generated_language_service_classify_text_sync.py | 2 +- ...v1beta2_generated_language_service_analyze_entities_async.py | 2 +- ..._v1beta2_generated_language_service_analyze_entities_sync.py | 2 +- ...generated_language_service_analyze_entity_sentiment_async.py | 2 +- ..._generated_language_service_analyze_entity_sentiment_sync.py | 2 +- ...1beta2_generated_language_service_analyze_sentiment_async.py | 2 +- ...v1beta2_generated_language_service_analyze_sentiment_sync.py | 2 +- ...e_v1beta2_generated_language_service_analyze_syntax_async.py | 2 +- ...ge_v1beta2_generated_language_service_analyze_syntax_sync.py | 2 +- ...ge_v1beta2_generated_language_service_annotate_text_async.py | 2 +- ...age_v1beta2_generated_language_service_annotate_text_sync.py | 2 +- ...ge_v1beta2_generated_language_service_classify_text_async.py | 2 +- ...age_v1beta2_generated_language_service_classify_text_sync.py | 2 +- scripts/fixup_language_v1_keywords.py | 2 +- scripts/fixup_language_v1beta2_keywords.py | 2 +- tests/__init__.py | 2 +- tests/unit/__init__.py | 2 +- tests/unit/gapic/__init__.py | 2 +- tests/unit/gapic/language_v1/__init__.py | 2 +- tests/unit/gapic/language_v1/test_language_service.py | 2 +- tests/unit/gapic/language_v1beta2/__init__.py | 2 +- tests/unit/gapic/language_v1beta2/test_language_service.py | 2 +- 56 files changed, 56 insertions(+), 56 deletions(-) diff --git a/google/cloud/language/__init__.py b/google/cloud/language/__init__.py index ef7f887d..07624150 100644 --- a/google/cloud/language/__init__.py +++ b/google/cloud/language/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py index ad83a6fa..bcca7fb4 100644 --- a/google/cloud/language_v1/__init__.py +++ b/google/cloud/language_v1/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/__init__.py b/google/cloud/language_v1/services/__init__.py index 4de65971..e8e1c384 100644 --- a/google/cloud/language_v1/services/__init__.py +++ b/google/cloud/language_v1/services/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/language_service/__init__.py b/google/cloud/language_v1/services/language_service/__init__.py index 46ba988d..d12b0495 100644 --- a/google/cloud/language_v1/services/language_service/__init__.py +++ b/google/cloud/language_v1/services/language_service/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index f6435aa8..33e58142 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 69f42618..0942d7f2 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/language_service/transports/__init__.py b/google/cloud/language_v1/services/language_service/transports/__init__.py index be3ebc9a..2cb702a6 100644 --- a/google/cloud/language_v1/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1/services/language_service/transports/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 5d147fc1..b1f97f7a 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 5657b6a1..86ea561d 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 4490dab8..4b10a361 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/types/__init__.py b/google/cloud/language_v1/types/__init__.py index adb04117..6a80ff72 100644 --- a/google/cloud/language_v1/types/__init__.py +++ b/google/cloud/language_v1/types/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 25a6fff4..02fec89c 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py index ad83a6fa..bcca7fb4 100644 --- a/google/cloud/language_v1beta2/__init__.py +++ b/google/cloud/language_v1beta2/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/__init__.py b/google/cloud/language_v1beta2/services/__init__.py index 4de65971..e8e1c384 100644 --- a/google/cloud/language_v1beta2/services/__init__.py +++ b/google/cloud/language_v1beta2/services/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/language_service/__init__.py b/google/cloud/language_v1beta2/services/language_service/__init__.py index 46ba988d..d12b0495 100644 --- a/google/cloud/language_v1beta2/services/language_service/__init__.py +++ b/google/cloud/language_v1beta2/services/language_service/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 3565d049..1a212bd5 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 00781271..83cd0992 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py index be3ebc9a..2cb702a6 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index ea3aba83..cc1fbc12 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index f962d7dc..c09dea48 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index ca6b00b3..4cb0142e 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/types/__init__.py b/google/cloud/language_v1beta2/types/__init__.py index adb04117..6a80ff72 100644 --- a/google/cloud/language_v1beta2/types/__init__.py +++ b/google/cloud/language_v1beta2/types/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 68f9297b..3c168b58 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py index 4425e700..32be0c31 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py index b472cbb9..4321949c 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py index 6877a933..ed70384b 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py index 717f6a26..59315468 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py index 5ecddcea..2391f11c 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py index 4432bae8..c588371f 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py index 42ff7dc8..ea004078 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py index f6e60b25..01df9c51 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py index 5688624d..0edccb1a 100644 --- a/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py index fc25e29d..2ccfc4dd 100644 --- a/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py index 467ccf14..1ceb7247 100644 --- a/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py index 971ac522..335d74a1 100644 --- a/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py index 21dac6b8..f69b7fbd 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py index 6bd39eac..77dc2c4f 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py index a4758665..ec6b1a8e 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py index ced33c17..74815762 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py index 83eb6498..bea0b0d8 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py index d8871001..55031f69 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py index 49075225..481b9d99 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py index f1352edd..73d34c96 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py index ac1d1519..fc3619c5 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py index c14bfe11..ac8a7636 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py index dd669c0e..72d76f60 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py index bd2b3b7e..9d000fc2 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/scripts/fixup_language_v1_keywords.py b/scripts/fixup_language_v1_keywords.py index aac999b1..e4268c0f 100644 --- a/scripts/fixup_language_v1_keywords.py +++ b/scripts/fixup_language_v1_keywords.py @@ -1,6 +1,6 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/scripts/fixup_language_v1beta2_keywords.py b/scripts/fixup_language_v1beta2_keywords.py index aac999b1..e4268c0f 100644 --- a/scripts/fixup_language_v1beta2_keywords.py +++ b/scripts/fixup_language_v1beta2_keywords.py @@ -1,6 +1,6 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/__init__.py b/tests/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/unit/gapic/__init__.py +++ b/tests/unit/gapic/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/gapic/language_v1/__init__.py b/tests/unit/gapic/language_v1/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/unit/gapic/language_v1/__init__.py +++ b/tests/unit/gapic/language_v1/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index e322b5db..859fa443 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/gapic/language_v1beta2/__init__.py b/tests/unit/gapic/language_v1beta2/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/unit/gapic/language_v1beta2/__init__.py +++ b/tests/unit/gapic/language_v1beta2/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index d3462f23..681ab4b3 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From c61378b84106928c6dcffbe49db2104960332888 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Sat, 26 Feb 2022 20:04:49 +0100 Subject: [PATCH 119/254] chore(deps): update all dependencies (#253) * chore(deps): update all dependencies * revert numpy pin changes for python <= 3.7 * add classifier for python 3.9 and 3.10 Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- setup.py | 2 ++ 6 files changed, 7 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index c86677b3..8418e788 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.36.0 -google-auth==2.3.3 +google-auth==2.4.1 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index b562bb86..572357c3 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.3.1 +google-cloud-language==2.3.2 numpy==1.22.1; python_version > '3.7' numpy==1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index d2b8f2f0..8d0fae86 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.3.1 +google-cloud-language==2.3.2 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index d2b8f2f0..8d0fae86 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.3.1 +google-cloud-language==2.3.2 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index d2b8f2f0..8d0fae86 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.3.1 +google-cloud-language==2.3.2 diff --git a/setup.py b/setup.py index cd04169e..66e7d024 100644 --- a/setup.py +++ b/setup.py @@ -78,6 +78,8 @@ "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", "Operating System :: OS Independent", "Topic :: Internet", ], From ad568d04d0c6106803cdc249b7ac8a6b623a7ec4 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Mon, 28 Feb 2022 23:52:22 +0100 Subject: [PATCH 120/254] chore(deps): update all dependencies (#265) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update all dependencies * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert change for python 3.7 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements-test.txt | 2 +- samples/snippets/api/requirements.txt | 4 ++-- samples/snippets/classify_text/requirements-test.txt | 2 +- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements-test.txt | 2 +- samples/snippets/generated-samples/v1/requirements-test.txt | 2 +- samples/snippets/sentiment/requirements-test.txt | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt index 92709451..c2845bff 100644 --- a/samples/snippets/api/requirements-test.txt +++ b/samples/snippets/api/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.5 +pytest==7.0.1 diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 8418e788..16bc690d 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.36.0 -google-auth==2.4.1 +google-api-python-client==2.38.0 +google-auth==2.6.0 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt index 92709451..c2845bff 100644 --- a/samples/snippets/classify_text/requirements-test.txt +++ b/samples/snippets/classify_text/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.5 +pytest==7.0.1 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 572357c3..33cadea4 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ google-cloud-language==2.3.2 -numpy==1.22.1; python_version > '3.7' +numpy==1.22.2; python_version > '3.7' numpy==1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt index 92709451..c2845bff 100644 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ b/samples/snippets/cloud-client/v1/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.5 +pytest==7.0.1 diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt index 92709451..c2845bff 100644 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ b/samples/snippets/generated-samples/v1/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.5 +pytest==7.0.1 diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt index 92709451..c2845bff 100644 --- a/samples/snippets/sentiment/requirements-test.txt +++ b/samples/snippets/sentiment/requirements-test.txt @@ -1 +1 @@ -pytest==6.2.5 +pytest==7.0.1 From 8337d97f5ce3de0d3e4e3d37cd3967413941bfdf Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 28 Feb 2022 18:01:26 -0500 Subject: [PATCH 121/254] chore(main): release 2.4.0 (#257) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 12 ++++++++++++ setup.py | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6fe8a06..46634590 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.4.0](https://github.com/googleapis/python-language/compare/v2.3.2...v2.4.0) (2022-02-28) + + +### Features + +* add api key support ([#256](https://github.com/googleapis/python-language/issues/256)) ([593ec8a](https://github.com/googleapis/python-language/commit/593ec8a998c612b3a87b4b9a53bd166c0b2c10f6)) + + +### Bug Fixes + +* resolve DuplicateCredentialArgs error when using credentials_file ([3e7c964](https://github.com/googleapis/python-language/commit/3e7c96410914d9080ecd0325c61bdc624adf08e1)) + ### [2.3.2](https://github.com/googleapis/python-language/compare/v2.3.1...v2.3.2) (2022-01-20) diff --git a/setup.py b/setup.py index 66e7d024..443d0541 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.3.2" +version = "2.4.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From ae431d81c380c6c91483b7fd39b16420d9090fa8 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 1 Mar 2022 12:34:18 +0000 Subject: [PATCH 122/254] chore(deps): update actions/setup-python action to v3 (#270) Source-Link: https://github.com/googleapis/synthtool/commit/571ee2c3b26182429eddcf115122ee545d7d3787 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:660abdf857d3ab9aabcd967c163c70e657fcc5653595c709263af5f3fa23ef67 --- .github/.OwlBot.lock.yaml | 3 +-- .github/workflows/docs.yml | 4 ++-- .github/workflows/lint.yml | 2 +- .github/workflows/unittest.yml | 4 ++-- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index b668c04d..d9a55fa4 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ed1f9983d5a935a89fe8085e8bb97d94e41015252c5b6c9771257cf8624367e6 - + digest: sha256:660abdf857d3ab9aabcd967c163c70e657fcc5653595c709263af5f3fa23ef67 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index f7b8344c..cca4e98b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -10,7 +10,7 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v3 with: python-version: "3.10" - name: Install nox @@ -26,7 +26,7 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v3 with: python-version: "3.10" - name: Install nox diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 1e8b05c3..f687324e 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -10,7 +10,7 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v3 with: python-version: "3.10" - name: Install nox diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 074ee250..d3003e09 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -13,7 +13,7 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v3 with: python-version: ${{ matrix.python }} - name: Install nox @@ -39,7 +39,7 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v3 with: python-version: "3.10" - name: Install coverage From 4f96a1e9394567a583e3facb3a7198b2075ead1b Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 1 Mar 2022 16:25:09 +0100 Subject: [PATCH 123/254] chore(deps): update all dependencies (#269) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update all dependencies * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert change Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 16bc690d..616dfb22 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.38.0 +google-api-python-client==2.39.0 google-auth==2.6.0 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 33cadea4..51bd8a78 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.3.2 +google-cloud-language==2.4.0 numpy==1.22.2; python_version > '3.7' numpy==1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 8d0fae86..94560e6f 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.3.2 +google-cloud-language==2.4.0 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 8d0fae86..94560e6f 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.3.2 +google-cloud-language==2.4.0 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 8d0fae86..94560e6f 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.3.2 +google-cloud-language==2.4.0 From b01cbd6b84b98212e44c5a5e1a0fedbc48c566f6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 3 Mar 2022 00:30:35 +0000 Subject: [PATCH 124/254] chore(deps): update actions/checkout action to v3 (#272) Source-Link: https://github.com/googleapis/synthtool/commit/ca879097772aeec2cbb971c3cea8ecc81522b68a Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:6162c384d685c5fe22521d3f37f6fc732bf99a085f6d47b677dbcae97fc21392 --- .github/.OwlBot.lock.yaml | 2 +- .github/workflows/docs.yml | 4 ++-- .github/workflows/lint.yml | 2 +- .github/workflows/unittest.yml | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index d9a55fa4..480226ac 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:660abdf857d3ab9aabcd967c163c70e657fcc5653595c709263af5f3fa23ef67 + digest: sha256:6162c384d685c5fe22521d3f37f6fc732bf99a085f6d47b677dbcae97fc21392 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index cca4e98b..b46d7305 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v3 with: @@ -24,7 +24,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v3 with: diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index f687324e..f512a496 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v3 with: diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index d3003e09..e87fe5b7 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -11,7 +11,7 @@ jobs: python: ['3.6', '3.7', '3.8', '3.9', '3.10'] steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v3 with: @@ -37,7 +37,7 @@ jobs: - unit steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v3 with: From 94b2ae43c46cd6d56e0ee407a44011b42d8e77b1 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Fri, 4 Mar 2022 11:47:20 -0500 Subject: [PATCH 125/254] fix(deps): require google-api-core>=1.31.5, >=2.3.2 (#273) fix(deps): require proto-plus>=1.15.0 --- setup.py | 4 ++-- testing/constraints-3.6.txt | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index 443d0541..98bbcfa9 100644 --- a/setup.py +++ b/setup.py @@ -32,8 +32,8 @@ # NOTE: Maintainers, please do not require google-api-core>=2.x.x # Until this issue is closed # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-api-core[grpc] >= 1.28.0, <3.0.0dev", - "proto-plus >= 1.10.0", + "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", + "proto-plus >= 1.15.0", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 9e0fb5ad..9f7fec03 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -4,6 +4,6 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.28.0 -proto-plus==1.10.0 +google-api-core==1.31.5 +proto-plus==1.15.0 libcst==0.2.5 From a5db2724b9b9915a51557c799a1fca3a61c3b8be Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 4 Mar 2022 12:47:52 -0500 Subject: [PATCH 126/254] chore: Adding support for pytest-xdist and pytest-parallel (#274) Source-Link: https://github.com/googleapis/synthtool/commit/82f5cb283efffe96e1b6cd634738e0e7de2cd90a Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:5d8da01438ece4021d135433f2cf3227aa39ef0eaccc941d62aa35e6902832ae Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 78 +++++++++++-------- samples/snippets/classify_text/noxfile.py | 78 +++++++++++-------- samples/snippets/cloud-client/v1/noxfile.py | 78 +++++++++++-------- .../snippets/generated-samples/v1/noxfile.py | 78 +++++++++++-------- samples/snippets/sentiment/noxfile.py | 78 +++++++++++-------- 6 files changed, 221 insertions(+), 171 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 480226ac..7e08e05a 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:6162c384d685c5fe22521d3f37f6fc732bf99a085f6d47b677dbcae97fc21392 + digest: sha256:5d8da01438ece4021d135433f2cf3227aa39ef0eaccc941d62aa35e6902832ae diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 20cdfc62..85f5836d 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -188,42 +188,52 @@ def _session_tests( # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") test_list.extend(glob.glob("tests")) + if len(test_list) == 0: print("No tests found, skipping directory.") - else: - 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + return + + 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.""" + concurrent_args = [] + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + with open("requirements.txt") as rfile: + packages = rfile.read() + + if os.path.exists("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") + with open("requirements-test.txt") as rtfile: + packages += rtfile.read() + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + if "pytest-parallel" in packages: + concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) + elif "pytest-xdist" in packages: + concurrent_args.extend(["-n", "auto"]) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 20cdfc62..85f5836d 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -188,42 +188,52 @@ def _session_tests( # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") test_list.extend(glob.glob("tests")) + if len(test_list) == 0: print("No tests found, skipping directory.") - else: - 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + return + + 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.""" + concurrent_args = [] + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + with open("requirements.txt") as rfile: + packages = rfile.read() + + if os.path.exists("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") + with open("requirements-test.txt") as rtfile: + packages += rtfile.read() + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + if "pytest-parallel" in packages: + concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) + elif "pytest-xdist" in packages: + concurrent_args.extend(["-n", "auto"]) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 20cdfc62..85f5836d 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -188,42 +188,52 @@ def _session_tests( # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") test_list.extend(glob.glob("tests")) + if len(test_list) == 0: print("No tests found, skipping directory.") - else: - 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + return + + 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.""" + concurrent_args = [] + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + with open("requirements.txt") as rfile: + packages = rfile.read() + + if os.path.exists("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") + with open("requirements-test.txt") as rtfile: + packages += rtfile.read() + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + if "pytest-parallel" in packages: + concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) + elif "pytest-xdist" in packages: + concurrent_args.extend(["-n", "auto"]) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 20cdfc62..85f5836d 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -188,42 +188,52 @@ def _session_tests( # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") test_list.extend(glob.glob("tests")) + if len(test_list) == 0: print("No tests found, skipping directory.") - else: - 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + return + + 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.""" + concurrent_args = [] + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + with open("requirements.txt") as rfile: + packages = rfile.read() + + if os.path.exists("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") + with open("requirements-test.txt") as rtfile: + packages += rtfile.read() + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + if "pytest-parallel" in packages: + concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) + elif "pytest-xdist" in packages: + concurrent_args.extend(["-n", "auto"]) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 20cdfc62..85f5836d 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -188,42 +188,52 @@ def _session_tests( # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") test_list.extend(glob.glob("tests")) + if len(test_list) == 0: print("No tests found, skipping directory.") - else: - 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"): - 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"): - 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()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + return + + 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.""" + concurrent_args = [] + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + with open("requirements.txt") as rfile: + packages = rfile.read() + + if os.path.exists("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") + with open("requirements-test.txt") as rtfile: + packages += rtfile.read() + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + if "pytest-parallel" in packages: + concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) + elif "pytest-xdist" in packages: + concurrent_args.extend(["-n", "auto"]) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) From 6f326ac64d7687f57f7475501b031f216af1172c Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 5 Mar 2022 00:28:16 +0000 Subject: [PATCH 127/254] chore(deps): update actions/download-artifact action to v3 (#276) Source-Link: https://github.com/googleapis/synthtool/commit/38e11ad1104dcc1e63b52691ddf2fe4015d06955 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:4e1991042fe54b991db9ca17c8fb386e61b22fe4d1472a568bf0fcac85dcf5d3 --- .github/.OwlBot.lock.yaml | 2 +- .github/workflows/unittest.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 7e08e05a..44c78f7c 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:5d8da01438ece4021d135433f2cf3227aa39ef0eaccc941d62aa35e6902832ae + digest: sha256:4e1991042fe54b991db9ca17c8fb386e61b22fe4d1472a568bf0fcac85dcf5d3 diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index e87fe5b7..e5be6edb 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -26,7 +26,7 @@ jobs: run: | nox -s unit-${{ matrix.python }} - name: Upload coverage results - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: coverage-artifacts path: .coverage-${{ matrix.python }} @@ -47,7 +47,7 @@ jobs: python -m pip install --upgrade setuptools pip wheel python -m pip install coverage - name: Download coverage results - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v3 with: name: coverage-artifacts path: .coverage-results/ From 321b43a34ac4f0a73c684e1fce5f5409273f7a68 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 7 Mar 2022 10:58:02 -0500 Subject: [PATCH 128/254] chore(main): release 2.4.1 (#275) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 8 ++++++++ setup.py | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46634590..be795a5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-language/#history +### [2.4.1](https://github.com/googleapis/python-language/compare/v2.4.0...v2.4.1) (2022-03-05) + + +### Bug Fixes + +* **deps:** require google-api-core>=1.31.5, >=2.3.2 ([#273](https://github.com/googleapis/python-language/issues/273)) ([94b2ae4](https://github.com/googleapis/python-language/commit/94b2ae43c46cd6d56e0ee407a44011b42d8e77b1)) +* **deps:** require proto-plus>=1.15.0 ([94b2ae4](https://github.com/googleapis/python-language/commit/94b2ae43c46cd6d56e0ee407a44011b42d8e77b1)) + ## [2.4.0](https://github.com/googleapis/python-language/compare/v2.3.2...v2.4.0) (2022-02-28) diff --git a/setup.py b/setup.py index 98bbcfa9..7547eb60 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.4.0" +version = "2.4.1" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From d184b2ad0bb83cc8b59cc0584e9e3ab5bde76bd5 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 8 Mar 2022 02:48:49 +0100 Subject: [PATCH 129/254] chore(deps): update all dependencies (#278) * chore(deps): update all dependencies * revert Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/classify_text/requirements.txt | 4 ++-- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 51bd8a78..1c28b1e2 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.4.0 -numpy==1.22.2; python_version > '3.7' +google-cloud-language==2.4.1 +numpy==1.22.3; python_version > '3.7' numpy==1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 94560e6f..0d2a8d65 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.0 +google-cloud-language==2.4.1 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 94560e6f..0d2a8d65 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.0 +google-cloud-language==2.4.1 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 94560e6f..0d2a8d65 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.0 +google-cloud-language==2.4.1 From d0479997f751e23f05963026c6d4d6de4cb41f00 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 23 Mar 2022 11:38:11 -0600 Subject: [PATCH 130/254] chore(python): configure release-please on previous major versions (#282) Source-Link: https://github.com/googleapis/synthtool/commit/c1dd87e9287f8de99930d3046dd555c4d03384c6 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:2d13c2172a5d6129c861edaa48b60ead15aeaf58aa75e02d870c4cbdfa63aaba Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 2 +- .github/release-please.yml | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 44c78f7c..88076277 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:4e1991042fe54b991db9ca17c8fb386e61b22fe4d1472a568bf0fcac85dcf5d3 + digest: sha256:2d13c2172a5d6129c861edaa48b60ead15aeaf58aa75e02d870c4cbdfa63aaba diff --git a/.github/release-please.yml b/.github/release-please.yml index 466597e5..29601ad4 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,2 +1,11 @@ releaseType: python handleGHRelease: true +# NOTE: this section is generated by synthtool.languages.python +# See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py +branches: +- branch: v1 + handleGHRelease: true + releaseType: python +- branch: v0 + handleGHRelease: true + releaseType: python From 9e8536b47cd9e592631e1fcf08ea1b87af50aa1f Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 28 Mar 2022 19:59:25 -0400 Subject: [PATCH 131/254] chore(python): use black==22.3.0 (#283) Source-Link: https://github.com/googleapis/synthtool/commit/6fab84af09f2cf89a031fd8671d1def6b2931b11 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:7cffbc10910c3ab1b852c05114a08d374c195a81cdec1d4a67a1d129331d0bfe Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 2 +- docs/conf.py | 5 +- .../services/language_service/async_client.py | 46 +- .../services/language_service/client.py | 87 +++- .../language_service/transports/base.py | 10 +- .../language_service/transports/grpc.py | 3 +- .../language_v1/types/language_service.py | 415 ++++++++++++++---- .../services/language_service/async_client.py | 46 +- .../services/language_service/client.py | 87 +++- .../language_service/transports/base.py | 10 +- .../language_service/transports/grpc.py | 3 +- .../types/language_service.py | 415 ++++++++++++++---- noxfile.py | 9 +- samples/snippets/api/analyze_test.py | 38 +- samples/snippets/api/noxfile.py | 4 +- .../classify_text/classify_text_tutorial.py | 8 +- samples/snippets/classify_text/noxfile.py | 4 +- samples/snippets/cloud-client/v1/noxfile.py | 4 +- .../snippets/cloud-client/v1/quickstart.py | 2 +- .../snippets/generated-samples/v1/noxfile.py | 4 +- samples/snippets/sentiment/noxfile.py | 4 +- .../language_v1/test_language_service.py | 233 +++++++--- .../language_v1beta2/test_language_service.py | 233 +++++++--- 23 files changed, 1307 insertions(+), 365 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 88076277..87dd0061 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:2d13c2172a5d6129c861edaa48b60ead15aeaf58aa75e02d870c4cbdfa63aaba + digest: sha256:7cffbc10910c3ab1b852c05114a08d374c195a81cdec1d4a67a1d129331d0bfe diff --git a/docs/conf.py b/docs/conf.py index e780d1a1..8296ba53 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -361,7 +361,10 @@ intersphinx_mapping = { "python": ("https://python.readthedocs.org/en/latest/", None), "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), + "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/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 33e58142..80cb5502 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -301,7 +301,12 @@ def sample_analyze_sentiment(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -407,7 +412,12 @@ def sample_analyze_entities(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -516,7 +526,12 @@ def sample_analyze_entity_sentiment(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -621,7 +636,12 @@ def sample_analyze_syntax(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -716,7 +736,12 @@ def sample_classify_text(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -833,7 +858,12 @@ def sample_annotate_text(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -847,7 +877,9 @@ async def __aexit__(self, exc_type, exc, tb): try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-language",).version, + gapic_version=pkg_resources.get_distribution( + "google-cloud-language", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 0942d7f2..a3a215e7 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -54,7 +54,10 @@ class LanguageServiceClientMeta(type): _transport_registry["grpc"] = LanguageServiceGrpcTransport _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport - def get_transport_class(cls, label: str = None,) -> Type[LanguageServiceTransport]: + def get_transport_class( + cls, + label: str = None, + ) -> Type[LanguageServiceTransport]: """Returns an appropriate transport class. Args: @@ -161,7 +164,9 @@ def transport(self) -> LanguageServiceTransport: return self._transport @staticmethod - def common_billing_account_path(billing_account: str,) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, @@ -174,9 +179,13 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str,) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder,) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: @@ -185,9 +194,13 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str,) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization,) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: @@ -196,9 +209,13 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str,) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project,) + return "projects/{project}".format( + project=project, + ) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: @@ -207,10 +224,14 @@ def parse_common_project_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str,) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( - project=project, location=location, + project=project, + location=location, ) @staticmethod @@ -474,7 +495,12 @@ def sample_analyze_sentiment(): rpc = self._transport._wrapped_methods[self._transport.analyze_sentiment] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -570,7 +596,12 @@ def sample_analyze_entities(): rpc = self._transport._wrapped_methods[self._transport.analyze_entities] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -669,7 +700,12 @@ def sample_analyze_entity_sentiment(): rpc = self._transport._wrapped_methods[self._transport.analyze_entity_sentiment] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -764,7 +800,12 @@ def sample_analyze_syntax(): rpc = self._transport._wrapped_methods[self._transport.analyze_syntax] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -849,7 +890,12 @@ def sample_classify_text(): rpc = self._transport._wrapped_methods[self._transport.classify_text] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -956,7 +1002,12 @@ def sample_annotate_text(): rpc = self._transport._wrapped_methods[self._transport.annotate_text] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -977,7 +1028,9 @@ def __exit__(self, type, value, traceback): try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-language",).version, + gapic_version=pkg_resources.get_distribution( + "google-cloud-language", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index b1f97f7a..67326655 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -29,7 +29,9 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-language",).version, + gapic_version=pkg_resources.get_distribution( + "google-cloud-language", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -216,9 +218,9 @@ def _prep_wrapped_messages(self, client_info): def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 86ea561d..31f4bc9d 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -225,8 +225,7 @@ def create_channel( @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 02fec89c..d26ac7a8 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -104,10 +104,25 @@ class Type(proto.Enum): PLAIN_TEXT = 1 HTML = 2 - type_ = proto.Field(proto.ENUM, number=1, enum=Type,) - content = proto.Field(proto.STRING, number=2, oneof="source",) - gcs_content_uri = proto.Field(proto.STRING, number=3, oneof="source",) - language = proto.Field(proto.STRING, number=4,) + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + content = proto.Field( + proto.STRING, + number=2, + oneof="source", + ) + gcs_content_uri = proto.Field( + proto.STRING, + number=3, + oneof="source", + ) + language = proto.Field( + proto.STRING, + number=4, + ) class Sentence(proto.Message): @@ -123,8 +138,16 @@ class Sentence(proto.Message): the sentence. """ - text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - sentiment = proto.Field(proto.MESSAGE, number=2, message="Sentiment",) + text = proto.Field( + proto.MESSAGE, + number=1, + message="TextSpan", + ) + sentiment = proto.Field( + proto.MESSAGE, + number=2, + message="Sentiment", + ) class Entity(proto.Message): @@ -184,12 +207,34 @@ class Type(proto.Enum): NUMBER = 12 PRICE = 13 - name = proto.Field(proto.STRING, number=1,) - type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - metadata = proto.MapField(proto.STRING, proto.STRING, number=3,) - salience = proto.Field(proto.FLOAT, number=4,) - mentions = proto.RepeatedField(proto.MESSAGE, number=5, message="EntityMention",) - sentiment = proto.Field(proto.MESSAGE, number=6, message="Sentiment",) + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + salience = proto.Field( + proto.FLOAT, + number=4, + ) + mentions = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="EntityMention", + ) + sentiment = proto.Field( + proto.MESSAGE, + number=6, + message="Sentiment", + ) class Token(proto.Message): @@ -207,10 +252,25 @@ class Token(proto.Message): of the token. """ - text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - part_of_speech = proto.Field(proto.MESSAGE, number=2, message="PartOfSpeech",) - dependency_edge = proto.Field(proto.MESSAGE, number=3, message="DependencyEdge",) - lemma = proto.Field(proto.STRING, number=4,) + text = proto.Field( + proto.MESSAGE, + number=1, + message="TextSpan", + ) + part_of_speech = proto.Field( + proto.MESSAGE, + number=2, + message="PartOfSpeech", + ) + dependency_edge = proto.Field( + proto.MESSAGE, + number=3, + message="DependencyEdge", + ) + lemma = proto.Field( + proto.STRING, + number=4, + ) class Sentiment(proto.Message): @@ -227,8 +287,14 @@ class Sentiment(proto.Message): sentiment) and 1.0 (positive sentiment). """ - magnitude = proto.Field(proto.FLOAT, number=2,) - score = proto.Field(proto.FLOAT, number=3,) + magnitude = proto.Field( + proto.FLOAT, + number=2, + ) + score = proto.Field( + proto.FLOAT, + number=3, + ) class PartOfSpeech(proto.Message): @@ -400,18 +466,66 @@ class Voice(proto.Enum): CAUSATIVE = 2 PASSIVE = 3 - tag = proto.Field(proto.ENUM, number=1, enum=Tag,) - aspect = proto.Field(proto.ENUM, number=2, enum=Aspect,) - case = proto.Field(proto.ENUM, number=3, enum=Case,) - form = proto.Field(proto.ENUM, number=4, enum=Form,) - gender = proto.Field(proto.ENUM, number=5, enum=Gender,) - mood = proto.Field(proto.ENUM, number=6, enum=Mood,) - number = proto.Field(proto.ENUM, number=7, enum=Number,) - person = proto.Field(proto.ENUM, number=8, enum=Person,) - proper = proto.Field(proto.ENUM, number=9, enum=Proper,) - reciprocity = proto.Field(proto.ENUM, number=10, enum=Reciprocity,) - tense = proto.Field(proto.ENUM, number=11, enum=Tense,) - voice = proto.Field(proto.ENUM, number=12, enum=Voice,) + tag = proto.Field( + proto.ENUM, + number=1, + enum=Tag, + ) + aspect = proto.Field( + proto.ENUM, + number=2, + enum=Aspect, + ) + case = proto.Field( + proto.ENUM, + number=3, + enum=Case, + ) + form = proto.Field( + proto.ENUM, + number=4, + enum=Form, + ) + gender = proto.Field( + proto.ENUM, + number=5, + enum=Gender, + ) + mood = proto.Field( + proto.ENUM, + number=6, + enum=Mood, + ) + number = proto.Field( + proto.ENUM, + number=7, + enum=Number, + ) + person = proto.Field( + proto.ENUM, + number=8, + enum=Person, + ) + proper = proto.Field( + proto.ENUM, + number=9, + enum=Proper, + ) + reciprocity = proto.Field( + proto.ENUM, + number=10, + enum=Reciprocity, + ) + tense = proto.Field( + proto.ENUM, + number=11, + enum=Tense, + ) + voice = proto.Field( + proto.ENUM, + number=12, + enum=Voice, + ) class DependencyEdge(proto.Message): @@ -517,8 +631,15 @@ class Label(proto.Enum): MES = 81 NCOMP = 82 - head_token_index = proto.Field(proto.INT32, number=1,) - label = proto.Field(proto.ENUM, number=2, enum=Label,) + head_token_index = proto.Field( + proto.INT32, + number=1, + ) + label = proto.Field( + proto.ENUM, + number=2, + enum=Label, + ) class EntityMention(proto.Message): @@ -544,9 +665,21 @@ class Type(proto.Enum): PROPER = 1 COMMON = 2 - text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - sentiment = proto.Field(proto.MESSAGE, number=3, message="Sentiment",) + text = proto.Field( + proto.MESSAGE, + number=1, + message="TextSpan", + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + sentiment = proto.Field( + proto.MESSAGE, + number=3, + message="Sentiment", + ) class TextSpan(proto.Message): @@ -562,8 +695,14 @@ class TextSpan(proto.Message): specified in the API request. """ - content = proto.Field(proto.STRING, number=1,) - begin_offset = proto.Field(proto.INT32, number=2,) + content = proto.Field( + proto.STRING, + number=1, + ) + begin_offset = proto.Field( + proto.INT32, + number=2, + ) class ClassificationCategory(proto.Message): @@ -580,8 +719,14 @@ class ClassificationCategory(proto.Message): that this category represents the given text. """ - name = proto.Field(proto.STRING, number=1,) - confidence = proto.Field(proto.FLOAT, number=2,) + name = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) class AnalyzeSentimentRequest(proto.Message): @@ -595,8 +740,16 @@ class AnalyzeSentimentRequest(proto.Message): calculate sentence offsets. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeSentimentResponse(proto.Message): @@ -616,9 +769,20 @@ class AnalyzeSentimentResponse(proto.Message): document. """ - document_sentiment = proto.Field(proto.MESSAGE, number=1, message="Sentiment",) - language = proto.Field(proto.STRING, number=2,) - sentences = proto.RepeatedField(proto.MESSAGE, number=3, message="Sentence",) + document_sentiment = proto.Field( + proto.MESSAGE, + number=1, + message="Sentiment", + ) + language = proto.Field( + proto.STRING, + number=2, + ) + sentences = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Sentence", + ) class AnalyzeEntitySentimentRequest(proto.Message): @@ -632,8 +796,16 @@ class AnalyzeEntitySentimentRequest(proto.Message): calculate offsets. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeEntitySentimentResponse(proto.Message): @@ -651,8 +823,15 @@ class AnalyzeEntitySentimentResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - language = proto.Field(proto.STRING, number=2,) + entities = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Entity", + ) + language = proto.Field( + proto.STRING, + number=2, + ) class AnalyzeEntitiesRequest(proto.Message): @@ -666,8 +845,16 @@ class AnalyzeEntitiesRequest(proto.Message): calculate offsets. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeEntitiesResponse(proto.Message): @@ -685,8 +872,15 @@ class AnalyzeEntitiesResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - language = proto.Field(proto.STRING, number=2,) + entities = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Entity", + ) + language = proto.Field( + proto.STRING, + number=2, + ) class AnalyzeSyntaxRequest(proto.Message): @@ -700,8 +894,16 @@ class AnalyzeSyntaxRequest(proto.Message): calculate offsets. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeSyntaxResponse(proto.Message): @@ -721,9 +923,20 @@ class AnalyzeSyntaxResponse(proto.Message): field for more details. """ - sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - language = proto.Field(proto.STRING, number=3,) + sentences = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Sentence", + ) + tokens = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Token", + ) + language = proto.Field( + proto.STRING, + number=3, + ) class ClassifyTextRequest(proto.Message): @@ -734,7 +947,11 @@ class ClassifyTextRequest(proto.Message): Input document. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) class ClassifyTextResponse(proto.Message): @@ -746,7 +963,9 @@ class ClassifyTextResponse(proto.Message): """ categories = proto.RepeatedField( - proto.MESSAGE, number=1, message="ClassificationCategory", + proto.MESSAGE, + number=1, + message="ClassificationCategory", ) @@ -784,15 +1003,42 @@ class Features(proto.Message): Classify the full document into categories. """ - extract_syntax = proto.Field(proto.BOOL, number=1,) - extract_entities = proto.Field(proto.BOOL, number=2,) - extract_document_sentiment = proto.Field(proto.BOOL, number=3,) - extract_entity_sentiment = proto.Field(proto.BOOL, number=4,) - classify_text = proto.Field(proto.BOOL, number=6,) - - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - features = proto.Field(proto.MESSAGE, number=2, message=Features,) - encoding_type = proto.Field(proto.ENUM, number=3, enum="EncodingType",) + extract_syntax = proto.Field( + proto.BOOL, + number=1, + ) + extract_entities = proto.Field( + proto.BOOL, + number=2, + ) + extract_document_sentiment = proto.Field( + proto.BOOL, + number=3, + ) + extract_entity_sentiment = proto.Field( + proto.BOOL, + number=4, + ) + classify_text = proto.Field( + proto.BOOL, + number=6, + ) + + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + features = proto.Field( + proto.MESSAGE, + number=2, + message=Features, + ) + encoding_type = proto.Field( + proto.ENUM, + number=3, + enum="EncodingType", + ) class AnnotateTextResponse(proto.Message): @@ -825,13 +1071,34 @@ class AnnotateTextResponse(proto.Message): Categories identified in the input document. """ - sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - entities = proto.RepeatedField(proto.MESSAGE, number=3, message="Entity",) - document_sentiment = proto.Field(proto.MESSAGE, number=4, message="Sentiment",) - language = proto.Field(proto.STRING, number=5,) + sentences = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Sentence", + ) + tokens = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Token", + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Entity", + ) + document_sentiment = proto.Field( + proto.MESSAGE, + number=4, + message="Sentiment", + ) + language = proto.Field( + proto.STRING, + number=5, + ) categories = proto.RepeatedField( - proto.MESSAGE, number=6, message="ClassificationCategory", + proto.MESSAGE, + number=6, + message="ClassificationCategory", ) diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 1a212bd5..6053c975 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -302,7 +302,12 @@ def sample_analyze_sentiment(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -408,7 +413,12 @@ def sample_analyze_entities(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -517,7 +527,12 @@ def sample_analyze_entity_sentiment(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -622,7 +637,12 @@ def sample_analyze_syntax(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -717,7 +737,12 @@ def sample_classify_text(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -834,7 +859,12 @@ def sample_annotate_text(): ) # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -848,7 +878,9 @@ async def __aexit__(self, exc_type, exc, tb): try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-language",).version, + gapic_version=pkg_resources.get_distribution( + "google-cloud-language", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 83cd0992..d4e44895 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -54,7 +54,10 @@ class LanguageServiceClientMeta(type): _transport_registry["grpc"] = LanguageServiceGrpcTransport _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport - def get_transport_class(cls, label: str = None,) -> Type[LanguageServiceTransport]: + def get_transport_class( + cls, + label: str = None, + ) -> Type[LanguageServiceTransport]: """Returns an appropriate transport class. Args: @@ -161,7 +164,9 @@ def transport(self) -> LanguageServiceTransport: return self._transport @staticmethod - def common_billing_account_path(billing_account: str,) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, @@ -174,9 +179,13 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str,) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder,) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: @@ -185,9 +194,13 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str,) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization,) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: @@ -196,9 +209,13 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str,) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project,) + return "projects/{project}".format( + project=project, + ) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: @@ -207,10 +224,14 @@ def parse_common_project_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str,) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( - project=project, location=location, + project=project, + location=location, ) @staticmethod @@ -475,7 +496,12 @@ def sample_analyze_sentiment(): rpc = self._transport._wrapped_methods[self._transport.analyze_sentiment] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -571,7 +597,12 @@ def sample_analyze_entities(): rpc = self._transport._wrapped_methods[self._transport.analyze_entities] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -670,7 +701,12 @@ def sample_analyze_entity_sentiment(): rpc = self._transport._wrapped_methods[self._transport.analyze_entity_sentiment] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -765,7 +801,12 @@ def sample_analyze_syntax(): rpc = self._transport._wrapped_methods[self._transport.analyze_syntax] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -850,7 +891,12 @@ def sample_classify_text(): rpc = self._transport._wrapped_methods[self._transport.classify_text] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -957,7 +1003,12 @@ def sample_annotate_text(): rpc = self._transport._wrapped_methods[self._transport.annotate_text] # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -978,7 +1029,9 @@ def __exit__(self, type, value, traceback): try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-language",).version, + gapic_version=pkg_resources.get_distribution( + "google-cloud-language", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index cc1fbc12..3c3de710 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -29,7 +29,9 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-language",).version, + gapic_version=pkg_resources.get_distribution( + "google-cloud-language", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -216,9 +218,9 @@ def _prep_wrapped_messages(self, client_info): def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index c09dea48..f5725f24 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -225,8 +225,7 @@ def create_channel( @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 3c168b58..fe526cb8 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -104,10 +104,25 @@ class Type(proto.Enum): PLAIN_TEXT = 1 HTML = 2 - type_ = proto.Field(proto.ENUM, number=1, enum=Type,) - content = proto.Field(proto.STRING, number=2, oneof="source",) - gcs_content_uri = proto.Field(proto.STRING, number=3, oneof="source",) - language = proto.Field(proto.STRING, number=4,) + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + content = proto.Field( + proto.STRING, + number=2, + oneof="source", + ) + gcs_content_uri = proto.Field( + proto.STRING, + number=3, + oneof="source", + ) + language = proto.Field( + proto.STRING, + number=4, + ) class Sentence(proto.Message): @@ -123,8 +138,16 @@ class Sentence(proto.Message): the sentence. """ - text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - sentiment = proto.Field(proto.MESSAGE, number=2, message="Sentiment",) + text = proto.Field( + proto.MESSAGE, + number=1, + message="TextSpan", + ) + sentiment = proto.Field( + proto.MESSAGE, + number=2, + message="Sentiment", + ) class Entity(proto.Message): @@ -184,12 +207,34 @@ class Type(proto.Enum): NUMBER = 12 PRICE = 13 - name = proto.Field(proto.STRING, number=1,) - type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - metadata = proto.MapField(proto.STRING, proto.STRING, number=3,) - salience = proto.Field(proto.FLOAT, number=4,) - mentions = proto.RepeatedField(proto.MESSAGE, number=5, message="EntityMention",) - sentiment = proto.Field(proto.MESSAGE, number=6, message="Sentiment",) + name = proto.Field( + proto.STRING, + number=1, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + metadata = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + salience = proto.Field( + proto.FLOAT, + number=4, + ) + mentions = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="EntityMention", + ) + sentiment = proto.Field( + proto.MESSAGE, + number=6, + message="Sentiment", + ) class Token(proto.Message): @@ -207,10 +252,25 @@ class Token(proto.Message): of the token. """ - text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - part_of_speech = proto.Field(proto.MESSAGE, number=2, message="PartOfSpeech",) - dependency_edge = proto.Field(proto.MESSAGE, number=3, message="DependencyEdge",) - lemma = proto.Field(proto.STRING, number=4,) + text = proto.Field( + proto.MESSAGE, + number=1, + message="TextSpan", + ) + part_of_speech = proto.Field( + proto.MESSAGE, + number=2, + message="PartOfSpeech", + ) + dependency_edge = proto.Field( + proto.MESSAGE, + number=3, + message="DependencyEdge", + ) + lemma = proto.Field( + proto.STRING, + number=4, + ) class Sentiment(proto.Message): @@ -228,8 +288,14 @@ class Sentiment(proto.Message): sentiment) and 1.0 (positive sentiment). """ - magnitude = proto.Field(proto.FLOAT, number=2,) - score = proto.Field(proto.FLOAT, number=3,) + magnitude = proto.Field( + proto.FLOAT, + number=2, + ) + score = proto.Field( + proto.FLOAT, + number=3, + ) class PartOfSpeech(proto.Message): @@ -399,18 +465,66 @@ class Voice(proto.Enum): CAUSATIVE = 2 PASSIVE = 3 - tag = proto.Field(proto.ENUM, number=1, enum=Tag,) - aspect = proto.Field(proto.ENUM, number=2, enum=Aspect,) - case = proto.Field(proto.ENUM, number=3, enum=Case,) - form = proto.Field(proto.ENUM, number=4, enum=Form,) - gender = proto.Field(proto.ENUM, number=5, enum=Gender,) - mood = proto.Field(proto.ENUM, number=6, enum=Mood,) - number = proto.Field(proto.ENUM, number=7, enum=Number,) - person = proto.Field(proto.ENUM, number=8, enum=Person,) - proper = proto.Field(proto.ENUM, number=9, enum=Proper,) - reciprocity = proto.Field(proto.ENUM, number=10, enum=Reciprocity,) - tense = proto.Field(proto.ENUM, number=11, enum=Tense,) - voice = proto.Field(proto.ENUM, number=12, enum=Voice,) + tag = proto.Field( + proto.ENUM, + number=1, + enum=Tag, + ) + aspect = proto.Field( + proto.ENUM, + number=2, + enum=Aspect, + ) + case = proto.Field( + proto.ENUM, + number=3, + enum=Case, + ) + form = proto.Field( + proto.ENUM, + number=4, + enum=Form, + ) + gender = proto.Field( + proto.ENUM, + number=5, + enum=Gender, + ) + mood = proto.Field( + proto.ENUM, + number=6, + enum=Mood, + ) + number = proto.Field( + proto.ENUM, + number=7, + enum=Number, + ) + person = proto.Field( + proto.ENUM, + number=8, + enum=Person, + ) + proper = proto.Field( + proto.ENUM, + number=9, + enum=Proper, + ) + reciprocity = proto.Field( + proto.ENUM, + number=10, + enum=Reciprocity, + ) + tense = proto.Field( + proto.ENUM, + number=11, + enum=Tense, + ) + voice = proto.Field( + proto.ENUM, + number=12, + enum=Voice, + ) class DependencyEdge(proto.Message): @@ -514,8 +628,15 @@ class Label(proto.Enum): MES = 81 NCOMP = 82 - head_token_index = proto.Field(proto.INT32, number=1,) - label = proto.Field(proto.ENUM, number=2, enum=Label,) + head_token_index = proto.Field( + proto.INT32, + number=1, + ) + label = proto.Field( + proto.ENUM, + number=2, + enum=Label, + ) class EntityMention(proto.Message): @@ -541,9 +662,21 @@ class Type(proto.Enum): PROPER = 1 COMMON = 2 - text = proto.Field(proto.MESSAGE, number=1, message="TextSpan",) - type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - sentiment = proto.Field(proto.MESSAGE, number=3, message="Sentiment",) + text = proto.Field( + proto.MESSAGE, + number=1, + message="TextSpan", + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + sentiment = proto.Field( + proto.MESSAGE, + number=3, + message="Sentiment", + ) class TextSpan(proto.Message): @@ -559,8 +692,14 @@ class TextSpan(proto.Message): specified in the API request. """ - content = proto.Field(proto.STRING, number=1,) - begin_offset = proto.Field(proto.INT32, number=2,) + content = proto.Field( + proto.STRING, + number=1, + ) + begin_offset = proto.Field( + proto.INT32, + number=2, + ) class ClassificationCategory(proto.Message): @@ -577,8 +716,14 @@ class ClassificationCategory(proto.Message): that this category represents the given text. """ - name = proto.Field(proto.STRING, number=1,) - confidence = proto.Field(proto.FLOAT, number=2,) + name = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) class AnalyzeSentimentRequest(proto.Message): @@ -593,8 +738,16 @@ class AnalyzeSentimentRequest(proto.Message): sentiment. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeSentimentResponse(proto.Message): @@ -614,9 +767,20 @@ class AnalyzeSentimentResponse(proto.Message): document. """ - document_sentiment = proto.Field(proto.MESSAGE, number=1, message="Sentiment",) - language = proto.Field(proto.STRING, number=2,) - sentences = proto.RepeatedField(proto.MESSAGE, number=3, message="Sentence",) + document_sentiment = proto.Field( + proto.MESSAGE, + number=1, + message="Sentiment", + ) + language = proto.Field( + proto.STRING, + number=2, + ) + sentences = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Sentence", + ) class AnalyzeEntitySentimentRequest(proto.Message): @@ -630,8 +794,16 @@ class AnalyzeEntitySentimentRequest(proto.Message): calculate offsets. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeEntitySentimentResponse(proto.Message): @@ -649,8 +821,15 @@ class AnalyzeEntitySentimentResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - language = proto.Field(proto.STRING, number=2,) + entities = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Entity", + ) + language = proto.Field( + proto.STRING, + number=2, + ) class AnalyzeEntitiesRequest(proto.Message): @@ -664,8 +843,16 @@ class AnalyzeEntitiesRequest(proto.Message): calculate offsets. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeEntitiesResponse(proto.Message): @@ -683,8 +870,15 @@ class AnalyzeEntitiesResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField(proto.MESSAGE, number=1, message="Entity",) - language = proto.Field(proto.STRING, number=2,) + entities = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Entity", + ) + language = proto.Field( + proto.STRING, + number=2, + ) class AnalyzeSyntaxRequest(proto.Message): @@ -698,8 +892,16 @@ class AnalyzeSyntaxRequest(proto.Message): calculate offsets. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - encoding_type = proto.Field(proto.ENUM, number=2, enum="EncodingType",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + encoding_type = proto.Field( + proto.ENUM, + number=2, + enum="EncodingType", + ) class AnalyzeSyntaxResponse(proto.Message): @@ -719,9 +921,20 @@ class AnalyzeSyntaxResponse(proto.Message): field for more details. """ - sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - language = proto.Field(proto.STRING, number=3,) + sentences = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Sentence", + ) + tokens = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Token", + ) + language = proto.Field( + proto.STRING, + number=3, + ) class ClassifyTextRequest(proto.Message): @@ -732,7 +945,11 @@ class ClassifyTextRequest(proto.Message): Required. Input document. """ - document = proto.Field(proto.MESSAGE, number=1, message="Document",) + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) class ClassifyTextResponse(proto.Message): @@ -744,7 +961,9 @@ class ClassifyTextResponse(proto.Message): """ categories = proto.RepeatedField( - proto.MESSAGE, number=1, message="ClassificationCategory", + proto.MESSAGE, + number=1, + message="ClassificationCategory", ) @@ -785,15 +1004,42 @@ class Features(proto.Message): taxonomy <https://cloud.google.com/natural-language/docs/categories>`__. """ - extract_syntax = proto.Field(proto.BOOL, number=1,) - extract_entities = proto.Field(proto.BOOL, number=2,) - extract_document_sentiment = proto.Field(proto.BOOL, number=3,) - extract_entity_sentiment = proto.Field(proto.BOOL, number=4,) - classify_text = proto.Field(proto.BOOL, number=6,) - - document = proto.Field(proto.MESSAGE, number=1, message="Document",) - features = proto.Field(proto.MESSAGE, number=2, message=Features,) - encoding_type = proto.Field(proto.ENUM, number=3, enum="EncodingType",) + extract_syntax = proto.Field( + proto.BOOL, + number=1, + ) + extract_entities = proto.Field( + proto.BOOL, + number=2, + ) + extract_document_sentiment = proto.Field( + proto.BOOL, + number=3, + ) + extract_entity_sentiment = proto.Field( + proto.BOOL, + number=4, + ) + classify_text = proto.Field( + proto.BOOL, + number=6, + ) + + document = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + features = proto.Field( + proto.MESSAGE, + number=2, + message=Features, + ) + encoding_type = proto.Field( + proto.ENUM, + number=3, + enum="EncodingType", + ) class AnnotateTextResponse(proto.Message): @@ -826,13 +1072,34 @@ class AnnotateTextResponse(proto.Message): Categories identified in the input document. """ - sentences = proto.RepeatedField(proto.MESSAGE, number=1, message="Sentence",) - tokens = proto.RepeatedField(proto.MESSAGE, number=2, message="Token",) - entities = proto.RepeatedField(proto.MESSAGE, number=3, message="Entity",) - document_sentiment = proto.Field(proto.MESSAGE, number=4, message="Sentiment",) - language = proto.Field(proto.STRING, number=5,) + sentences = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Sentence", + ) + tokens = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Token", + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Entity", + ) + document_sentiment = proto.Field( + proto.MESSAGE, + number=4, + message="Sentiment", + ) + language = proto.Field( + proto.STRING, + number=5, + ) categories = proto.RepeatedField( - proto.MESSAGE, number=6, message="ClassificationCategory", + proto.MESSAGE, + number=6, + message="ClassificationCategory", ) diff --git a/noxfile.py b/noxfile.py index 2a2001c4..3addb4ed 100644 --- a/noxfile.py +++ b/noxfile.py @@ -24,7 +24,7 @@ import nox -BLACK_VERSION = "black==19.10b0" +BLACK_VERSION = "black==22.3.0" BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" @@ -57,7 +57,9 @@ def lint(session): """ session.install("flake8", BLACK_VERSION) session.run( - "black", "--check", *BLACK_PATHS, + "black", + "--check", + *BLACK_PATHS, ) session.run("flake8", "google", "tests") @@ -67,7 +69,8 @@ def blacken(session): """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) session.run( - "black", *BLACK_PATHS, + "black", + *BLACK_PATHS, ) diff --git a/samples/snippets/api/analyze_test.py b/samples/snippets/api/analyze_test.py index c797e2e3..da5f0ab0 100644 --- a/samples/snippets/api/analyze_test.py +++ b/samples/snippets/api/analyze_test.py @@ -48,7 +48,7 @@ def test_analyze_sentiment(capsys): def test_analyze_syntax(capsys): result = analyze.analyze_syntax( textwrap.dedent( - u"""\ + """\ Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great. @@ -71,7 +71,7 @@ def test_analyze_syntax_utf8(): bits. The offsets we get should be the index of the first byte of the character. """ - test_string = u"a \u00e3 \u0201 \U0001f636 b" + test_string = "a \u00e3 \u0201 \U0001f636 b" byte_array = test_string.encode("utf8") result = analyze.analyze_syntax(test_string, encoding="UTF8") tokens = result["tokens"] @@ -82,19 +82,19 @@ def test_analyze_syntax_utf8(): byte_array[offset : offset + 1].decode("utf8") == tokens[0]["text"]["content"] ) - assert tokens[1]["text"]["content"] == u"\u00e3" + assert tokens[1]["text"]["content"] == "\u00e3" offset = tokens[1]["text"].get("beginOffset", 0) assert ( byte_array[offset : offset + 2].decode("utf8") == tokens[1]["text"]["content"] ) - assert tokens[2]["text"]["content"] == u"\u0201" + assert tokens[2]["text"]["content"] == "\u0201" offset = tokens[2]["text"].get("beginOffset", 0) assert ( byte_array[offset : offset + 2].decode("utf8") == tokens[2]["text"]["content"] ) - assert tokens[3]["text"]["content"] == u"\U0001f636" + assert tokens[3]["text"]["content"] == "\U0001f636" offset = tokens[3]["text"].get("beginOffset", 0) assert ( byte_array[offset : offset + 4].decode("utf8") == tokens[3]["text"]["content"] @@ -102,7 +102,7 @@ def test_analyze_syntax_utf8(): # This demonstrates that the offset takes into account the variable-length # characters before the target token. - assert tokens[4]["text"]["content"] == u"b" + assert tokens[4]["text"]["content"] == "b" offset = tokens[4]["text"].get("beginOffset", 0) # 'b' is only one byte long assert ( @@ -117,7 +117,7 @@ def test_analyze_syntax_utf16(): bits. The returned offsets will be the index of the first 2-byte character of the token. """ - test_string = u"a \u00e3 \u0201 \U0001f636 b" + test_string = "a \u00e3 \u0201 \U0001f636 b" byte_array = test_string.encode("utf16") # Remove the byte order marker, which the offsets don't account for byte_array = byte_array[2:] @@ -133,7 +133,7 @@ def test_analyze_syntax_utf16(): byte_array[offset : offset + 2].decode("utf16") == tokens[0]["text"]["content"] ) - assert tokens[1]["text"]["content"] == u"\u00e3" + assert tokens[1]["text"]["content"] == "\u00e3" offset = 2 * tokens[1]["text"].get("beginOffset", 0) # A UTF16 character with a low codepoint is 16 bits (2 bytes) long, so # slice out 2 bytes starting from the offset. Then interpret the bytes as @@ -142,7 +142,7 @@ def test_analyze_syntax_utf16(): byte_array[offset : offset + 2].decode("utf16") == tokens[1]["text"]["content"] ) - assert tokens[2]["text"]["content"] == u"\u0201" + assert tokens[2]["text"]["content"] == "\u0201" offset = 2 * tokens[2]["text"].get("beginOffset", 0) # A UTF16 character with a low codepoint is 16 bits (2 bytes) long, so # slice out 2 bytes starting from the offset. Then interpret the bytes as @@ -151,7 +151,7 @@ def test_analyze_syntax_utf16(): byte_array[offset : offset + 2].decode("utf16") == tokens[2]["text"]["content"] ) - assert tokens[3]["text"]["content"] == u"\U0001f636" + assert tokens[3]["text"]["content"] == "\U0001f636" offset = 2 * tokens[3]["text"].get("beginOffset", 0) # A UTF16 character with a high codepoint is 32 bits (4 bytes) long, so # slice out 4 bytes starting from the offset. Then interpret those bytes as @@ -162,7 +162,7 @@ def test_analyze_syntax_utf16(): # This demonstrates that the offset takes into account the variable-length # characters before the target token. - assert tokens[4]["text"]["content"] == u"b" + assert tokens[4]["text"]["content"] == "b" offset = 2 * tokens[4]["text"].get("beginOffset", 0) # Even though 'b' is only one byte long, utf16 still encodes it using 16 # bits @@ -192,7 +192,7 @@ def test_annotate_text_utf32(): unicode object with the raw offset returned by the api (ie without multiplying it by 4, as it is below). """ - test_string = u"a \u00e3 \u0201 \U0001f636 b" + test_string = "a \u00e3 \u0201 \U0001f636 b" byte_array = test_string.encode("utf32") # Remove the byte order marker, which the offsets don't account for byte_array = byte_array[4:] @@ -208,7 +208,7 @@ def test_annotate_text_utf32(): byte_array[offset : offset + 4].decode("utf32") == tokens[0]["text"]["content"] ) - assert tokens[1]["text"]["content"] == u"\u00e3" + assert tokens[1]["text"]["content"] == "\u00e3" offset = 4 * tokens[1]["text"].get("beginOffset", 0) # A UTF32 character with a low codepoint is 32 bits (4 bytes) long, so # slice out 4 bytes starting from the offset. Then interpret the bytes as @@ -217,7 +217,7 @@ def test_annotate_text_utf32(): byte_array[offset : offset + 4].decode("utf32") == tokens[1]["text"]["content"] ) - assert tokens[2]["text"]["content"] == u"\u0201" + assert tokens[2]["text"]["content"] == "\u0201" offset = 4 * tokens[2]["text"].get("beginOffset", 0) # A UTF32 character with a low codepoint is 32 bits (4 bytes) long, so # slice out 4 bytes starting from the offset. Then interpret the bytes as @@ -226,7 +226,7 @@ def test_annotate_text_utf32(): byte_array[offset : offset + 4].decode("utf32") == tokens[2]["text"]["content"] ) - assert tokens[3]["text"]["content"] == u"\U0001f636" + assert tokens[3]["text"]["content"] == "\U0001f636" offset = 4 * tokens[3]["text"].get("beginOffset", 0) # A UTF32 character with a high codepoint is 32 bits (4 bytes) long, so # slice out 4 bytes starting from the offset. Then interpret those bytes as @@ -237,7 +237,7 @@ def test_annotate_text_utf32(): # This demonstrates that the offset takes into account the variable-length # characters before the target token. - assert tokens[4]["text"]["content"] == u"b" + assert tokens[4]["text"]["content"] == "b" offset = 4 * tokens[4]["text"].get("beginOffset", 0) # Even though 'b' is only one byte long, utf32 still encodes it using 32 # bits @@ -252,7 +252,7 @@ def test_annotate_text_utf32_directly_index_into_unicode(): See the explanation for test_annotate_text_utf32. Essentially, indexing into a utf32 array is equivalent to indexing into a python unicode object. """ - test_string = u"a \u00e3 \u0201 \U0001f636 b" + test_string = "a \u00e3 \u0201 \U0001f636 b" result = analyze.analyze_syntax(test_string, encoding="UTF32") tokens = result["tokens"] @@ -260,11 +260,11 @@ def test_annotate_text_utf32_directly_index_into_unicode(): offset = tokens[0]["text"].get("beginOffset", 0) assert test_string[offset] == tokens[0]["text"]["content"] - assert tokens[1]["text"]["content"] == u"\u00e3" + assert tokens[1]["text"]["content"] == "\u00e3" offset = tokens[1]["text"].get("beginOffset", 0) assert test_string[offset] == tokens[1]["text"]["content"] - assert tokens[2]["text"]["content"] == u"\u0201" + assert tokens[2]["text"]["content"] == "\u0201" offset = tokens[2]["text"].get("beginOffset", 0) assert test_string[offset] == tokens[2]["text"]["content"] diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 85f5836d..25f87a21 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -29,7 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -BLACK_VERSION = "black==19.10b0" +BLACK_VERSION = "black==22.3.0" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -253,7 +253,7 @@ def py(session: nox.sessions.Session) -> None: def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ + """Returns the root folder of the project.""" # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) for i in range(10): diff --git a/samples/snippets/classify_text/classify_text_tutorial.py b/samples/snippets/classify_text/classify_text_tutorial.py index 675f8499..de35451d 100644 --- a/samples/snippets/classify_text/classify_text_tutorial.py +++ b/samples/snippets/classify_text/classify_text_tutorial.py @@ -35,7 +35,7 @@ # [START language_classify_text_tutorial_classify] def classify(text, verbose=True): - """Classify the input text into categories. """ + """Classify the input text into categories.""" language_client = language_v1.LanguageServiceClient() @@ -56,9 +56,9 @@ def classify(text, verbose=True): if verbose: print(text) for category in categories: - print(u"=" * 20) - print(u"{:<16}: {}".format("category", category.name)) - print(u"{:<16}: {}".format("confidence", category.confidence)) + print("=" * 20) + print("{:<16}: {}".format("category", category.name)) + print("{:<16}: {}".format("confidence", category.confidence)) return result diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 85f5836d..25f87a21 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -29,7 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -BLACK_VERSION = "black==19.10b0" +BLACK_VERSION = "black==22.3.0" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -253,7 +253,7 @@ def py(session: nox.sessions.Session) -> None: def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ + """Returns the root folder of the project.""" # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) for i in range(10): diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 85f5836d..25f87a21 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -29,7 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -BLACK_VERSION = "black==19.10b0" +BLACK_VERSION = "black==22.3.0" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -253,7 +253,7 @@ def py(session: nox.sessions.Session) -> None: def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ + """Returns the root folder of the project.""" # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) for i in range(10): diff --git a/samples/snippets/cloud-client/v1/quickstart.py b/samples/snippets/cloud-client/v1/quickstart.py index b9b0e96c..59c1cd43 100644 --- a/samples/snippets/cloud-client/v1/quickstart.py +++ b/samples/snippets/cloud-client/v1/quickstart.py @@ -29,7 +29,7 @@ def run_quickstart(): # [END language_python_migration_client] # The text to analyze - text = u"Hello, world!" + text = "Hello, world!" document = language_v1.Document( content=text, type_=language_v1.Document.Type.PLAIN_TEXT ) diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 85f5836d..25f87a21 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -29,7 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -BLACK_VERSION = "black==19.10b0" +BLACK_VERSION = "black==22.3.0" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -253,7 +253,7 @@ def py(session: nox.sessions.Session) -> None: def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ + """Returns the root folder of the project.""" # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) for i in range(10): diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 85f5836d..25f87a21 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -29,7 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING -BLACK_VERSION = "black==19.10b0" +BLACK_VERSION = "black==22.3.0" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -253,7 +253,7 @@ def py(session: nox.sessions.Session) -> None: def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ + """Returns the root folder of the project.""" # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) for i in range(10): diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 859fa443..d5ac0ac6 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -86,7 +86,11 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] + "client_class", + [ + LanguageServiceClient, + LanguageServiceAsyncClient, + ], ) def test_language_service_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() @@ -128,7 +132,11 @@ def test_language_service_client_service_account_always_use_jwt( @pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] + "client_class", + [ + LanguageServiceClient, + LanguageServiceAsyncClient, + ], ) def test_language_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -502,7 +510,9 @@ def test_language_service_client_client_options_scopes( client_class, transport_class, transport_name ): # Check the case scopes are provided. - options = client_options.ClientOptions(scopes=["1", "2"],) + options = client_options.ClientOptions( + scopes=["1", "2"], + ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) @@ -646,11 +656,16 @@ def test_language_service_client_create_channel_credentials_file( @pytest.mark.parametrize( - "request_type", [language_service.AnalyzeSentimentRequest, dict,] + "request_type", + [ + language_service.AnalyzeSentimentRequest, + dict, + ], ) def test_analyze_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -681,7 +696,8 @@ def test_analyze_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -700,7 +716,8 @@ async def test_analyze_sentiment_async( request_type=language_service.AnalyzeSentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -713,7 +730,9 @@ async def test_analyze_sentiment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSentimentResponse(language="language_value",) + language_service.AnalyzeSentimentResponse( + language="language_value", + ) ) response = await client.analyze_sentiment(request) @@ -733,7 +752,9 @@ async def test_analyze_sentiment_async_from_dict(): def test_analyze_sentiment_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -765,7 +786,9 @@ def test_analyze_sentiment_flattened(): def test_analyze_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -837,11 +860,16 @@ async def test_analyze_sentiment_flattened_error_async(): @pytest.mark.parametrize( - "request_type", [language_service.AnalyzeEntitiesRequest, dict,] + "request_type", + [ + language_service.AnalyzeEntitiesRequest, + dict, + ], ) def test_analyze_entities(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -870,7 +898,8 @@ def test_analyze_entities_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -887,7 +916,8 @@ async def test_analyze_entities_async( request_type=language_service.AnalyzeEntitiesRequest, ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -898,7 +928,9 @@ async def test_analyze_entities_async( with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitiesResponse(language="language_value",) + language_service.AnalyzeEntitiesResponse( + language="language_value", + ) ) response = await client.analyze_entities(request) @@ -918,7 +950,9 @@ async def test_analyze_entities_async_from_dict(): def test_analyze_entities_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: @@ -948,7 +982,9 @@ def test_analyze_entities_flattened(): def test_analyze_entities_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1018,11 +1054,16 @@ async def test_analyze_entities_flattened_error_async(): @pytest.mark.parametrize( - "request_type", [language_service.AnalyzeEntitySentimentRequest, dict,] + "request_type", + [ + language_service.AnalyzeEntitySentimentRequest, + dict, + ], ) def test_analyze_entity_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1053,7 +1094,8 @@ def test_analyze_entity_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1072,7 +1114,8 @@ async def test_analyze_entity_sentiment_async( request_type=language_service.AnalyzeEntitySentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1085,7 +1128,9 @@ async def test_analyze_entity_sentiment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitySentimentResponse(language="language_value",) + language_service.AnalyzeEntitySentimentResponse( + language="language_value", + ) ) response = await client.analyze_entity_sentiment(request) @@ -1105,7 +1150,9 @@ async def test_analyze_entity_sentiment_async_from_dict(): def test_analyze_entity_sentiment_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1137,7 +1184,9 @@ def test_analyze_entity_sentiment_flattened(): def test_analyze_entity_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1208,10 +1257,17 @@ async def test_analyze_entity_sentiment_flattened_error_async(): ) -@pytest.mark.parametrize("request_type", [language_service.AnalyzeSyntaxRequest, dict,]) +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeSyntaxRequest, + dict, + ], +) def test_analyze_syntax(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1240,7 +1296,8 @@ def test_analyze_syntax_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1256,7 +1313,8 @@ async def test_analyze_syntax_async( transport: str = "grpc_asyncio", request_type=language_service.AnalyzeSyntaxRequest ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1267,7 +1325,9 @@ async def test_analyze_syntax_async( with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSyntaxResponse(language="language_value",) + language_service.AnalyzeSyntaxResponse( + language="language_value", + ) ) response = await client.analyze_syntax(request) @@ -1287,7 +1347,9 @@ async def test_analyze_syntax_async_from_dict(): def test_analyze_syntax_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: @@ -1317,7 +1379,9 @@ def test_analyze_syntax_flattened(): def test_analyze_syntax_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1386,10 +1450,17 @@ async def test_analyze_syntax_flattened_error_async(): ) -@pytest.mark.parametrize("request_type", [language_service.ClassifyTextRequest, dict,]) +@pytest.mark.parametrize( + "request_type", + [ + language_service.ClassifyTextRequest, + dict, + ], +) def test_classify_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1415,7 +1486,8 @@ def test_classify_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1431,7 +1503,8 @@ async def test_classify_text_async( transport: str = "grpc_asyncio", request_type=language_service.ClassifyTextRequest ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1461,7 +1534,9 @@ async def test_classify_text_async_from_dict(): def test_classify_text_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.classify_text), "__call__") as call: @@ -1487,7 +1562,9 @@ def test_classify_text_flattened(): def test_classify_text_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1550,10 +1627,17 @@ async def test_classify_text_flattened_error_async(): ) -@pytest.mark.parametrize("request_type", [language_service.AnnotateTextRequest, dict,]) +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnnotateTextRequest, + dict, + ], +) def test_annotate_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1582,7 +1666,8 @@ def test_annotate_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1598,7 +1683,8 @@ async def test_annotate_text_async( transport: str = "grpc_asyncio", request_type=language_service.AnnotateTextRequest ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1609,7 +1695,9 @@ async def test_annotate_text_async( with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnnotateTextResponse(language="language_value",) + language_service.AnnotateTextResponse( + language="language_value", + ) ) response = await client.annotate_text(request) @@ -1629,7 +1717,9 @@ async def test_annotate_text_async_from_dict(): def test_annotate_text_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: @@ -1663,7 +1753,9 @@ def test_annotate_text_flattened(): def test_annotate_text_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1745,7 +1837,8 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -1765,7 +1858,10 @@ def test_credentials_transport_error(): options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): - client = LanguageServiceClient(client_options=options, transport=transport,) + client = LanguageServiceClient( + client_options=options, + transport=transport, + ) # It is an error to provide an api_key and a credential. options = mock.Mock() @@ -1781,7 +1877,8 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = LanguageServiceClient( - client_options={"scopes": ["1", "2"]}, transport=transport, + client_options={"scopes": ["1", "2"]}, + transport=transport, ) @@ -1826,8 +1923,13 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) - assert isinstance(client.transport, transports.LanguageServiceGrpcTransport,) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LanguageServiceGrpcTransport, + ) def test_language_service_base_transport_error(): @@ -1877,7 +1979,8 @@ def test_language_service_base_transport_with_credentials_file(): Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LanguageServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus", + credentials_file="credentials.json", + quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", @@ -2047,7 +2150,8 @@ def test_language_service_grpc_transport_channel(): # Check that channel is used if provided. transport = transports.LanguageServiceGrpcTransport( - host="squid.clam.whelk", channel=channel, + host="squid.clam.whelk", + channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2059,7 +2163,8 @@ def test_language_service_grpc_asyncio_transport_channel(): # Check that channel is used if provided. transport = transports.LanguageServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", channel=channel, + host="squid.clam.whelk", + channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2188,7 +2293,9 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) + expected = "folders/{folder}".format( + folder=folder, + ) actual = LanguageServiceClient.common_folder_path(folder) assert expected == actual @@ -2206,7 +2313,9 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = LanguageServiceClient.common_organization_path(organization) assert expected == actual @@ -2224,7 +2333,9 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) + expected = "projects/{project}".format( + project=project, + ) actual = LanguageServiceClient.common_project_path(project) assert expected == actual @@ -2244,7 +2355,8 @@ def test_common_location_path(): project = "winkle" location = "nautilus" expected = "projects/{project}/locations/{location}".format( - project=project, location=location, + project=project, + location=location, ) actual = LanguageServiceClient.common_location_path(project, location) assert expected == actual @@ -2269,7 +2381,8 @@ def test_client_with_default_client_info(): transports.LanguageServiceTransport, "_prep_wrapped_messages" ) as prep: client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2278,7 +2391,8 @@ def test_client_with_default_client_info(): ) as prep: transport_class = LanguageServiceClient.get_transport_class() transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2286,7 +2400,8 @@ def test_client_with_default_client_info(): @pytest.mark.asyncio async def test_transport_close_async(): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", ) with mock.patch.object( type(getattr(client.transport, "grpc_channel")), "close" diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 681ab4b3..89f8432a 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -88,7 +88,11 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] + "client_class", + [ + LanguageServiceClient, + LanguageServiceAsyncClient, + ], ) def test_language_service_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() @@ -130,7 +134,11 @@ def test_language_service_client_service_account_always_use_jwt( @pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient,] + "client_class", + [ + LanguageServiceClient, + LanguageServiceAsyncClient, + ], ) def test_language_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -504,7 +512,9 @@ def test_language_service_client_client_options_scopes( client_class, transport_class, transport_name ): # Check the case scopes are provided. - options = client_options.ClientOptions(scopes=["1", "2"],) + options = client_options.ClientOptions( + scopes=["1", "2"], + ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) @@ -648,11 +658,16 @@ def test_language_service_client_create_channel_credentials_file( @pytest.mark.parametrize( - "request_type", [language_service.AnalyzeSentimentRequest, dict,] + "request_type", + [ + language_service.AnalyzeSentimentRequest, + dict, + ], ) def test_analyze_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -683,7 +698,8 @@ def test_analyze_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -702,7 +718,8 @@ async def test_analyze_sentiment_async( request_type=language_service.AnalyzeSentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -715,7 +732,9 @@ async def test_analyze_sentiment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSentimentResponse(language="language_value",) + language_service.AnalyzeSentimentResponse( + language="language_value", + ) ) response = await client.analyze_sentiment(request) @@ -735,7 +754,9 @@ async def test_analyze_sentiment_async_from_dict(): def test_analyze_sentiment_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -767,7 +788,9 @@ def test_analyze_sentiment_flattened(): def test_analyze_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -839,11 +862,16 @@ async def test_analyze_sentiment_flattened_error_async(): @pytest.mark.parametrize( - "request_type", [language_service.AnalyzeEntitiesRequest, dict,] + "request_type", + [ + language_service.AnalyzeEntitiesRequest, + dict, + ], ) def test_analyze_entities(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -872,7 +900,8 @@ def test_analyze_entities_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -889,7 +918,8 @@ async def test_analyze_entities_async( request_type=language_service.AnalyzeEntitiesRequest, ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -900,7 +930,9 @@ async def test_analyze_entities_async( with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitiesResponse(language="language_value",) + language_service.AnalyzeEntitiesResponse( + language="language_value", + ) ) response = await client.analyze_entities(request) @@ -920,7 +952,9 @@ async def test_analyze_entities_async_from_dict(): def test_analyze_entities_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: @@ -950,7 +984,9 @@ def test_analyze_entities_flattened(): def test_analyze_entities_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1020,11 +1056,16 @@ async def test_analyze_entities_flattened_error_async(): @pytest.mark.parametrize( - "request_type", [language_service.AnalyzeEntitySentimentRequest, dict,] + "request_type", + [ + language_service.AnalyzeEntitySentimentRequest, + dict, + ], ) def test_analyze_entity_sentiment(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1055,7 +1096,8 @@ def test_analyze_entity_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1074,7 +1116,8 @@ async def test_analyze_entity_sentiment_async( request_type=language_service.AnalyzeEntitySentimentRequest, ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1087,7 +1130,9 @@ async def test_analyze_entity_sentiment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitySentimentResponse(language="language_value",) + language_service.AnalyzeEntitySentimentResponse( + language="language_value", + ) ) response = await client.analyze_entity_sentiment(request) @@ -1107,7 +1152,9 @@ async def test_analyze_entity_sentiment_async_from_dict(): def test_analyze_entity_sentiment_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1139,7 +1186,9 @@ def test_analyze_entity_sentiment_flattened(): def test_analyze_entity_sentiment_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1210,10 +1259,17 @@ async def test_analyze_entity_sentiment_flattened_error_async(): ) -@pytest.mark.parametrize("request_type", [language_service.AnalyzeSyntaxRequest, dict,]) +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeSyntaxRequest, + dict, + ], +) def test_analyze_syntax(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,7 +1298,8 @@ def test_analyze_syntax_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1258,7 +1315,8 @@ async def test_analyze_syntax_async( transport: str = "grpc_asyncio", request_type=language_service.AnalyzeSyntaxRequest ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1269,7 +1327,9 @@ async def test_analyze_syntax_async( with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSyntaxResponse(language="language_value",) + language_service.AnalyzeSyntaxResponse( + language="language_value", + ) ) response = await client.analyze_syntax(request) @@ -1289,7 +1349,9 @@ async def test_analyze_syntax_async_from_dict(): def test_analyze_syntax_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: @@ -1319,7 +1381,9 @@ def test_analyze_syntax_flattened(): def test_analyze_syntax_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1388,10 +1452,17 @@ async def test_analyze_syntax_flattened_error_async(): ) -@pytest.mark.parametrize("request_type", [language_service.ClassifyTextRequest, dict,]) +@pytest.mark.parametrize( + "request_type", + [ + language_service.ClassifyTextRequest, + dict, + ], +) def test_classify_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1417,7 +1488,8 @@ def test_classify_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1433,7 +1505,8 @@ async def test_classify_text_async( transport: str = "grpc_asyncio", request_type=language_service.ClassifyTextRequest ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1463,7 +1536,9 @@ async def test_classify_text_async_from_dict(): def test_classify_text_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.classify_text), "__call__") as call: @@ -1489,7 +1564,9 @@ def test_classify_text_flattened(): def test_classify_text_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1552,10 +1629,17 @@ async def test_classify_text_flattened_error_async(): ) -@pytest.mark.parametrize("request_type", [language_service.AnnotateTextRequest, dict,]) +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnnotateTextRequest, + dict, + ], +) def test_annotate_text(request_type, transport: str = "grpc"): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1584,7 +1668,8 @@ def test_annotate_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1600,7 +1685,8 @@ async def test_annotate_text_async( transport: str = "grpc_asyncio", request_type=language_service.AnnotateTextRequest ): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1611,7 +1697,9 @@ async def test_annotate_text_async( with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnnotateTextResponse(language="language_value",) + language_service.AnnotateTextResponse( + language="language_value", + ) ) response = await client.annotate_text(request) @@ -1631,7 +1719,9 @@ async def test_annotate_text_async_from_dict(): def test_annotate_text_flattened(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: @@ -1665,7 +1755,9 @@ def test_annotate_text_flattened(): def test_annotate_text_flattened_error(): - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1747,7 +1839,8 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -1767,7 +1860,10 @@ def test_credentials_transport_error(): options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): - client = LanguageServiceClient(client_options=options, transport=transport,) + client = LanguageServiceClient( + client_options=options, + transport=transport, + ) # It is an error to provide an api_key and a credential. options = mock.Mock() @@ -1783,7 +1879,8 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = LanguageServiceClient( - client_options={"scopes": ["1", "2"]}, transport=transport, + client_options={"scopes": ["1", "2"]}, + transport=transport, ) @@ -1828,8 +1925,13 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = LanguageServiceClient(credentials=ga_credentials.AnonymousCredentials(),) - assert isinstance(client.transport, transports.LanguageServiceGrpcTransport,) + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LanguageServiceGrpcTransport, + ) def test_language_service_base_transport_error(): @@ -1879,7 +1981,8 @@ def test_language_service_base_transport_with_credentials_file(): Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LanguageServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus", + credentials_file="credentials.json", + quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", @@ -2049,7 +2152,8 @@ def test_language_service_grpc_transport_channel(): # Check that channel is used if provided. transport = transports.LanguageServiceGrpcTransport( - host="squid.clam.whelk", channel=channel, + host="squid.clam.whelk", + channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2061,7 +2165,8 @@ def test_language_service_grpc_asyncio_transport_channel(): # Check that channel is used if provided. transport = transports.LanguageServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", channel=channel, + host="squid.clam.whelk", + channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -2190,7 +2295,9 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) + expected = "folders/{folder}".format( + folder=folder, + ) actual = LanguageServiceClient.common_folder_path(folder) assert expected == actual @@ -2208,7 +2315,9 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = LanguageServiceClient.common_organization_path(organization) assert expected == actual @@ -2226,7 +2335,9 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) + expected = "projects/{project}".format( + project=project, + ) actual = LanguageServiceClient.common_project_path(project) assert expected == actual @@ -2246,7 +2357,8 @@ def test_common_location_path(): project = "winkle" location = "nautilus" expected = "projects/{project}/locations/{location}".format( - project=project, location=location, + project=project, + location=location, ) actual = LanguageServiceClient.common_location_path(project, location) assert expected == actual @@ -2271,7 +2383,8 @@ def test_client_with_default_client_info(): transports.LanguageServiceTransport, "_prep_wrapped_messages" ) as prep: client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2280,7 +2393,8 @@ def test_client_with_default_client_info(): ) as prep: transport_class = LanguageServiceClient.get_transport_class() transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2288,7 +2402,8 @@ def test_client_with_default_client_info(): @pytest.mark.asyncio async def test_transport_close_async(): client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", ) with mock.patch.object( type(getattr(client.transport, "grpc_channel")), "close" From 83ae95aa1ab34feece9de7eb8efc8c79728ae9dd Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 30 Mar 2022 16:01:28 +0200 Subject: [PATCH 132/254] chore(deps): update all dependencies (#279) * chore(deps): update all dependencies * revert change for pinned version Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements-test.txt | 2 +- samples/snippets/api/requirements.txt | 4 ++-- samples/snippets/classify_text/requirements-test.txt | 2 +- samples/snippets/cloud-client/v1/requirements-test.txt | 2 +- samples/snippets/generated-samples/v1/requirements-test.txt | 2 +- samples/snippets/sentiment/requirements-test.txt | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt index c2845bff..4f6bf643 100644 --- a/samples/snippets/api/requirements-test.txt +++ b/samples/snippets/api/requirements-test.txt @@ -1 +1 @@ -pytest==7.0.1 +pytest==7.1.1 diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 616dfb22..e39a6af7 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.39.0 -google-auth==2.6.0 +google-api-python-client==2.42.0 +google-auth==2.6.2 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt index c2845bff..4f6bf643 100644 --- a/samples/snippets/classify_text/requirements-test.txt +++ b/samples/snippets/classify_text/requirements-test.txt @@ -1 +1 @@ -pytest==7.0.1 +pytest==7.1.1 diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt index c2845bff..4f6bf643 100644 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ b/samples/snippets/cloud-client/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.0.1 +pytest==7.1.1 diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt index c2845bff..4f6bf643 100644 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ b/samples/snippets/generated-samples/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.0.1 +pytest==7.1.1 diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt index c2845bff..4f6bf643 100644 --- a/samples/snippets/sentiment/requirements-test.txt +++ b/samples/snippets/sentiment/requirements-test.txt @@ -1 +1 @@ -pytest==7.0.1 +pytest==7.1.1 From 55f6ffa47f7f20e02d6355dce8ad3d955a5bc0f8 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 30 Mar 2022 16:43:15 +0200 Subject: [PATCH 133/254] chore: use === in requirements.txt for environment specific pins (#284) * chore(deps): update dependency numpy to v1.22.3 * chore: use === in requirements.txt for environment specific pins * revert version bump for environment specific pin Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/classify_text/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 1c28b1e2..dc049d13 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ google-cloud-language==2.4.1 numpy==1.22.3; python_version > '3.7' -numpy==1.21.4; python_version == '3.7' +numpy===1.21.4; python_version == '3.7' From c036500fa9485d5cc0be91ca1861205004d4435a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 30 Mar 2022 16:42:33 +0000 Subject: [PATCH 134/254] chore(python): add E231 to .flake8 ignore list (#285) Source-Link: https://github.com/googleapis/synthtool/commit/7ff4aad2ec5af0380e8bd6da1fa06eaadf24ec81 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:462782b0b492346b2d9099aaff52206dd30bc8e031ea97082e6facecc2373244 --- .flake8 | 2 +- .github/.OwlBot.lock.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.flake8 b/.flake8 index 29227d4c..2e438749 100644 --- a/.flake8 +++ b/.flake8 @@ -16,7 +16,7 @@ # Generated by synthtool. DO NOT EDIT! [flake8] -ignore = E203, E266, E501, W503 +ignore = E203, E231, E266, E501, W503 exclude = # Exclude generated code. **/proto/** diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 87dd0061..9e0a9356 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:7cffbc10910c3ab1b852c05114a08d374c195a81cdec1d4a67a1d129331d0bfe + digest: sha256:462782b0b492346b2d9099aaff52206dd30bc8e031ea97082e6facecc2373244 From 09812bc7c27d9d955410e667be9f0ee70e8a01f5 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 1 Apr 2022 00:12:14 +0000 Subject: [PATCH 135/254] chore(python): update .pre-commit-config.yaml to use black==22.3.0 (#286) Source-Link: https://github.com/googleapis/synthtool/commit/7804ade3daae0d66649bee8df6c55484c6580b8d Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:eede5672562a32821444a8e803fb984a6f61f2237ea3de229d2de24453f4ae7d --- .github/.OwlBot.lock.yaml | 3 ++- .pre-commit-config.yaml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 9e0a9356..22cc254a 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:462782b0b492346b2d9099aaff52206dd30bc8e031ea97082e6facecc2373244 + digest: sha256:eede5672562a32821444a8e803fb984a6f61f2237ea3de229d2de24453f4ae7d +# created: 2022-03-30T23:44:26.560599165Z diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 62eb5a77..46d23716 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -22,7 +22,7 @@ repos: - id: end-of-file-fixer - id: check-yaml - repo: https://github.com/psf/black - rev: 19.10b0 + rev: 22.3.0 hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 From cd891ebb82d86b2c452cd94a042a2d32ee36180d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 1 Apr 2022 02:04:24 +0000 Subject: [PATCH 136/254] chore(python): Enable size-label bot (#288) Source-Link: https://github.com/googleapis/synthtool/commit/06e82790dd719a165ad32b8a06f8f6ec3e3cae0f Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:b3500c053313dc34e07b1632ba9e4e589f4f77036a7cf39e1fe8906811ae0fce --- .github/.OwlBot.lock.yaml | 4 ++-- .github/auto-label.yaml | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 .github/auto-label.yaml diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 22cc254a..58a0b153 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:eede5672562a32821444a8e803fb984a6f61f2237ea3de229d2de24453f4ae7d -# created: 2022-03-30T23:44:26.560599165Z + digest: sha256:b3500c053313dc34e07b1632ba9e4e589f4f77036a7cf39e1fe8906811ae0fce +# created: 2022-04-01T01:42:03.609279246Z diff --git a/.github/auto-label.yaml b/.github/auto-label.yaml new file mode 100644 index 00000000..09c8d735 --- /dev/null +++ b/.github/auto-label.yaml @@ -0,0 +1,2 @@ +requestsize: + enabled: true From 8b57360d588aac751055ab8cb19057aaedcc3fdb Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 1 Apr 2022 19:34:10 +0000 Subject: [PATCH 137/254] chore(python): refactor unit / system test dependency install (#289) Source-Link: https://github.com/googleapis/synthtool/commit/993985f0fc4b37152e588f0549bcbdaf34666023 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:1894490910e891a385484514b22eb5133578897eb5b3c380e6d8ad475c6647cd --- .github/.OwlBot.lock.yaml | 4 +- noxfile.py | 105 ++++++++++++++++++++++++++++++-------- 2 files changed, 87 insertions(+), 22 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 58a0b153..fa576229 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:b3500c053313dc34e07b1632ba9e4e589f4f77036a7cf39e1fe8906811ae0fce -# created: 2022-04-01T01:42:03.609279246Z + digest: sha256:1894490910e891a385484514b22eb5133578897eb5b3c380e6d8ad475c6647cd +# created: 2022-04-01T15:48:07.524222836Z diff --git a/noxfile.py b/noxfile.py index 3addb4ed..6ee5e8ab 100644 --- a/noxfile.py +++ b/noxfile.py @@ -20,16 +20,40 @@ import os import pathlib import shutil +import warnings import nox - BLACK_VERSION = "black==22.3.0" BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] + UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES = [] +UNIT_TEST_LOCAL_DEPENDENCIES = [] +UNIT_TEST_DEPENDENCIES = [] +UNIT_TEST_EXTRAS = [] +UNIT_TEST_EXTRAS_BY_PYTHON = {} + +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES = [] +SYSTEM_TEST_DEPENDENCIES = [] +SYSTEM_TEST_EXTRAS = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON = {} CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() @@ -81,23 +105,41 @@ def lint_setup_py(session): session.run("python", "setup.py", "check", "--restructuredtext", "--strict") +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + def default(session): # Install all test dependencies, then install this package in-place. constraints_path = str( CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) - session.install( - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", - "-c", - constraints_path, - ) - - session.install("-e", ".", "-c", constraints_path) + install_unittest_dependencies(session, "-c", constraints_path) # Run py.test against the unit tests. session.run( @@ -121,6 +163,35 @@ def unit(session): default(session) +def install_systemtest_dependencies(session, *constraints): + + # Use pre-release gRPC for system tests. + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + @nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): """Run the system test suite.""" @@ -143,13 +214,7 @@ def system(session): if not system_test_exists and not system_test_folder_exists: session.skip("System tests were not found") - # Use pre-release gRPC for system tests. - session.install("--pre", "grpcio") - - # Install all test dependencies, then install this package into the - # virtualenv's dist-packages. - session.install("mock", "pytest", "google-cloud-testutils", "-c", constraints_path) - session.install("-e", ".", "-c", constraints_path) + install_systemtest_dependencies(session, "-c", constraints_path) # Run py.test against the system tests. if system_test_exists: From 89773ecc9b47c739a94c6b9a1cacfe0ada526a75 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 6 Apr 2022 13:02:46 +0200 Subject: [PATCH 138/254] chore(deps): update dependency google-api-python-client to v2.43.0 (#291) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index e39a6af7..4ba22b3f 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.42.0 +google-api-python-client==2.43.0 google-auth==2.6.2 google-auth-httplib2==0.1.0 From 80104a46d384120a7c35bf378c05ed5cb9d3943e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 6 Apr 2022 11:18:45 -0400 Subject: [PATCH 139/254] chore(python): add license header to auto-label.yaml (#293) Source-Link: https://github.com/googleapis/synthtool/commit/eb78c980b52c7c6746d2edb77d9cf7aaa99a2aab Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:8a5d3f6a2e43ed8293f34e06a2f56931d1e88a2694c3bb11b15df4eb256ad163 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 4 ++-- .github/auto-label.yaml | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index fa576229..bc893c97 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:1894490910e891a385484514b22eb5133578897eb5b3c380e6d8ad475c6647cd -# created: 2022-04-01T15:48:07.524222836Z + digest: sha256:8a5d3f6a2e43ed8293f34e06a2f56931d1e88a2694c3bb11b15df4eb256ad163 +# created: 2022-04-06T10:30:21.687684602Z diff --git a/.github/auto-label.yaml b/.github/auto-label.yaml index 09c8d735..41bff0b5 100644 --- a/.github/auto-label.yaml +++ b/.github/auto-label.yaml @@ -1,2 +1,15 @@ +# Copyright 2022 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. requestsize: enabled: true From aa514b546465fabbf8b9e02338a16b4348f51242 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Fri, 8 Apr 2022 01:13:27 +0200 Subject: [PATCH 140/254] chore(deps): update dependency google-auth to v2.6.3 (#296) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 4ba22b3f..6c83831d 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.43.0 -google-auth==2.6.2 +google-auth==2.6.3 google-auth-httplib2==0.1.0 From c73ef330e30cc82b700f99e33e5fa08aaf8c5f01 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 13 Apr 2022 00:48:11 +0200 Subject: [PATCH 141/254] chore(deps): update dependency google-api-python-client to v2.44.0 (#299) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 6c83831d..3b0e3602 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.43.0 +google-api-python-client==2.44.0 google-auth==2.6.3 google-auth-httplib2==0.1.0 From ac63ed78adabafeca852dc977518a6073db6d743 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 13 Apr 2022 01:28:46 +0200 Subject: [PATCH 142/254] chore(deps): update dependency google-auth to v2.6.4 (#300) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 3b0e3602..ab42a15e 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.44.0 -google-auth==2.6.3 +google-auth==2.6.4 google-auth-httplib2==0.1.0 From 41c28cd35b91adcbe3221a898419c323875b5cfd Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 13 Apr 2022 00:20:11 +0000 Subject: [PATCH 143/254] chore: Use gapic-generator-python 0.65.0 (#298) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 440970084 Source-Link: https://github.com/googleapis/googleapis/commit/5e0a3d57254ab9857ccac77fc6ffade7b69a2dc7 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b0c628a3fade768f225d76992791ea1ba2a881be Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjBjNjI4YTNmYWRlNzY4ZjIyNWQ3Njk5Mjc5MWVhMWJhMmE4ODFiZSJ9 docs: fix type in docstring for map fields --- .../services/language_service/async_client.py | 24 ++---- .../services/language_service/client.py | 6 +- .../language_service/transports/base.py | 23 +++--- .../language_service/transports/grpc.py | 4 + .../language_v1/types/language_service.py | 2 +- .../services/language_service/async_client.py | 24 ++---- .../services/language_service/client.py | 6 +- .../language_service/transports/base.py | 23 +++--- .../language_service/transports/grpc.py | 4 + .../types/language_service.py | 2 +- .../language_v1/test_language_service.py | 79 +++++++++++++++---- .../language_v1beta2/test_language_service.py | 79 +++++++++++++++---- 12 files changed, 172 insertions(+), 104 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 80cb5502..e12649a7 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import functools import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions @@ -291,8 +291,7 @@ def sample_analyze_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -326,7 +325,6 @@ async def analyze_entities( salience, mentions for each entity, and other properties. - .. code-block:: python from google.cloud import language_v1 @@ -402,8 +400,7 @@ def sample_analyze_entities(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -437,7 +434,6 @@ async def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. - .. code-block:: python from google.cloud import language_v1 @@ -516,8 +512,7 @@ def sample_analyze_entity_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -550,7 +545,6 @@ async def analyze_syntax( boundaries and tokenization along with part of speech tags, dependency trees, and other properties. - .. code-block:: python from google.cloud import language_v1 @@ -626,8 +620,7 @@ def sample_analyze_syntax(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -726,8 +719,7 @@ def sample_classify_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -761,7 +753,6 @@ async def annotate_text( that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call. - .. code-block:: python from google.cloud import language_v1 @@ -848,8 +839,7 @@ def sample_annotate_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index a3a215e7..a5173c34 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import os import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib @@ -520,7 +520,6 @@ def analyze_entities( salience, mentions for each entity, and other properties. - .. code-block:: python from google.cloud import language_v1 @@ -621,7 +620,6 @@ def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. - .. code-block:: python from google.cloud import language_v1 @@ -724,7 +722,6 @@ def analyze_syntax( boundaries and tokenization along with part of speech tags, dependency trees, and other properties. - .. code-block:: python from google.cloud import language_v1 @@ -915,7 +912,6 @@ def annotate_text( that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call. - .. code-block:: python from google.cloud import language_v1 diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 67326655..29a95fad 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -83,6 +83,7 @@ def __init__( always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" @@ -130,8 +131,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -145,8 +145,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -160,8 +159,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -175,8 +173,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -190,8 +187,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -205,8 +201,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -296,5 +291,9 @@ def annotate_text( ]: raise NotImplementedError() + @property + def kind(self) -> str: + raise NotImplementedError() + __all__ = ("LanguageServiceTransport",) diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 31f4bc9d..b7b421af 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -412,5 +412,9 @@ def annotate_text( def close(self): self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc" + __all__ = ("LanguageServiceGrpcTransport",) diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index d26ac7a8..eed340e3 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -160,7 +160,7 @@ class Entity(proto.Message): The representative name for the entity. type_ (google.cloud.language_v1.types.Entity.Type): The entity type. - metadata (Sequence[google.cloud.language_v1.types.Entity.MetadataEntry]): + metadata (Mapping[str, str]): Metadata associated with the entity. For most entity types, the metadata is a Wikipedia URL diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 6053c975..08757b5c 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import functools import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions @@ -292,8 +292,7 @@ def sample_analyze_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -327,7 +326,6 @@ async def analyze_entities( salience, mentions for each entity, and other properties. - .. code-block:: python from google.cloud import language_v1beta2 @@ -403,8 +401,7 @@ def sample_analyze_entities(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -438,7 +435,6 @@ async def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. - .. code-block:: python from google.cloud import language_v1beta2 @@ -517,8 +513,7 @@ def sample_analyze_entity_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -551,7 +546,6 @@ async def analyze_syntax( boundaries and tokenization along with part-of-speech tags, dependency trees, and other properties. - .. code-block:: python from google.cloud import language_v1beta2 @@ -627,8 +621,7 @@ def sample_analyze_syntax(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -727,8 +720,7 @@ def sample_classify_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -762,7 +754,6 @@ async def annotate_text( sentiment, entity, and classification features in one call. - .. code-block:: python from google.cloud import language_v1beta2 @@ -849,8 +840,7 @@ def sample_annotate_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index d4e44895..ac1049b9 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import os import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib @@ -521,7 +521,6 @@ def analyze_entities( salience, mentions for each entity, and other properties. - .. code-block:: python from google.cloud import language_v1beta2 @@ -622,7 +621,6 @@ def analyze_entity_sentiment( in the text and analyzes sentiment associated with each entity and its mentions. - .. code-block:: python from google.cloud import language_v1beta2 @@ -725,7 +723,6 @@ def analyze_syntax( boundaries and tokenization along with part-of-speech tags, dependency trees, and other properties. - .. code-block:: python from google.cloud import language_v1beta2 @@ -916,7 +913,6 @@ def annotate_text( sentiment, entity, and classification features in one call. - .. code-block:: python from google.cloud import language_v1beta2 diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 3c3de710..278b65df 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -83,6 +83,7 @@ def __init__( always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" @@ -130,8 +131,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -145,8 +145,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -160,8 +159,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -175,8 +173,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -190,8 +187,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -205,8 +201,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, + core_exceptions.GoogleAPICallError, ), deadline=600.0, ), @@ -296,5 +291,9 @@ def annotate_text( ]: raise NotImplementedError() + @property + def kind(self) -> str: + raise NotImplementedError() + __all__ = ("LanguageServiceTransport",) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index f5725f24..c6b1b540 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -412,5 +412,9 @@ def annotate_text( def close(self): self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc" + __all__ = ("LanguageServiceGrpcTransport",) diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index fe526cb8..194002bc 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -160,7 +160,7 @@ class Entity(proto.Message): The representative name for the entity. type_ (google.cloud.language_v1beta2.types.Entity.Type): The entity type. - metadata (Sequence[google.cloud.language_v1beta2.types.Entity.MetadataEntry]): + metadata (Mapping[str, str]): Metadata associated with the entity. For most entity types, the metadata is a Wikipedia URL diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index d5ac0ac6..08447420 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -86,24 +86,26 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", + "client_class,transport_name", [ - LanguageServiceClient, - LanguageServiceAsyncClient, + (LanguageServiceClient, "grpc"), + (LanguageServiceAsyncClient, "grpc_asyncio"), ], ) -def test_language_service_client_from_service_account_info(client_class): +def test_language_service_client_from_service_account_info( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} - client = client_class.from_service_account_info(info) + client = client_class.from_service_account_info(info, transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == "language.googleapis.com:443" + assert client.transport._host == ("language.googleapis.com:443") @pytest.mark.parametrize( @@ -132,27 +134,33 @@ def test_language_service_client_service_account_always_use_jwt( @pytest.mark.parametrize( - "client_class", + "client_class,transport_name", [ - LanguageServiceClient, - LanguageServiceAsyncClient, + (LanguageServiceClient, "grpc"), + (LanguageServiceAsyncClient, "grpc_asyncio"), ], ) -def test_language_service_client_from_service_account_file(client_class): +def test_language_service_client_from_service_account_file( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json("dummy/file/path.json") + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == "language.googleapis.com:443" + assert client.transport._host == ("language.googleapis.com:443") def test_language_service_client_get_transport_class(): @@ -1921,6 +1929,19 @@ def test_transport_adc(transport_class): adc.assert_called_once() +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) +def test_transport_kind(transport_name): + transport = LanguageServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = LanguageServiceClient( @@ -1968,6 +1989,14 @@ def test_language_service_base_transport(): with pytest.raises(NotImplementedError): transport.close() + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + def test_language_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file @@ -2125,24 +2154,40 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c ) -def test_language_service_host_no_port(): +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_language_service_host_no_port(transport_name): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com" ), + transport=transport_name, ) - assert client.transport._host == "language.googleapis.com:443" + assert client.transport._host == ("language.googleapis.com:443") -def test_language_service_host_with_port(): +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_language_service_host_with_port(transport_name): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com:8000" ), + transport=transport_name, ) - assert client.transport._host == "language.googleapis.com:8000" + assert client.transport._host == ("language.googleapis.com:8000") def test_language_service_grpc_transport_channel(): diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 89f8432a..6603d4a3 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -88,24 +88,26 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", + "client_class,transport_name", [ - LanguageServiceClient, - LanguageServiceAsyncClient, + (LanguageServiceClient, "grpc"), + (LanguageServiceAsyncClient, "grpc_asyncio"), ], ) -def test_language_service_client_from_service_account_info(client_class): +def test_language_service_client_from_service_account_info( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} - client = client_class.from_service_account_info(info) + client = client_class.from_service_account_info(info, transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == "language.googleapis.com:443" + assert client.transport._host == ("language.googleapis.com:443") @pytest.mark.parametrize( @@ -134,27 +136,33 @@ def test_language_service_client_service_account_always_use_jwt( @pytest.mark.parametrize( - "client_class", + "client_class,transport_name", [ - LanguageServiceClient, - LanguageServiceAsyncClient, + (LanguageServiceClient, "grpc"), + (LanguageServiceAsyncClient, "grpc_asyncio"), ], ) -def test_language_service_client_from_service_account_file(client_class): +def test_language_service_client_from_service_account_file( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json("dummy/file/path.json") + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == "language.googleapis.com:443" + assert client.transport._host == ("language.googleapis.com:443") def test_language_service_client_get_transport_class(): @@ -1923,6 +1931,19 @@ def test_transport_adc(transport_class): adc.assert_called_once() +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) +def test_transport_kind(transport_name): + transport = LanguageServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = LanguageServiceClient( @@ -1970,6 +1991,14 @@ def test_language_service_base_transport(): with pytest.raises(NotImplementedError): transport.close() + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + def test_language_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file @@ -2127,24 +2156,40 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c ) -def test_language_service_host_no_port(): +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_language_service_host_no_port(transport_name): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com" ), + transport=transport_name, ) - assert client.transport._host == "language.googleapis.com:443" + assert client.transport._host == ("language.googleapis.com:443") -def test_language_service_host_with_port(): +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_language_service_host_with_port(transport_name): client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="language.googleapis.com:8000" ), + transport=transport_name, ) - assert client.transport._host == "language.googleapis.com:8000" + assert client.transport._host == ("language.googleapis.com:8000") def test_language_service_grpc_transport_channel(): From 7719e96d8d2ee0bed1c8f7ca545174aa855e3ab2 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 14 Apr 2022 07:43:12 -0400 Subject: [PATCH 144/254] chore: use gapic-generator-python 0.65.1 (#302) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: use gapic-generator-python 0.65.1 PiperOrigin-RevId: 441524537 Source-Link: https://github.com/googleapis/googleapis/commit/2a273915b3f70fe86c9d2a75470a0b83e48d0abf Source-Link: https://github.com/googleapis/googleapis-gen/commit/ab6756a48c89b5bcb9fb73443cb8e55d574f4643 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYWI2NzU2YTQ4Yzg5YjViY2I5ZmI3MzQ0M2NiOGU1NWQ1NzRmNDY0MyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../services/language_service/async_client.py | 18 +- .../language_service/transports/base.py | 18 +- .../services/language_service/async_client.py | 18 +- .../language_service/transports/base.py | 18 +- .../snippet_metadata_language_v1.json | 538 +++++++++++++++++- .../snippet_metadata_language_v1beta2.json | 538 +++++++++++++++++- 6 files changed, 1076 insertions(+), 72 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index e12649a7..96784158 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -291,7 +291,8 @@ def sample_analyze_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -400,7 +401,8 @@ def sample_analyze_entities(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -512,7 +514,8 @@ def sample_analyze_entity_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -620,7 +623,8 @@ def sample_analyze_syntax(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -719,7 +723,8 @@ def sample_classify_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -839,7 +844,8 @@ def sample_annotate_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 29a95fad..65c3cae2 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -131,7 +131,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -145,7 +146,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -159,7 +161,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -173,7 +176,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -187,7 +191,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -201,7 +206,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 08757b5c..f20561ed 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -292,7 +292,8 @@ def sample_analyze_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -401,7 +402,8 @@ def sample_analyze_entities(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -513,7 +515,8 @@ def sample_analyze_entity_sentiment(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -621,7 +624,8 @@ def sample_analyze_syntax(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -720,7 +724,8 @@ def sample_classify_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -840,7 +845,8 @@ def sample_annotate_text(): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 278b65df..dd29d40a 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -131,7 +131,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -145,7 +146,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -159,7 +161,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -173,7 +176,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -187,7 +191,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -201,7 +206,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.GoogleAPICallError, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/samples/generated_samples/snippet_metadata_language_v1.json b/samples/generated_samples/snippet_metadata_language_v1.json index ad0df512..c1e4dd61 100644 --- a/samples/generated_samples/snippet_metadata_language_v1.json +++ b/samples/generated_samples/snippet_metadata_language_v1.json @@ -1,16 +1,65 @@ { + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.language.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-language" + }, "snippets": [ { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_entities", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntities", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntities" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeEntitiesRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeEntitiesResponse", + "shortName": "analyze_entities" }, + "description": "Sample for AnalyzeEntities", "file": "language_v1_generated_language_service_analyze_entities_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_async", "segments": [ { @@ -43,18 +92,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_entities_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_entities", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntities", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntities" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeEntitiesRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeEntitiesResponse", + "shortName": "analyze_entities" }, + "description": "Sample for AnalyzeEntities", "file": "language_v1_generated_language_service_analyze_entities_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_sync", "segments": [ { @@ -87,19 +176,59 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_entities_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_entity_sentiment", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntitySentiment", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntitySentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeEntitySentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeEntitySentimentResponse", + "shortName": "analyze_entity_sentiment" }, + "description": "Sample for AnalyzeEntitySentiment", "file": "language_v1_generated_language_service_analyze_entity_sentiment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_async", "segments": [ { @@ -132,18 +261,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_entity_sentiment_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_entity_sentiment", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntitySentiment", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntitySentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeEntitySentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeEntitySentimentResponse", + "shortName": "analyze_entity_sentiment" }, + "description": "Sample for AnalyzeEntitySentiment", "file": "language_v1_generated_language_service_analyze_entity_sentiment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync", "segments": [ { @@ -176,19 +345,59 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_entity_sentiment_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_sentiment", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSentiment", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeSentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeSentimentResponse", + "shortName": "analyze_sentiment" }, + "description": "Sample for AnalyzeSentiment", "file": "language_v1_generated_language_service_analyze_sentiment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_async", "segments": [ { @@ -221,18 +430,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_sentiment_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_sentiment", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSentiment", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeSentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeSentimentResponse", + "shortName": "analyze_sentiment" }, + "description": "Sample for AnalyzeSentiment", "file": "language_v1_generated_language_service_analyze_sentiment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_sync", "segments": [ { @@ -265,19 +514,59 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_sentiment_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_syntax", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSyntax", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSyntax" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeSyntaxRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeSyntaxResponse", + "shortName": "analyze_syntax" }, + "description": "Sample for AnalyzeSyntax", "file": "language_v1_generated_language_service_analyze_syntax_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_async", "segments": [ { @@ -310,18 +599,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_syntax_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_syntax", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSyntax", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSyntax" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnalyzeSyntaxRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnalyzeSyntaxResponse", + "shortName": "analyze_syntax" }, + "description": "Sample for AnalyzeSyntax", "file": "language_v1_generated_language_service_analyze_syntax_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_sync", "segments": [ { @@ -354,19 +683,63 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_analyze_syntax_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.annotate_text", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnnotateText", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnnotateText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnnotateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "features", + "type": "google.cloud.language_v1.types.AnnotateTextRequest.Features" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnnotateTextResponse", + "shortName": "annotate_text" }, + "description": "Sample for AnnotateText", "file": "language_v1_generated_language_service_annotate_text_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnnotateText_async", "segments": [ { @@ -399,18 +772,62 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_annotate_text_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceClient.annotate_text", "method": { + "fullName": "google.cloud.language.v1.LanguageService.AnnotateText", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "AnnotateText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.AnnotateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "features", + "type": "google.cloud.language_v1.types.AnnotateTextRequest.Features" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.AnnotateTextResponse", + "shortName": "annotate_text" }, + "description": "Sample for AnnotateText", "file": "language_v1_generated_language_service_annotate_text_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_AnnotateText_sync", "segments": [ { @@ -443,19 +860,55 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_annotate_text_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.classify_text", "method": { + "fullName": "google.cloud.language.v1.LanguageService.ClassifyText", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "ClassifyText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.ClassifyTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.ClassifyTextResponse", + "shortName": "classify_text" }, + "description": "Sample for ClassifyText", "file": "language_v1_generated_language_service_classify_text_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_ClassifyText_async", "segments": [ { @@ -488,18 +941,54 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_classify_text_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceClient.classify_text", "method": { + "fullName": "google.cloud.language.v1.LanguageService.ClassifyText", "service": { + "fullName": "google.cloud.language.v1.LanguageService", "shortName": "LanguageService" }, "shortName": "ClassifyText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.ClassifyTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.ClassifyTextResponse", + "shortName": "classify_text" }, + "description": "Sample for ClassifyText", "file": "language_v1_generated_language_service_classify_text_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1_generated_LanguageService_ClassifyText_sync", "segments": [ { @@ -532,7 +1021,8 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1_generated_language_service_classify_text_sync.py" } ] } diff --git a/samples/generated_samples/snippet_metadata_language_v1beta2.json b/samples/generated_samples/snippet_metadata_language_v1beta2.json index 68415e8e..bf3a59ca 100644 --- a/samples/generated_samples/snippet_metadata_language_v1beta2.json +++ b/samples/generated_samples/snippet_metadata_language_v1beta2.json @@ -1,16 +1,65 @@ { + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.language.v1beta2", + "version": "v1beta2" + } + ], + "language": "PYTHON", + "name": "google-cloud-language" + }, "snippets": [ { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_entities", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntities", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntities" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitiesResponse", + "shortName": "analyze_entities" }, + "description": "Sample for AnalyzeEntities", "file": "language_v1beta2_generated_language_service_analyze_entities_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_async", "segments": [ { @@ -43,18 +92,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_entities_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_entities", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntities", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntities" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitiesResponse", + "shortName": "analyze_entities" }, + "description": "Sample for AnalyzeEntities", "file": "language_v1beta2_generated_language_service_analyze_entities_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_sync", "segments": [ { @@ -87,19 +176,59 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_entities_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_entity_sentiment", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntitySentiment", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntitySentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentResponse", + "shortName": "analyze_entity_sentiment" }, + "description": "Sample for AnalyzeEntitySentiment", "file": "language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async", "segments": [ { @@ -132,18 +261,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_entity_sentiment", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntitySentiment", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeEntitySentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentResponse", + "shortName": "analyze_entity_sentiment" }, + "description": "Sample for AnalyzeEntitySentiment", "file": "language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync", "segments": [ { @@ -176,19 +345,59 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_sentiment", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSentiment", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeSentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeSentimentResponse", + "shortName": "analyze_sentiment" }, + "description": "Sample for AnalyzeSentiment", "file": "language_v1beta2_generated_language_service_analyze_sentiment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_async", "segments": [ { @@ -221,18 +430,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_sentiment_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_sentiment", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSentiment", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSentiment" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeSentimentRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeSentimentResponse", + "shortName": "analyze_sentiment" }, + "description": "Sample for AnalyzeSentiment", "file": "language_v1beta2_generated_language_service_analyze_sentiment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync", "segments": [ { @@ -265,19 +514,59 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_sentiment_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_syntax", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSyntax", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSyntax" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeSyntaxResponse", + "shortName": "analyze_syntax" }, + "description": "Sample for AnalyzeSyntax", "file": "language_v1beta2_generated_language_service_analyze_syntax_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_async", "segments": [ { @@ -310,18 +599,58 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_syntax_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_syntax", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSyntax", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnalyzeSyntax" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnalyzeSyntaxResponse", + "shortName": "analyze_syntax" }, + "description": "Sample for AnalyzeSyntax", "file": "language_v1beta2_generated_language_service_analyze_syntax_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync", "segments": [ { @@ -354,19 +683,63 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_analyze_syntax_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.annotate_text", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnnotateText", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnnotateText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "features", + "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest.Features" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnnotateTextResponse", + "shortName": "annotate_text" }, + "description": "Sample for AnnotateText", "file": "language_v1beta2_generated_language_service_annotate_text_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_async", "segments": [ { @@ -399,18 +772,62 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_annotate_text_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.annotate_text", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.AnnotateText", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "AnnotateText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "features", + "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest.Features" + }, + { + "name": "encoding_type", + "type": "google.cloud.language_v1beta2.types.EncodingType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.AnnotateTextResponse", + "shortName": "annotate_text" }, + "description": "Sample for AnnotateText", "file": "language_v1beta2_generated_language_service_annotate_text_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_sync", "segments": [ { @@ -443,19 +860,55 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_annotate_text_sync.py" }, { + "canonical": true, "clientMethod": { "async": true, + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.classify_text", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.ClassifyText", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "ClassifyText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.ClassifyTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.ClassifyTextResponse", + "shortName": "classify_text" }, + "description": "Sample for ClassifyText", "file": "language_v1beta2_generated_language_service_classify_text_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_async", "segments": [ { @@ -488,18 +941,54 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_classify_text_async.py" }, { + "canonical": true, "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.classify_text", "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.ClassifyText", "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", "shortName": "LanguageService" }, "shortName": "ClassifyText" - } + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.ClassifyTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.ClassifyTextResponse", + "shortName": "classify_text" }, + "description": "Sample for ClassifyText", "file": "language_v1beta2_generated_language_service_classify_text_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_sync", "segments": [ { @@ -532,7 +1021,8 @@ "start": 45, "type": "RESPONSE_HANDLING" } - ] + ], + "title": "language_v1beta2_generated_language_service_classify_text_sync.py" } ] } From 37be36fdfa49a41a4ba2993dcd507980a4c1d098 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Fri, 15 Apr 2022 02:45:14 +0200 Subject: [PATCH 145/254] chore(deps): update dependency google-auth to v2.6.5 (#303) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index ab42a15e..13fd78ce 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.44.0 -google-auth==2.6.4 +google-auth==2.6.5 google-auth-httplib2==0.1.0 From c605af68b349e50ef4a33854a8280f967453a085 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 19 Apr 2022 16:59:43 +0200 Subject: [PATCH 146/254] chore(deps): update dependency google-api-python-client to v2.45.0 (#304) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 13fd78ce..665a8c67 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.44.0 +google-api-python-client==2.45.0 google-auth==2.6.5 google-auth-httplib2==0.1.0 From 680ba3c47350419774ebbdf539ba9ec0bd0cb623 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 20 Apr 2022 21:28:28 -0400 Subject: [PATCH 147/254] chore(python): add nox session to sort python imports (#305) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(python): add nox session to sort python imports Source-Link: https://github.com/googleapis/synthtool/commit/1b71c10e20de7ed3f97f692f99a0e3399b67049f Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:00c9d764fd1cd56265f12a5ef4b99a0c9e87cf261018099141e2ca5158890416 * revert change to region tag * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 4 +- docs/conf.py | 2 +- google/cloud/language/__init__.py | 51 +++++++++--------- google/cloud/language_v1/__init__.py | 52 +++++++++---------- .../services/language_service/__init__.py | 2 +- .../services/language_service/async_client.py | 9 ++-- .../services/language_service/client.py | 7 +-- .../language_service/transports/__init__.py | 1 - .../language_service/transports/base.py | 4 +- .../language_service/transports/grpc.py | 9 ++-- .../transports/grpc_asyncio.py | 9 ++-- google/cloud/language_v1/types/__init__.py | 2 +- .../language_v1/types/language_service.py | 1 - google/cloud/language_v1beta2/__init__.py | 52 +++++++++---------- .../services/language_service/__init__.py | 2 +- .../services/language_service/async_client.py | 9 ++-- .../services/language_service/client.py | 7 +-- .../language_service/transports/__init__.py | 1 - .../language_service/transports/base.py | 4 +- .../language_service/transports/grpc.py | 9 ++-- .../transports/grpc_asyncio.py | 9 ++-- .../cloud/language_v1beta2/types/__init__.py | 2 +- .../types/language_service.py | 1 - noxfile.py | 28 ++++++++-- samples/snippets/api/noxfile.py | 23 +++++++- .../classify_text_tutorial_test.py | 1 - samples/snippets/classify_text/noxfile.py | 23 +++++++- samples/snippets/cloud-client/v1/noxfile.py | 23 +++++++- .../snippets/cloud-client/v1/quickstart.py | 1 - .../v1/language_sentiment_text.py | 1 + .../snippets/generated-samples/v1/noxfile.py | 23 +++++++- samples/snippets/sentiment/noxfile.py | 23 +++++++- setup.py | 1 - .../language_v1/test_language_service.py | 28 +++++----- .../language_v1beta2/test_language_service.py | 28 ++++------ 35 files changed, 280 insertions(+), 172 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index bc893c97..7c454abf 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:8a5d3f6a2e43ed8293f34e06a2f56931d1e88a2694c3bb11b15df4eb256ad163 -# created: 2022-04-06T10:30:21.687684602Z + digest: sha256:00c9d764fd1cd56265f12a5ef4b99a0c9e87cf261018099141e2ca5158890416 +# created: 2022-04-20T23:42:53.970438194Z diff --git a/docs/conf.py b/docs/conf.py index 8296ba53..0c13ee09 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -24,9 +24,9 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys import os import shlex +import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the diff --git a/google/cloud/language/__init__.py b/google/cloud/language/__init__.py index 07624150..60d1431a 100644 --- a/google/cloud/language/__init__.py +++ b/google/cloud/language/__init__.py @@ -14,40 +14,37 @@ # limitations under the License. # -from google.cloud.language_v1.services.language_service.client import ( - LanguageServiceClient, -) from google.cloud.language_v1.services.language_service.async_client import ( LanguageServiceAsyncClient, ) - -from google.cloud.language_v1.types.language_service import AnalyzeEntitiesRequest -from google.cloud.language_v1.types.language_service import AnalyzeEntitiesResponse -from google.cloud.language_v1.types.language_service import ( - AnalyzeEntitySentimentRequest, +from google.cloud.language_v1.services.language_service.client import ( + LanguageServiceClient, ) from google.cloud.language_v1.types.language_service import ( + AnalyzeEntitiesRequest, + AnalyzeEntitiesResponse, + AnalyzeEntitySentimentRequest, AnalyzeEntitySentimentResponse, + AnalyzeSentimentRequest, + AnalyzeSentimentResponse, + AnalyzeSyntaxRequest, + AnalyzeSyntaxResponse, + AnnotateTextRequest, + AnnotateTextResponse, + ClassificationCategory, + ClassifyTextRequest, + ClassifyTextResponse, + DependencyEdge, + Document, + EncodingType, + Entity, + EntityMention, + PartOfSpeech, + Sentence, + Sentiment, + TextSpan, + Token, ) -from google.cloud.language_v1.types.language_service import AnalyzeSentimentRequest -from google.cloud.language_v1.types.language_service import AnalyzeSentimentResponse -from google.cloud.language_v1.types.language_service import AnalyzeSyntaxRequest -from google.cloud.language_v1.types.language_service import AnalyzeSyntaxResponse -from google.cloud.language_v1.types.language_service import AnnotateTextRequest -from google.cloud.language_v1.types.language_service import AnnotateTextResponse -from google.cloud.language_v1.types.language_service import ClassificationCategory -from google.cloud.language_v1.types.language_service import ClassifyTextRequest -from google.cloud.language_v1.types.language_service import ClassifyTextResponse -from google.cloud.language_v1.types.language_service import DependencyEdge -from google.cloud.language_v1.types.language_service import Document -from google.cloud.language_v1.types.language_service import Entity -from google.cloud.language_v1.types.language_service import EntityMention -from google.cloud.language_v1.types.language_service import PartOfSpeech -from google.cloud.language_v1.types.language_service import Sentence -from google.cloud.language_v1.types.language_service import Sentiment -from google.cloud.language_v1.types.language_service import TextSpan -from google.cloud.language_v1.types.language_service import Token -from google.cloud.language_v1.types.language_service import EncodingType __all__ = ( "LanguageServiceClient", diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py index bcca7fb4..9e99392d 100644 --- a/google/cloud/language_v1/__init__.py +++ b/google/cloud/language_v1/__init__.py @@ -14,32 +14,32 @@ # limitations under the License. # -from .services.language_service import LanguageServiceClient -from .services.language_service import LanguageServiceAsyncClient - -from .types.language_service import AnalyzeEntitiesRequest -from .types.language_service import AnalyzeEntitiesResponse -from .types.language_service import AnalyzeEntitySentimentRequest -from .types.language_service import AnalyzeEntitySentimentResponse -from .types.language_service import AnalyzeSentimentRequest -from .types.language_service import AnalyzeSentimentResponse -from .types.language_service import AnalyzeSyntaxRequest -from .types.language_service import AnalyzeSyntaxResponse -from .types.language_service import AnnotateTextRequest -from .types.language_service import AnnotateTextResponse -from .types.language_service import ClassificationCategory -from .types.language_service import ClassifyTextRequest -from .types.language_service import ClassifyTextResponse -from .types.language_service import DependencyEdge -from .types.language_service import Document -from .types.language_service import Entity -from .types.language_service import EntityMention -from .types.language_service import PartOfSpeech -from .types.language_service import Sentence -from .types.language_service import Sentiment -from .types.language_service import TextSpan -from .types.language_service import Token -from .types.language_service import EncodingType +from .services.language_service import LanguageServiceAsyncClient, LanguageServiceClient +from .types.language_service import ( + AnalyzeEntitiesRequest, + AnalyzeEntitiesResponse, + AnalyzeEntitySentimentRequest, + AnalyzeEntitySentimentResponse, + AnalyzeSentimentRequest, + AnalyzeSentimentResponse, + AnalyzeSyntaxRequest, + AnalyzeSyntaxResponse, + AnnotateTextRequest, + AnnotateTextResponse, + ClassificationCategory, + ClassifyTextRequest, + ClassifyTextResponse, + DependencyEdge, + Document, + EncodingType, + Entity, + EntityMention, + PartOfSpeech, + Sentence, + Sentiment, + TextSpan, + Token, +) __all__ = ( "LanguageServiceAsyncClient", diff --git a/google/cloud/language_v1/services/language_service/__init__.py b/google/cloud/language_v1/services/language_service/__init__.py index d12b0495..6a15301c 100644 --- a/google/cloud/language_v1/services/language_service/__init__.py +++ b/google/cloud/language_v1/services/language_service/__init__.py @@ -13,8 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import LanguageServiceClient from .async_client import LanguageServiceAsyncClient +from .client import LanguageServiceClient __all__ = ( "LanguageServiceClient", diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 96784158..cf38f87c 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -17,14 +17,14 @@ import functools import re from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources -from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -32,9 +32,10 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1.types import language_service -from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport + from .client import LanguageServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport +from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport class LanguageServiceAsyncClient: diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index a5173c34..3ac67a03 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -17,17 +17,17 @@ import os import re from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # 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 +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -35,7 +35,8 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1.types import language_service -from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport from .transports.grpc import LanguageServiceGrpcTransport from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport diff --git a/google/cloud/language_v1/services/language_service/transports/__init__.py b/google/cloud/language_v1/services/language_service/transports/__init__.py index 2cb702a6..5ec2196c 100644 --- a/google/cloud/language_v1/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1/services/language_service/transports/__init__.py @@ -20,7 +20,6 @@ from .grpc import LanguageServiceGrpcTransport from .grpc_asyncio import LanguageServiceGrpcAsyncIOTransport - # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[LanguageServiceTransport]] _transport_registry["grpc"] = LanguageServiceGrpcTransport diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 65c3cae2..770b217e 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -15,15 +15,15 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources -import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +import pkg_resources from google.cloud.language_v1.types import language_service diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index b7b421af..5bf182e1 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -13,19 +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, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, grpc_helpers 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.language_v1.types import language_service -from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport class LanguageServiceGrpcTransport(LanguageServiceTransport): diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 4b10a361..06ea0290 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -13,19 +13,18 @@ # 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, Union +import warnings -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async +from google.api_core import gapic_v1, grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.language_v1.types import language_service -from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport from .grpc import LanguageServiceGrpcTransport diff --git a/google/cloud/language_v1/types/__init__.py b/google/cloud/language_v1/types/__init__.py index 6a80ff72..0f35f2e3 100644 --- a/google/cloud/language_v1/types/__init__.py +++ b/google/cloud/language_v1/types/__init__.py @@ -29,6 +29,7 @@ ClassifyTextResponse, DependencyEdge, Document, + EncodingType, Entity, EntityMention, PartOfSpeech, @@ -36,7 +37,6 @@ Sentiment, TextSpan, Token, - EncodingType, ) __all__ = ( diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index eed340e3..2cd79d57 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -15,7 +15,6 @@ # import proto # type: ignore - __protobuf__ = proto.module( package="google.cloud.language.v1", manifest={ diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py index bcca7fb4..9e99392d 100644 --- a/google/cloud/language_v1beta2/__init__.py +++ b/google/cloud/language_v1beta2/__init__.py @@ -14,32 +14,32 @@ # limitations under the License. # -from .services.language_service import LanguageServiceClient -from .services.language_service import LanguageServiceAsyncClient - -from .types.language_service import AnalyzeEntitiesRequest -from .types.language_service import AnalyzeEntitiesResponse -from .types.language_service import AnalyzeEntitySentimentRequest -from .types.language_service import AnalyzeEntitySentimentResponse -from .types.language_service import AnalyzeSentimentRequest -from .types.language_service import AnalyzeSentimentResponse -from .types.language_service import AnalyzeSyntaxRequest -from .types.language_service import AnalyzeSyntaxResponse -from .types.language_service import AnnotateTextRequest -from .types.language_service import AnnotateTextResponse -from .types.language_service import ClassificationCategory -from .types.language_service import ClassifyTextRequest -from .types.language_service import ClassifyTextResponse -from .types.language_service import DependencyEdge -from .types.language_service import Document -from .types.language_service import Entity -from .types.language_service import EntityMention -from .types.language_service import PartOfSpeech -from .types.language_service import Sentence -from .types.language_service import Sentiment -from .types.language_service import TextSpan -from .types.language_service import Token -from .types.language_service import EncodingType +from .services.language_service import LanguageServiceAsyncClient, LanguageServiceClient +from .types.language_service import ( + AnalyzeEntitiesRequest, + AnalyzeEntitiesResponse, + AnalyzeEntitySentimentRequest, + AnalyzeEntitySentimentResponse, + AnalyzeSentimentRequest, + AnalyzeSentimentResponse, + AnalyzeSyntaxRequest, + AnalyzeSyntaxResponse, + AnnotateTextRequest, + AnnotateTextResponse, + ClassificationCategory, + ClassifyTextRequest, + ClassifyTextResponse, + DependencyEdge, + Document, + EncodingType, + Entity, + EntityMention, + PartOfSpeech, + Sentence, + Sentiment, + TextSpan, + Token, +) __all__ = ( "LanguageServiceAsyncClient", diff --git a/google/cloud/language_v1beta2/services/language_service/__init__.py b/google/cloud/language_v1beta2/services/language_service/__init__.py index d12b0495..6a15301c 100644 --- a/google/cloud/language_v1beta2/services/language_service/__init__.py +++ b/google/cloud/language_v1beta2/services/language_service/__init__.py @@ -13,8 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import LanguageServiceClient from .async_client import LanguageServiceAsyncClient +from .client import LanguageServiceClient __all__ = ( "LanguageServiceClient", diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index f20561ed..abeaf9e3 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -17,14 +17,14 @@ import functools import re from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources -from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -32,9 +32,10 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1beta2.types import language_service -from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport + from .client import LanguageServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport +from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport class LanguageServiceAsyncClient: diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index ac1049b9..936f1151 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -17,17 +17,17 @@ import os import re from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # 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 +import pkg_resources try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -35,7 +35,8 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.language_v1beta2.types import language_service -from .transports.base import LanguageServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport from .transports.grpc import LanguageServiceGrpcTransport from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport diff --git a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py index 2cb702a6..5ec2196c 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py @@ -20,7 +20,6 @@ from .grpc import LanguageServiceGrpcTransport from .grpc_asyncio import LanguageServiceGrpcAsyncIOTransport - # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[LanguageServiceTransport]] _transport_registry["grpc"] = LanguageServiceGrpcTransport diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index dd29d40a..358e3dce 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -15,15 +15,15 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources -import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +import pkg_resources from google.cloud.language_v1beta2.types import language_service diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index c6b1b540..b584552e 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -13,19 +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, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, grpc_helpers 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.language_v1beta2.types import language_service -from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport class LanguageServiceGrpcTransport(LanguageServiceTransport): diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 4cb0142e..f4f8e4d3 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -13,19 +13,18 @@ # 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, Union +import warnings -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async +from google.api_core import gapic_v1, grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.language_v1beta2.types import language_service -from .base import LanguageServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport from .grpc import LanguageServiceGrpcTransport diff --git a/google/cloud/language_v1beta2/types/__init__.py b/google/cloud/language_v1beta2/types/__init__.py index 6a80ff72..0f35f2e3 100644 --- a/google/cloud/language_v1beta2/types/__init__.py +++ b/google/cloud/language_v1beta2/types/__init__.py @@ -29,6 +29,7 @@ ClassifyTextResponse, DependencyEdge, Document, + EncodingType, Entity, EntityMention, PartOfSpeech, @@ -36,7 +37,6 @@ Sentiment, TextSpan, Token, - EncodingType, ) __all__ = ( diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 194002bc..b43b62ed 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -15,7 +15,6 @@ # import proto # type: ignore - __protobuf__ = proto.module( package="google.cloud.language.v1beta2", manifest={ diff --git a/noxfile.py b/noxfile.py index 6ee5e8ab..7c1742d2 100644 --- a/noxfile.py +++ b/noxfile.py @@ -17,6 +17,7 @@ # Generated by synthtool. DO NOT EDIT! from __future__ import absolute_import + import os import pathlib import shutil @@ -25,7 +26,8 @@ import nox BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] +ISORT_VERSION = "isort==5.10.1" +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" @@ -83,7 +85,7 @@ def lint(session): session.run( "black", "--check", - *BLACK_PATHS, + *LINT_PATHS, ) session.run("flake8", "google", "tests") @@ -94,7 +96,27 @@ def blacken(session): session.install(BLACK_VERSION) session.run( "black", - *BLACK_PATHS, + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, ) diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 25f87a21..3b3ffa5d 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -22,7 +22,6 @@ import nox - # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING # DO NOT EDIT THIS FILE EVER! @@ -30,6 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING BLACK_VERSION = "black==22.3.0" +ISORT_VERSION = "isort==5.10.1" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -168,12 +168,33 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) +# +# format = isort + black +# + + +@nox.session +def format(session: nox.sessions.Session) -> None: + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run("isort", "--fss", *python_files) + session.run("black", *python_files) + + # # Sample Tests # diff --git a/samples/snippets/classify_text/classify_text_tutorial_test.py b/samples/snippets/classify_text/classify_text_tutorial_test.py index 5e821129..5859a771 100644 --- a/samples/snippets/classify_text/classify_text_tutorial_test.py +++ b/samples/snippets/classify_text/classify_text_tutorial_test.py @@ -17,7 +17,6 @@ import classify_text_tutorial - OUTPUT = "index.json" RESOURCES = os.path.join(os.path.dirname(__file__), "resources") QUERY_TEXT = """Google Home enables users to speak voice commands to interact diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 25f87a21..3b3ffa5d 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -22,7 +22,6 @@ import nox - # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING # DO NOT EDIT THIS FILE EVER! @@ -30,6 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING BLACK_VERSION = "black==22.3.0" +ISORT_VERSION = "isort==5.10.1" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -168,12 +168,33 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) +# +# format = isort + black +# + + +@nox.session +def format(session: nox.sessions.Session) -> None: + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run("isort", "--fss", *python_files) + session.run("black", *python_files) + + # # Sample Tests # diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 25f87a21..3b3ffa5d 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -22,7 +22,6 @@ import nox - # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING # DO NOT EDIT THIS FILE EVER! @@ -30,6 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING BLACK_VERSION = "black==22.3.0" +ISORT_VERSION = "isort==5.10.1" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -168,12 +168,33 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) +# +# format = isort + black +# + + +@nox.session +def format(session: nox.sessions.Session) -> None: + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run("isort", "--fss", *python_files) + session.run("black", *python_files) + + # # Sample Tests # diff --git a/samples/snippets/cloud-client/v1/quickstart.py b/samples/snippets/cloud-client/v1/quickstart.py index 59c1cd43..bbc914d1 100644 --- a/samples/snippets/cloud-client/v1/quickstart.py +++ b/samples/snippets/cloud-client/v1/quickstart.py @@ -22,7 +22,6 @@ def run_quickstart(): from google.cloud import language_v1 # [END language_python_migration_imports] - # Instantiates a client # [START language_python_migration_client] client = language_v1.LanguageServiceClient() diff --git a/samples/snippets/generated-samples/v1/language_sentiment_text.py b/samples/snippets/generated-samples/v1/language_sentiment_text.py index 4170ddbc..13447d17 100644 --- a/samples/snippets/generated-samples/v1/language_sentiment_text.py +++ b/samples/snippets/generated-samples/v1/language_sentiment_text.py @@ -21,6 +21,7 @@ import sys +# isort: split # [START language_sentiment_text] from google.cloud import language_v1 diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 25f87a21..3b3ffa5d 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -22,7 +22,6 @@ import nox - # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING # DO NOT EDIT THIS FILE EVER! @@ -30,6 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING BLACK_VERSION = "black==22.3.0" +ISORT_VERSION = "isort==5.10.1" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -168,12 +168,33 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) +# +# format = isort + black +# + + +@nox.session +def format(session: nox.sessions.Session) -> None: + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run("isort", "--fss", *python_files) + session.run("black", *python_files) + + # # Sample Tests # diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 25f87a21..3b3ffa5d 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -22,7 +22,6 @@ import nox - # WARNING - WARNING - WARNING - WARNING - WARNING # WARNING - WARNING - WARNING - WARNING - WARNING # DO NOT EDIT THIS FILE EVER! @@ -30,6 +29,7 @@ # WARNING - WARNING - WARNING - WARNING - WARNING BLACK_VERSION = "black==22.3.0" +ISORT_VERSION = "isort==5.10.1" # Copy `noxfile_config.py` to your directory and modify it instead. @@ -168,12 +168,33 @@ def lint(session: nox.sessions.Session) -> None: @nox.session def blacken(session: nox.sessions.Session) -> None: + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) python_files = [path for path in os.listdir(".") if path.endswith(".py")] session.run("black", *python_files) +# +# format = isort + black +# + + +@nox.session +def format(session: nox.sessions.Session) -> None: + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run("isort", "--fss", *python_files) + session.run("black", *python_files) + + # # Sample Tests # diff --git a/setup.py b/setup.py index 7547eb60..8c8c73b6 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,6 @@ import setuptools - # Package metadata. name = "google-cloud-language" diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 08447420..a3baefe2 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -13,32 +13,28 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import os -import mock - -import grpc -from grpc.experimental import aio import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - +import os +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template from google.api_core import client_options 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.api_core import path_template +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +import grpc +from grpc.experimental import aio +import mock +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + from google.cloud.language_v1.services.language_service import ( LanguageServiceAsyncClient, + LanguageServiceClient, + transports, ) -from google.cloud.language_v1.services.language_service import LanguageServiceClient -from google.cloud.language_v1.services.language_service import transports from google.cloud.language_v1.types import language_service -from google.oauth2 import service_account -import google.auth def client_cert_source_callback(): diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 6603d4a3..ff0e85f6 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -13,34 +13,28 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import os -import mock - -import grpc -from grpc.experimental import aio import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - +import os +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template from google.api_core import client_options 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.api_core import path_template +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +import grpc +from grpc.experimental import aio +import mock +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + from google.cloud.language_v1beta2.services.language_service import ( LanguageServiceAsyncClient, -) -from google.cloud.language_v1beta2.services.language_service import ( LanguageServiceClient, + transports, ) -from google.cloud.language_v1beta2.services.language_service import transports from google.cloud.language_v1beta2.types import language_service -from google.oauth2 import service_account -import google.auth def client_cert_source_callback(): From a8801b29c63d5b78454fe18ff4d9922ec8909098 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 21 Apr 2022 16:12:34 +0000 Subject: [PATCH 148/254] chore(python): use ubuntu 22.04 in docs image (#307) Source-Link: https://github.com/googleapis/synthtool/commit/f15cc72fb401b4861cedebb10af74afe428fb1f8 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:bc5eed3804aec2f05fad42aacf973821d9500c174015341f721a984a0825b6fd --- .github/.OwlBot.lock.yaml | 4 ++-- .kokoro/docker/docs/Dockerfile | 20 ++++++++++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 7c454abf..64f82d6b 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:00c9d764fd1cd56265f12a5ef4b99a0c9e87cf261018099141e2ca5158890416 -# created: 2022-04-20T23:42:53.970438194Z + digest: sha256:bc5eed3804aec2f05fad42aacf973821d9500c174015341f721a984a0825b6fd +# created: 2022-04-21T15:43:16.246106921Z diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile index 4e1b1fb8..238b87b9 100644 --- a/.kokoro/docker/docs/Dockerfile +++ b/.kokoro/docker/docs/Dockerfile @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from ubuntu:20.04 +from ubuntu:22.04 ENV DEBIAN_FRONTEND noninteractive @@ -60,8 +60,24 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* \ && rm -f /var/cache/apt/archives/*.deb +###################### Install python 3.8.11 + +# Download python 3.8.11 +RUN wget https://www.python.org/ftp/python/3.8.11/Python-3.8.11.tgz + +# Extract files +RUN tar -xvf Python-3.8.11.tgz + +# Install python 3.8.11 +RUN ./Python-3.8.11/configure --enable-optimizations +RUN make altinstall + +###################### Install pip RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ - && python3.8 /tmp/get-pip.py \ + && python3 /tmp/get-pip.py \ && rm /tmp/get-pip.py +# Test pip +RUN python3 -m pip + CMD ["python3.8"] From 5a66193d7e9f084f6cdd2148cf70c6976f545a0f Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Fri, 22 Apr 2022 10:27:20 +0200 Subject: [PATCH 149/254] chore(deps): update dependency google-auth to v2.6.6 (#308) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 665a8c67..ceb309e4 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.45.0 -google-auth==2.6.5 +google-auth==2.6.6 google-auth-httplib2==0.1.0 From 0f2de97e58fa6f58b743c3f85b05d5b82a46b258 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Mon, 25 Apr 2022 17:08:42 +0200 Subject: [PATCH 150/254] chore(deps): update dependency pytest to v7.1.2 (#310) --- samples/snippets/api/requirements-test.txt | 2 +- samples/snippets/classify_text/requirements-test.txt | 2 +- samples/snippets/cloud-client/v1/requirements-test.txt | 2 +- samples/snippets/generated-samples/v1/requirements-test.txt | 2 +- samples/snippets/sentiment/requirements-test.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt index 4f6bf643..d00689e0 100644 --- a/samples/snippets/api/requirements-test.txt +++ b/samples/snippets/api/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.1 +pytest==7.1.2 diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt index 4f6bf643..d00689e0 100644 --- a/samples/snippets/classify_text/requirements-test.txt +++ b/samples/snippets/classify_text/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.1 +pytest==7.1.2 diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt index 4f6bf643..d00689e0 100644 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ b/samples/snippets/cloud-client/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.1 +pytest==7.1.2 diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt index 4f6bf643..d00689e0 100644 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ b/samples/snippets/generated-samples/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.1 +pytest==7.1.2 diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt index 4f6bf643..d00689e0 100644 --- a/samples/snippets/sentiment/requirements-test.txt +++ b/samples/snippets/sentiment/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.1 +pytest==7.1.2 From 717faff52de5350d2428f1daae4c07d9c4487297 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 26 Apr 2022 20:03:33 +0200 Subject: [PATCH 151/254] chore(deps): update dependency google-api-python-client to v2.46.0 (#311) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index ceb309e4..658c99bf 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.45.0 +google-api-python-client==2.46.0 google-auth==2.6.6 google-auth-httplib2==0.1.0 From d202165a7493338d3887d30dbff39b6b9be97541 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 28 Apr 2022 08:05:13 -0400 Subject: [PATCH 152/254] chore: use gapic-generator-python 0.65.2 (#312) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: use gapic-generator-python 0.65.2 PiperOrigin-RevId: 444333013 Source-Link: https://github.com/googleapis/googleapis/commit/f91b6cf82e929280f6562f6110957c654bd9e2e6 Source-Link: https://github.com/googleapis/googleapis-gen/commit/16eb36095c294e712c74a1bf23550817b42174e5 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMTZlYjM2MDk1YzI5NGU3MTJjNzRhMWJmMjM1NTA4MTdiNDIxNzRlNSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../services/language_service/async_client.py | 36 +++++++++---------- .../services/language_service/async_client.py | 36 +++++++++---------- language-v1beta2-py.tar.gz | 0 3 files changed, 36 insertions(+), 36 deletions(-) create mode 100644 language-v1beta2-py.tar.gz diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index cf38f87c..3c778545 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -218,9 +218,9 @@ async def analyze_sentiment( from google.cloud import language_v1 - def sample_analyze_sentiment(): + async def sample_analyze_sentiment(): # Create a client - client = language_v1.LanguageServiceClient() + client = language_v1.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1.Document() @@ -231,7 +231,7 @@ def sample_analyze_sentiment(): ) # Make the request - response = client.analyze_sentiment(request=request) + response = await client.analyze_sentiment(request=request) # Handle the response print(response) @@ -331,9 +331,9 @@ async def analyze_entities( from google.cloud import language_v1 - def sample_analyze_entities(): + async def sample_analyze_entities(): # Create a client - client = language_v1.LanguageServiceClient() + client = language_v1.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1.Document() @@ -344,7 +344,7 @@ def sample_analyze_entities(): ) # Make the request - response = client.analyze_entities(request=request) + response = await client.analyze_entities(request=request) # Handle the response print(response) @@ -441,9 +441,9 @@ async def analyze_entity_sentiment( from google.cloud import language_v1 - def sample_analyze_entity_sentiment(): + async def sample_analyze_entity_sentiment(): # Create a client - client = language_v1.LanguageServiceClient() + client = language_v1.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1.Document() @@ -454,7 +454,7 @@ def sample_analyze_entity_sentiment(): ) # Make the request - response = client.analyze_entity_sentiment(request=request) + response = await client.analyze_entity_sentiment(request=request) # Handle the response print(response) @@ -553,9 +553,9 @@ async def analyze_syntax( from google.cloud import language_v1 - def sample_analyze_syntax(): + async def sample_analyze_syntax(): # Create a client - client = language_v1.LanguageServiceClient() + client = language_v1.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1.Document() @@ -566,7 +566,7 @@ def sample_analyze_syntax(): ) # Make the request - response = client.analyze_syntax(request=request) + response = await client.analyze_syntax(request=request) # Handle the response print(response) @@ -659,9 +659,9 @@ async def classify_text( from google.cloud import language_v1 - def sample_classify_text(): + async def sample_classify_text(): # Create a client - client = language_v1.LanguageServiceClient() + client = language_v1.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1.Document() @@ -672,7 +672,7 @@ def sample_classify_text(): ) # Make the request - response = client.classify_text(request=request) + response = await client.classify_text(request=request) # Handle the response print(response) @@ -763,9 +763,9 @@ async def annotate_text( from google.cloud import language_v1 - def sample_annotate_text(): + async def sample_annotate_text(): # Create a client - client = language_v1.LanguageServiceClient() + client = language_v1.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1.Document() @@ -776,7 +776,7 @@ def sample_annotate_text(): ) # Make the request - response = client.annotate_text(request=request) + response = await client.annotate_text(request=request) # Handle the response print(response) diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index abeaf9e3..52542d57 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -218,9 +218,9 @@ async def analyze_sentiment( from google.cloud import language_v1beta2 - def sample_analyze_sentiment(): + async def sample_analyze_sentiment(): # Create a client - client = language_v1beta2.LanguageServiceClient() + client = language_v1beta2.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1beta2.Document() @@ -231,7 +231,7 @@ def sample_analyze_sentiment(): ) # Make the request - response = client.analyze_sentiment(request=request) + response = await client.analyze_sentiment(request=request) # Handle the response print(response) @@ -332,9 +332,9 @@ async def analyze_entities( from google.cloud import language_v1beta2 - def sample_analyze_entities(): + async def sample_analyze_entities(): # Create a client - client = language_v1beta2.LanguageServiceClient() + client = language_v1beta2.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1beta2.Document() @@ -345,7 +345,7 @@ def sample_analyze_entities(): ) # Make the request - response = client.analyze_entities(request=request) + response = await client.analyze_entities(request=request) # Handle the response print(response) @@ -442,9 +442,9 @@ async def analyze_entity_sentiment( from google.cloud import language_v1beta2 - def sample_analyze_entity_sentiment(): + async def sample_analyze_entity_sentiment(): # Create a client - client = language_v1beta2.LanguageServiceClient() + client = language_v1beta2.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1beta2.Document() @@ -455,7 +455,7 @@ def sample_analyze_entity_sentiment(): ) # Make the request - response = client.analyze_entity_sentiment(request=request) + response = await client.analyze_entity_sentiment(request=request) # Handle the response print(response) @@ -554,9 +554,9 @@ async def analyze_syntax( from google.cloud import language_v1beta2 - def sample_analyze_syntax(): + async def sample_analyze_syntax(): # Create a client - client = language_v1beta2.LanguageServiceClient() + client = language_v1beta2.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1beta2.Document() @@ -567,7 +567,7 @@ def sample_analyze_syntax(): ) # Make the request - response = client.analyze_syntax(request=request) + response = await client.analyze_syntax(request=request) # Handle the response print(response) @@ -660,9 +660,9 @@ async def classify_text( from google.cloud import language_v1beta2 - def sample_classify_text(): + async def sample_classify_text(): # Create a client - client = language_v1beta2.LanguageServiceClient() + client = language_v1beta2.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1beta2.Document() @@ -673,7 +673,7 @@ def sample_classify_text(): ) # Make the request - response = client.classify_text(request=request) + response = await client.classify_text(request=request) # Handle the response print(response) @@ -764,9 +764,9 @@ async def annotate_text( from google.cloud import language_v1beta2 - def sample_annotate_text(): + async def sample_annotate_text(): # Create a client - client = language_v1beta2.LanguageServiceClient() + client = language_v1beta2.LanguageServiceAsyncClient() # Initialize request argument(s) document = language_v1beta2.Document() @@ -777,7 +777,7 @@ def sample_annotate_text(): ) # Make the request - response = client.annotate_text(request=request) + response = await client.annotate_text(request=request) # Handle the response print(response) diff --git a/language-v1beta2-py.tar.gz b/language-v1beta2-py.tar.gz new file mode 100644 index 00000000..e69de29b From 29f76f4adaf9b25ad1148c85384429e418ca4a26 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 3 May 2022 20:20:30 +0200 Subject: [PATCH 153/254] chore(deps): update dependency google-api-python-client to v2.47.0 (#313) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 658c99bf..654cf0f4 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.46.0 +google-api-python-client==2.47.0 google-auth==2.6.6 google-auth-httplib2==0.1.0 From 9eba3cdc115f84d239a788f5089b1190fb15d598 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 5 May 2022 12:12:25 -0400 Subject: [PATCH 154/254] chore: [autoapprove] update readme_gen.py to include autoescape True (#314) Source-Link: https://github.com/googleapis/synthtool/commit/6b4d5a6407d740beb4158b302194a62a4108a8a6 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f792ee1320e03eda2d13a5281a2989f7ed8a9e50b73ef6da97fac7e1e850b149 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 4 ++-- scripts/readme-gen/readme_gen.py | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 64f82d6b..b631901e 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:bc5eed3804aec2f05fad42aacf973821d9500c174015341f721a984a0825b6fd -# created: 2022-04-21T15:43:16.246106921Z + digest: sha256:f792ee1320e03eda2d13a5281a2989f7ed8a9e50b73ef6da97fac7e1e850b149 +# created: 2022-05-05T15:17:27.599381182Z diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py index d309d6e9..91b59676 100644 --- a/scripts/readme-gen/readme_gen.py +++ b/scripts/readme-gen/readme_gen.py @@ -28,7 +28,10 @@ jinja_env = jinja2.Environment( trim_blocks=True, loader=jinja2.FileSystemLoader( - os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates')))) + os.path.abspath(os.path.join(os.path.dirname(__file__), "templates")) + ), + autoescape=True, +) README_TMPL = jinja_env.get_template('README.tmpl.rst') From 2179f33e37a06fb593cc6947a25c06b67f75b613 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 5 May 2022 23:06:27 +0000 Subject: [PATCH 155/254] chore(python): auto approve template changes (#316) Source-Link: https://github.com/googleapis/synthtool/commit/453a5d9c9a55d1969240a37d36cec626d20a9024 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:81ed5ecdfc7cac5b699ba4537376f3563f6f04122c4ec9e735d3b3dc1d43dd32 --- .github/.OwlBot.lock.yaml | 4 ++-- .github/auto-approve.yml | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 .github/auto-approve.yml diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index b631901e..757c9dca 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f792ee1320e03eda2d13a5281a2989f7ed8a9e50b73ef6da97fac7e1e850b149 -# created: 2022-05-05T15:17:27.599381182Z + digest: sha256:81ed5ecdfc7cac5b699ba4537376f3563f6f04122c4ec9e735d3b3dc1d43dd32 +# created: 2022-05-05T22:08:23.383410683Z diff --git a/.github/auto-approve.yml b/.github/auto-approve.yml new file mode 100644 index 00000000..311ebbb8 --- /dev/null +++ b/.github/auto-approve.yml @@ -0,0 +1,3 @@ +# https://github.com/googleapis/repo-automation-bots/tree/main/packages/auto-approve +processes: + - "OwlBotTemplateChanges" From ca849da05f05e996ae7855e8ea5ac2858db260d2 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 17 May 2022 20:49:23 +0200 Subject: [PATCH 156/254] chore(deps): update dependency google-api-python-client to v2.48.0 (#318) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 654cf0f4..04f99eac 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.47.0 +google-api-python-client==2.48.0 google-auth==2.6.6 google-auth-httplib2==0.1.0 From e0a268177a5df9a843b19e1c4864ca5525963d5e Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 19 May 2022 08:53:05 -0400 Subject: [PATCH 157/254] chore(main): release 2.4.2 (#301) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 7 +++++++ setup.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be795a5f..81ecff76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +### [2.4.2](https://github.com/googleapis/python-language/compare/v2.4.1...v2.4.2) (2022-05-17) + + +### Documentation + +* fix type in docstring for map fields ([41c28cd](https://github.com/googleapis/python-language/commit/41c28cd35b91adcbe3221a898419c323875b5cfd)) + ### [2.4.1](https://github.com/googleapis/python-language/compare/v2.4.0...v2.4.1) (2022-03-05) diff --git a/setup.py b/setup.py index 8c8c73b6..5f033d43 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.4.1" +version = "2.4.2" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 7521e37f7b0e40f59183bfb11a3d0ae47144947a Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Thu, 19 May 2022 17:51:06 +0200 Subject: [PATCH 158/254] chore(deps): update dependency google-cloud-language to v2.4.2 (#319) --- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index dc049d13..18edbce3 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.4.1 +google-cloud-language==2.4.2 numpy==1.22.3; python_version > '3.7' numpy===1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 0d2a8d65..33f606ed 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.1 +google-cloud-language==2.4.2 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 0d2a8d65..33f606ed 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.1 +google-cloud-language==2.4.2 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 0d2a8d65..33f606ed 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.1 +google-cloud-language==2.4.2 From b46706a8fa4cf15ac201de5664200878d5ae464d Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Sun, 22 May 2022 20:08:05 +0200 Subject: [PATCH 159/254] chore(deps): update dependency numpy to v1.22.4 (#320) --- samples/snippets/classify_text/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 18edbce3..d0380844 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ google-cloud-language==2.4.2 -numpy==1.22.3; python_version > '3.7' +numpy==1.22.4; python_version > '3.7' numpy===1.21.4; python_version == '3.7' From 63edf1203e0caf9e9567daac0defbcd888332bd9 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Fri, 27 May 2022 19:51:02 +0200 Subject: [PATCH 160/254] chore(deps): update dependency google-api-python-client to v2.49.0 (#321) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 04f99eac..e9b14cef 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.48.0 +google-api-python-client==2.49.0 google-auth==2.6.6 google-auth-httplib2==0.1.0 From 94dafb6c01c5902e9a8390b0a04839657ee65f36 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 30 May 2022 17:32:22 +0000 Subject: [PATCH 161/254] chore: use gapic-generator-python 1.0.0 (#323) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 451250442 Source-Link: https://github.com/googleapis/googleapis/commit/cca5e8181f6442b134e8d4d206fbe9e0e74684ba Source-Link: https://github.com/googleapis/googleapis-gen/commit/0b219da161a8bdcc3c6f7b2efcd82105182a30ca Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMGIyMTlkYTE2MWE4YmRjYzNjNmY3YjJlZmNkODIxMDUxODJhMzBjYSJ9 --- tests/unit/gapic/language_v1/test_language_service.py | 11 +++++++++-- .../gapic/language_v1beta2/test_language_service.py | 11 +++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index a3baefe2..284c208a 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -13,9 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import math import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock +except ImportError: + import mock + +import math + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -25,7 +33,6 @@ from google.oauth2 import service_account import grpc from grpc.experimental import aio -import mock from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index ff0e85f6..e625436f 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -13,9 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import math import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock +except ImportError: + import mock + +import math + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -25,7 +33,6 @@ from google.oauth2 import service_account import grpc from grpc.experimental import aio -import mock from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest From 1048350a2b4cf175b445c52bd52142166d104fc6 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Wed, 1 Jun 2022 14:06:18 -0400 Subject: [PATCH 162/254] fix(deps): require protobuf <4.0.0dev (#325) --- setup.py | 3 ++- testing/constraints-3.6.txt | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 5f033d43..3f6d7c15 100644 --- a/setup.py +++ b/setup.py @@ -32,7 +32,8 @@ # Until this issue is closed # https://github.com/googleapis/google-cloud-python/issues/10566 "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", - "proto-plus >= 1.15.0", + "proto-plus >= 1.15.0, <2.0.0dev", + "protobuf >= 3.19.0, <4.0.0dev", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 9f7fec03..53020643 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,3 +7,4 @@ google-api-core==1.31.5 proto-plus==1.15.0 libcst==0.2.5 +protobuf==3.19.0 From 11aa9864db65556a3a27c1a7a99bf96ea60ad434 Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Thu, 2 Jun 2022 20:54:11 -0400 Subject: [PATCH 163/254] docs: fix changelog header to consistent size (#324) Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- CHANGELOG.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81ecff76..4f67aa53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,14 +4,14 @@ [1]: https://pypi.org/project/google-cloud-language/#history -### [2.4.2](https://github.com/googleapis/python-language/compare/v2.4.1...v2.4.2) (2022-05-17) +## [2.4.2](https://github.com/googleapis/python-language/compare/v2.4.1...v2.4.2) (2022-05-17) ### Documentation * fix type in docstring for map fields ([41c28cd](https://github.com/googleapis/python-language/commit/41c28cd35b91adcbe3221a898419c323875b5cfd)) -### [2.4.1](https://github.com/googleapis/python-language/compare/v2.4.0...v2.4.1) (2022-03-05) +## [2.4.1](https://github.com/googleapis/python-language/compare/v2.4.0...v2.4.1) (2022-03-05) ### Bug Fixes @@ -31,14 +31,14 @@ * resolve DuplicateCredentialArgs error when using credentials_file ([3e7c964](https://github.com/googleapis/python-language/commit/3e7c96410914d9080ecd0325c61bdc624adf08e1)) -### [2.3.2](https://github.com/googleapis/python-language/compare/v2.3.1...v2.3.2) (2022-01-20) +## [2.3.2](https://github.com/googleapis/python-language/compare/v2.3.1...v2.3.2) (2022-01-20) ### Documentation * **samples:** Document -> types.Document ([#227](https://github.com/googleapis/python-language/issues/227)) ([01367d7](https://github.com/googleapis/python-language/commit/01367d7b1e0ddba6e6b920f125730aa97d51ada0)) -### [2.3.1](https://www.github.com/googleapis/python-language/compare/v2.3.0...v2.3.1) (2021-11-01) +## [2.3.1](https://www.github.com/googleapis/python-language/compare/v2.3.0...v2.3.1) (2021-11-01) ### Bug Fixes @@ -58,7 +58,7 @@ * add context manager support in client ([#203](https://www.github.com/googleapis/python-language/issues/203)) ([91d48a8](https://www.github.com/googleapis/python-language/commit/91d48a8fee63b8279b235b70921d018206084b50)) -### [2.2.2](https://www.github.com/googleapis/python-language/compare/v2.2.1...v2.2.2) (2021-07-28) +## [2.2.2](https://www.github.com/googleapis/python-language/compare/v2.2.1...v2.2.2) (2021-07-28) ### Bug Fixes @@ -75,7 +75,7 @@ * release as 2.2.2 ([#170](https://www.github.com/googleapis/python-language/issues/170)) ([4d40053](https://www.github.com/googleapis/python-language/commit/4d400539508ec81cbc76e3f6166e3ec86054ed65)) -### [2.2.1](https://www.github.com/googleapis/python-language/compare/v2.2.0...v2.2.1) (2021-07-20) +## [2.2.1](https://www.github.com/googleapis/python-language/compare/v2.2.0...v2.2.1) (2021-07-20) ### Bug Fixes From a429ab8081144623d7bdf687eef38e1fd6563cbd Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Mon, 6 Jun 2022 18:08:28 -0400 Subject: [PATCH 164/254] chore: test minimum dependencies in python 3.7 (#328) --- testing/constraints-3.7.txt | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index da93009b..53020643 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -1,2 +1,10 @@ -# This constraints file is left inentionally empty -# so the latest version of dependencies is installed \ No newline at end of file +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.31.5 +proto-plus==1.15.0 +libcst==0.2.5 +protobuf==3.19.0 From 4a7cfd41241cf23b94a7edaf4cfec498d59a59a0 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Tue, 7 Jun 2022 07:57:54 -0400 Subject: [PATCH 165/254] chore(main): release 2.4.3 (#326) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 12 ++++++++++++ setup.py | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f67aa53..994e9410 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.4.3](https://github.com/googleapis/python-language/compare/v2.4.2...v2.4.3) (2022-06-06) + + +### Bug Fixes + +* **deps:** require protobuf <4.0.0dev ([#325](https://github.com/googleapis/python-language/issues/325)) ([1048350](https://github.com/googleapis/python-language/commit/1048350a2b4cf175b445c52bd52142166d104fc6)) + + +### Documentation + +* fix changelog header to consistent size ([#324](https://github.com/googleapis/python-language/issues/324)) ([11aa986](https://github.com/googleapis/python-language/commit/11aa9864db65556a3a27c1a7a99bf96ea60ad434)) + ## [2.4.2](https://github.com/googleapis/python-language/compare/v2.4.1...v2.4.2) (2022-05-17) diff --git a/setup.py b/setup.py index 3f6d7c15..a99b46fe 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.4.2" +version = "2.4.3" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 320b30ff235938c0983829660921d8b6fe083333 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 13 Jun 2022 06:38:02 -0400 Subject: [PATCH 166/254] chore(python): add missing import for prerelease testing (#333) Source-Link: https://github.com/googleapis/synthtool/commit/d2871d98e1e767d4ad49a557ff979236d64361a1 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:b2dc5f80edcf5d4486c39068c9fa11f7f851d9568eea4dcba130f994ea9b5e97 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 4 +- .kokoro/continuous/prerelease-deps.cfg | 7 +++ .kokoro/presubmit/prerelease-deps.cfg | 7 +++ noxfile.py | 65 ++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 .kokoro/continuous/prerelease-deps.cfg create mode 100644 .kokoro/presubmit/prerelease-deps.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 757c9dca..50b29ffd 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:81ed5ecdfc7cac5b699ba4537376f3563f6f04122c4ec9e735d3b3dc1d43dd32 -# created: 2022-05-05T22:08:23.383410683Z + digest: sha256:b2dc5f80edcf5d4486c39068c9fa11f7f851d9568eea4dcba130f994ea9b5e97 +# created: 2022-06-12T16:09:31.61859086Z diff --git a/.kokoro/continuous/prerelease-deps.cfg b/.kokoro/continuous/prerelease-deps.cfg new file mode 100644 index 00000000..3595fb43 --- /dev/null +++ b/.kokoro/continuous/prerelease-deps.cfg @@ -0,0 +1,7 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Only run this nox session. +env_vars: { + key: "NOX_SESSION" + value: "prerelease_deps" +} diff --git a/.kokoro/presubmit/prerelease-deps.cfg b/.kokoro/presubmit/prerelease-deps.cfg new file mode 100644 index 00000000..3595fb43 --- /dev/null +++ b/.kokoro/presubmit/prerelease-deps.cfg @@ -0,0 +1,7 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Only run this nox session. +env_vars: { + key: "NOX_SESSION" + value: "prerelease_deps" +} diff --git a/noxfile.py b/noxfile.py index 7c1742d2..5bb3c201 100644 --- a/noxfile.py +++ b/noxfile.py @@ -20,6 +20,7 @@ import os import pathlib +import re import shutil import warnings @@ -325,3 +326,67 @@ def docfx(session): os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def prerelease_deps(session): + """Run all tests with prerelease versions of dependencies installed.""" + + prerel_deps = [ + "protobuf", + "googleapis-common-protos", + "google-auth", + "grpcio", + "grpcio-status", + "google-api-core", + "proto-plus", + # dependencies of google-auth + "cryptography", + "pyasn1", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = ["requests"] + session.install(*other_deps) + + session.install(*UNIT_TEST_STANDARD_DEPENDENCIES) + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Don't overwrite prerelease packages. + deps = [dep for dep in deps if dep not in prerel_deps] + # We use --no-deps to ensure that pre-release versions aren't overwritten + # by the version ranges in setup.py. + session.install(*deps) + session.install("--no-deps", "-e", ".[all]") + + # Print out prerelease package versions + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run("python", "-c", "import grpc; print(grpc.__version__)") + + session.run("py.test", "tests/unit") + session.run("py.test", "tests/system") + session.run("py.test", "samples/snippets") From b36b40f1ea7a32ccc3b99c7bb815c89cdd75ff53 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 7 Jul 2022 10:14:10 -0400 Subject: [PATCH 167/254] fix: require python 3.7+ (#336) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(python): drop python 3.6 Source-Link: https://github.com/googleapis/synthtool/commit/4f89b13af10d086458f9b379e56a614f9d6dab7b Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:e7bb19d47c13839fe8c147e50e02e8b6cf5da8edd1af8b82208cd6f66cc2829c * add api_description to .repo-metadata.json * require python 3.7+ in setup.py * remove python 3.6 sample configs * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 4 +- .github/workflows/unittest.yml | 2 +- .kokoro/samples/python3.6/common.cfg | 40 --------- .kokoro/samples/python3.6/continuous.cfg | 7 -- .kokoro/samples/python3.6/periodic-head.cfg | 11 --- .kokoro/samples/python3.6/periodic.cfg | 6 -- .kokoro/samples/python3.6/presubmit.cfg | 6 -- .kokoro/test-samples-impl.sh | 4 +- .repo-metadata.json | 3 +- CONTRIBUTING.rst | 6 +- README.rst | 61 +++++++------ noxfile.py | 85 ++++++++++++------- samples/snippets/api/noxfile.py | 2 +- samples/snippets/classify_text/noxfile.py | 2 +- samples/snippets/cloud-client/v1/noxfile.py | 2 +- .../snippets/generated-samples/v1/noxfile.py | 2 +- samples/snippets/sentiment/noxfile.py | 2 +- .../templates/install_deps.tmpl.rst | 2 +- setup.py | 3 +- 19 files changed, 100 insertions(+), 150 deletions(-) delete mode 100644 .kokoro/samples/python3.6/common.cfg delete mode 100644 .kokoro/samples/python3.6/continuous.cfg delete mode 100644 .kokoro/samples/python3.6/periodic-head.cfg delete mode 100644 .kokoro/samples/python3.6/periodic.cfg delete mode 100644 .kokoro/samples/python3.6/presubmit.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 50b29ffd..1ce60852 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:b2dc5f80edcf5d4486c39068c9fa11f7f851d9568eea4dcba130f994ea9b5e97 -# created: 2022-06-12T16:09:31.61859086Z + digest: sha256:e7bb19d47c13839fe8c147e50e02e8b6cf5da8edd1af8b82208cd6f66cc2829c +# created: 2022-07-05T18:31:20.838186805Z diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index e5be6edb..5531b014 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python: ['3.6', '3.7', '3.8', '3.9', '3.10'] + python: ['3.7', '3.8', '3.9', '3.10'] steps: - name: Checkout uses: actions/checkout@v3 diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg deleted file mode 100644 index 3d32e6ed..00000000 --- a/.kokoro/samples/python3.6/common.cfg +++ /dev/null @@ -1,40 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Specify which tests to run -env_vars: { - key: "RUN_TESTS_SESSION" - value: "py-3.6" -} - -# Declare build specific Cloud project. -env_vars: { - key: "BUILD_SPECIFIC_GCLOUD_PROJECT" - value: "python-docs-samples-tests-py36" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples.sh" -} - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" -} - -# Download secrets for samples -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.6/continuous.cfg b/.kokoro/samples/python3.6/continuous.cfg deleted file mode 100644 index 7218af14..00000000 --- a/.kokoro/samples/python3.6/continuous.cfg +++ /dev/null @@ -1,7 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} - diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg deleted file mode 100644 index 676f8aa8..00000000 --- a/.kokoro/samples/python3.6/periodic-head.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples-against-head.sh" -} diff --git a/.kokoro/samples/python3.6/periodic.cfg b/.kokoro/samples/python3.6/periodic.cfg deleted file mode 100644 index 71cd1e59..00000000 --- a/.kokoro/samples/python3.6/periodic.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "False" -} diff --git a/.kokoro/samples/python3.6/presubmit.cfg b/.kokoro/samples/python3.6/presubmit.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.6/presubmit.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh index 8a324c9c..2c6500ca 100755 --- a/.kokoro/test-samples-impl.sh +++ b/.kokoro/test-samples-impl.sh @@ -33,7 +33,7 @@ export PYTHONUNBUFFERED=1 env | grep KOKORO # Install nox -python3.6 -m pip install --upgrade --quiet nox +python3.9 -m pip install --upgrade --quiet nox # Use secrets acessor service account to get secrets if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then @@ -76,7 +76,7 @@ for file in samples/**/requirements.txt; do echo "------------------------------------------------------------" # Use nox to execute the tests for the project. - python3.6 -m nox -s "$RUN_TESTS_SESSION" + python3.9 -m nox -s "$RUN_TESTS_SESSION" EXIT=$? # If this is a periodic build, send the test log to the FlakyBot. diff --git a/.repo-metadata.json b/.repo-metadata.json index 2997cbdb..21e66a7f 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -13,5 +13,6 @@ "requires_billing": true, "default_version": "v1", "codeowner_team": "@googleapis/cdpe-cloudai", - "api_shortname": "language" + "api_shortname": "language", + "api_description": "provides natural language understanding technologies to developers, including sentiment analysis, entity analysis, entity sentiment analysis, content classification, and syntax analysis. This API is part of the larger Cloud Machine Learning API family." } diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index adf8f81c..b200f77f 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.6, 3.7, 3.8, 3.9 and 3.10 on both UNIX and Windows. + 3.7, 3.8, 3.9 and 3.10 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -221,13 +221,11 @@ Supported Python Versions We support: -- `Python 3.6`_ - `Python 3.7`_ - `Python 3.8`_ - `Python 3.9`_ - `Python 3.10`_ -.. _Python 3.6: https://docs.python.org/3.6/ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ .. _Python 3.9: https://docs.python.org/3.9/ @@ -239,7 +237,7 @@ Supported versions can be found in our ``noxfile.py`` `config`_. .. _config: https://github.com/googleapis/python-language/blob/main/noxfile.py -We also explicitly decided to support Python 3 beginning with version 3.6. +We also explicitly decided to support Python 3 beginning with version 3.7. Reasons for this include: - Encouraging use of newest versions of Python 3 diff --git a/README.rst b/README.rst index 1311cd55..ba9380d5 100644 --- a/README.rst +++ b/README.rst @@ -1,35 +1,22 @@ -Python Client for Google Cloud Natural Language -=============================================== +Python Client for Natural Language API +====================================== -|GA| |pypi| |versions| +|stable| |pypi| |versions| -The `Google Cloud Natural Language`_ API can be used to reveal the -structure and meaning of text via powerful machine -learning models. You can use it to extract information about -people, places, events and much more, mentioned in text documents, -news articles or blog posts. You can use it to understand -sentiment about your product on social media or parse intent from -customer conversations happening in a call center or a messaging -app. You can analyze text uploaded in your request or integrate -with your document storage on Google Cloud Storage. +`Natural Language API`_: provides natural language understanding technologies to developers, including sentiment analysis, entity analysis, entity sentiment analysis, content classification, and syntax analysis. This API is part of the larger Cloud Machine Learning API family. - `Client Library Documentation`_ - `Product Documentation`_ -.. |GA| image:: https://img.shields.io/badge/support-GA-gold.svg - :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#general-availability +.. |stable| image:: https://img.shields.io/badge/support-stable-gold.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels .. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-language.svg :target: https://pypi.org/project/google-cloud-language/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-language.svg :target: https://pypi.org/project/google-cloud-language/ -.. _Google Cloud Natural Language: https://cloud.google.com/natural-language/ -.. _Product Documentation: https://cloud.google.com/natural-language/docs +.. _Natural Language API: https://cloud.google.com/natural-language/docs/ .. _Client Library Documentation: https://cloud.google.com/python/docs/reference/language/latest - -.. note:: - - This library currently does not run on Google App Engine Standard. - We are actively working on adding this support. +.. _Product Documentation: https://cloud.google.com/natural-language/docs/ Quick Start ----------- @@ -38,12 +25,12 @@ In order to use this library, you first need to go through the following steps: 1. `Select or create a Cloud Platform project.`_ 2. `Enable billing for your project.`_ -3. `Enable the Google Cloud Language API.`_ +3. `Enable the Natural Language API.`_ 4. `Setup Authentication.`_ .. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project .. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Enable the Google Cloud Language API.: https://cloud.google.com/natural-language +.. _Enable the Natural Language API.: https://cloud.google.com/natural-language/docs/ .. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html Installation @@ -60,15 +47,25 @@ dependencies. .. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/` folder. + + Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Python >= 3.6 +Our client libraries are compatible with all current [active](https://devguide.python.org/devcycle/#in-development-main-branch) and [maintenance](https://devguide.python.org/devcycle/#maintenance-branches) versions of +Python. + +Python >= 3.7 Unsupported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Python == 2.7. +Python <= 3.6 -The last version of this library compatible with Python 2.7 is google-cloud-language=1.3.0 +If you are using an [end-of-life](https://devguide.python.org/devcycle/#end-of-life-branches) +version of Python, we recommend that you update as soon as possible to an actively supported version. Mac/Linux @@ -92,13 +89,15 @@ Windows <your-env>\Scripts\activate <your-env>\Scripts\pip.exe install google-cloud-language - Next Steps ~~~~~~~~~~ -- Read the `Usage documentation`_ for the language client - to see available methods on the client. -- Read the `Product documentation`_ to learn +- Read the `Client Library Documentation`_ for Natural Language API + to see other available methods on the client. +- Read the `Natural Language API Product documentation`_ to learn more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. -.. _Usage documentation: https://cloud.google.com/python/docs/reference/language/latest +.. _Natural Language API Product documentation: https://cloud.google.com/natural-language/docs/ +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/noxfile.py b/noxfile.py index 5bb3c201..94b2f9c2 100644 --- a/noxfile.py +++ b/noxfile.py @@ -32,7 +32,7 @@ DEFAULT_PYTHON_VERSION = "3.8" -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] +UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", @@ -332,28 +332,15 @@ def docfx(session): def prerelease_deps(session): """Run all tests with prerelease versions of dependencies installed.""" - prerel_deps = [ - "protobuf", - "googleapis-common-protos", - "google-auth", - "grpcio", - "grpcio-status", - "google-api-core", - "proto-plus", - # dependencies of google-auth - "cryptography", - "pyasn1", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = ["requests"] - session.install(*other_deps) - + # Install all dependencies + session.install("-e", ".[all, tests, tracing]") session.install(*UNIT_TEST_STANDARD_DEPENDENCIES) - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES) + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) # Because we test minimum dependency versions on the minimum Python # version, the first version we test with in the unit tests sessions has a @@ -367,19 +354,44 @@ def prerelease_deps(session): constraints_text = constraints_file.read() # Ignore leading whitespace and comment lines. - deps = [ + constraints_deps = [ match.group(1) for match in re.finditer( r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE ) ] - # Don't overwrite prerelease packages. - deps = [dep for dep in deps if dep not in prerel_deps] - # We use --no-deps to ensure that pre-release versions aren't overwritten - # by the version ranges in setup.py. - session.install(*deps) - session.install("--no-deps", "-e", ".[all]") + session.install(*constraints_deps) + + if os.path.exists("samples/snippets/requirements.txt"): + session.install("-r", "samples/snippets/requirements.txt") + + if os.path.exists("samples/snippets/requirements-test.txt"): + session.install("-r", "samples/snippets/requirements-test.txt") + + prerel_deps = [ + "protobuf", + # dependency of grpc + "six", + "googleapis-common-protos", + "grpcio", + "grpcio-status", + "google-api-core", + "proto-plus", + "google-cloud-testutils", + # dependencies of google-cloud-testutils" + "click", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + "google-auth", + ] + session.install(*other_deps) # Print out prerelease package versions session.run( @@ -388,5 +400,16 @@ def prerelease_deps(session): session.run("python", "-c", "import grpc; print(grpc.__version__)") session.run("py.test", "tests/unit") - session.run("py.test", "tests/system") - session.run("py.test", "samples/snippets") + + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Only run system tests if found. + if os.path.exists(system_test_path) or os.path.exists(system_test_folder_path): + session.run("py.test", "tests/system") + + snippets_test_path = os.path.join("samples", "snippets") + + # Only run samples tests if found. + if os.path.exists(snippets_test_path): + session.run("py.test", "samples/snippets") diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index 3b3ffa5d..e9eb1cbf 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -88,7 +88,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] +ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index 3b3ffa5d..e9eb1cbf 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -88,7 +88,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] +ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index 3b3ffa5d..e9eb1cbf 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -88,7 +88,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] +ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index 3b3ffa5d..e9eb1cbf 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -88,7 +88,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] +ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index 3b3ffa5d..e9eb1cbf 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -88,7 +88,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to test samples. -ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] +ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst index 275d6498..6f069c6c 100644 --- a/scripts/readme-gen/templates/install_deps.tmpl.rst +++ b/scripts/readme-gen/templates/install_deps.tmpl.rst @@ -12,7 +12,7 @@ Install Dependencies .. _Python Development Environment Setup Guide: https://cloud.google.com/python/setup -#. Create a virtualenv. Samples are compatible with Python 3.6+. +#. Create a virtualenv. Samples are compatible with Python 3.7+. .. code-block:: bash diff --git a/setup.py b/setup.py index a99b46fe..98895a0a 100644 --- a/setup.py +++ b/setup.py @@ -75,7 +75,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", @@ -88,7 +87,7 @@ namespace_packages=namespaces, install_requires=dependencies, extras_require=extras, - python_requires=">=3.6", + python_requires=">=3.7", scripts=[ "scripts/fixup_language_v1_keywords.py", "scripts/fixup_language_v1beta2_keywords.py", From 592e7f85503f40373263b4d36118d6e4542f48cf Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 7 Jul 2022 14:26:11 +0000 Subject: [PATCH 168/254] fix(deps): require google-api-core >= 2.8.0 (#334) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 459095142 Source-Link: https://github.com/googleapis/googleapis/commit/4f1be992601ed740a581a32cedc4e7b6c6a27793 Source-Link: https://github.com/googleapis/googleapis-gen/commit/ae686d9cde4fc3e36d0ac02efb8643b15890c1ed Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYWU2ODZkOWNkZTRmYzNlMzZkMGFjMDJlZmI4NjQzYjE1ODkwYzFlZCJ9 feat: add audience parameter PiperOrigin-RevId: 456827138 Source-Link: https://github.com/googleapis/googleapis/commit/23f1a157189581734c7a77cddfeb7c5bc1e440ae Source-Link: https://github.com/googleapis/googleapis-gen/commit/4075a8514f676691ec156688a5bbf183aa9893ce Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDA3NWE4NTE0ZjY3NjY5MWVjMTU2Njg4YTViYmYxODNhYTk4OTNjZSJ9 --- .../services/language_service/client.py | 1 + .../language_service/transports/base.py | 16 ++++-- .../language_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + .../services/language_service/client.py | 1 + .../language_service/transports/base.py | 16 ++++-- .../language_service/transports/grpc.py | 2 + .../transports/grpc_asyncio.py | 2 + setup.py | 8 +-- testing/constraints-3.6.txt | 10 ---- testing/constraints-3.7.txt | 3 +- .../language_v1/test_language_service.py | 52 +++++++++++++++++++ .../language_v1beta2/test_language_service.py | 52 +++++++++++++++++++ 13 files changed, 138 insertions(+), 29 deletions(-) delete mode 100644 testing/constraints-3.6.txt diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 3ac67a03..89bc8b53 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -404,6 +404,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def analyze_sentiment( diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 770b217e..1ae661d7 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. if ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 5bf182e1..9349716b 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -153,6 +154,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index 06ea0290..e674a409 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -103,6 +103,7 @@ def __init__( quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -198,6 +199,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 936f1151..526359b6 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -404,6 +404,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def analyze_sentiment( diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 358e3dce..cea5272d 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. if ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index b584552e..42cf6f63 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -153,6 +154,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index f4f8e4d3..2ae5171b 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -103,6 +103,7 @@ def __init__( quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -198,6 +199,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/setup.py b/setup.py index 98895a0a..a1675cf4 100644 --- a/setup.py +++ b/setup.py @@ -28,15 +28,10 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - # NOTE: Maintainers, please do not require google-api-core>=2.x.x - # Until this issue is closed - # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", + "google-api-core[grpc] >= 2.8.0, <3.0.0dev", "proto-plus >= 1.15.0, <2.0.0dev", "protobuf >= 3.19.0, <4.0.0dev", ] -extras = {"libcst": "libcst >= 0.2.5"} - # Setup boilerplate below this line. @@ -86,7 +81,6 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - extras_require=extras, python_requires=">=3.7", scripts=[ "scripts/fixup_language_v1_keywords.py", diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt deleted file mode 100644 index 53020643..00000000 --- a/testing/constraints-3.6.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.31.5 -proto-plus==1.15.0 -libcst==0.2.5 -protobuf==3.19.0 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 53020643..6522c7ef 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -4,7 +4,6 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.31.5 +google-api-core==2.8.0 proto-plus==1.15.0 -libcst==0.2.5 protobuf==3.19.0 diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 284c208a..e6b6ecc9 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -226,6 +226,7 @@ def test_language_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -243,6 +244,7 @@ def test_language_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -260,6 +262,7 @@ def test_language_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -289,6 +292,25 @@ def test_language_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -366,6 +388,7 @@ def test_language_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -400,6 +423,7 @@ def test_language_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -422,6 +446,7 @@ def test_language_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -536,6 +561,7 @@ def test_language_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -574,6 +600,7 @@ def test_language_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -594,6 +621,7 @@ def test_language_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -632,6 +660,7 @@ def test_language_service_client_create_channel_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # test that the credentials from file are saved and used as the credentials. @@ -2074,6 +2103,28 @@ def test_language_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + ], +) +def test_language_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -2519,4 +2570,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index e625436f..0415d87d 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -226,6 +226,7 @@ def test_language_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -243,6 +244,7 @@ def test_language_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -260,6 +262,7 @@ def test_language_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -289,6 +292,25 @@ def test_language_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -366,6 +388,7 @@ def test_language_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -400,6 +423,7 @@ def test_language_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -422,6 +446,7 @@ def test_language_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -536,6 +561,7 @@ def test_language_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -574,6 +600,7 @@ def test_language_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -594,6 +621,7 @@ def test_language_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -632,6 +660,7 @@ def test_language_service_client_create_channel_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # test that the credentials from file are saved and used as the credentials. @@ -2074,6 +2103,28 @@ def test_language_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + ], +) +def test_language_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -2519,4 +2570,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) From c153b54a9d3cbad6a1f00818d6e7dbada5d12037 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 7 Jul 2022 12:03:00 -0400 Subject: [PATCH 169/254] chore(main): release 2.5.0 (#337) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 13 +++++++++++++ setup.py | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 994e9410..b1e16e7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.5.0](https://github.com/googleapis/python-language/compare/v2.4.3...v2.5.0) (2022-07-07) + + +### Features + +* add audience parameter ([592e7f8](https://github.com/googleapis/python-language/commit/592e7f85503f40373263b4d36118d6e4542f48cf)) + + +### Bug Fixes + +* **deps:** require google-api-core >= 2.8.0 ([#334](https://github.com/googleapis/python-language/issues/334)) ([592e7f8](https://github.com/googleapis/python-language/commit/592e7f85503f40373263b4d36118d6e4542f48cf)) +* require python 3.7+ ([#336](https://github.com/googleapis/python-language/issues/336)) ([b36b40f](https://github.com/googleapis/python-language/commit/b36b40f1ea7a32ccc3b99c7bb815c89cdd75ff53)) + ## [2.4.3](https://github.com/googleapis/python-language/compare/v2.4.2...v2.4.3) (2022-06-06) diff --git a/setup.py b/setup.py index a1675cf4..87ed19d6 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.4.3" +version = "2.5.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 7f296e2b2d9c8642e77cc0d9d21d11c07061205a Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Thu, 7 Jul 2022 18:31:47 +0200 Subject: [PATCH 170/254] chore(deps): update all dependencies (#329) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update all dependencies * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 4 ++-- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index e9b14cef..08c8a785 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.49.0 -google-auth==2.6.6 +google-api-python-client==2.50.0 +google-auth==2.7.0 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index d0380844..f4013916 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.4.2 +google-cloud-language==2.4.3 numpy==1.22.4; python_version > '3.7' numpy===1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 33f606ed..964e9dc4 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.2 +google-cloud-language==2.4.3 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 33f606ed..964e9dc4 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.2 +google-cloud-language==2.4.3 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 33f606ed..964e9dc4 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.2 +google-cloud-language==2.4.3 From b971d5995aad01f97ddde1caf2039ea64ae45c31 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Wed, 13 Jul 2022 13:20:05 -0400 Subject: [PATCH 171/254] fix(deps): require google-api-core>=1.32.0,>=2.8.0 (#339) * fix(deps): require google-api-core>=1.32.0,>=2.8.0 * chore: update constraints --- setup.py | 2 +- testing/constraints-3.7.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 87ed19d6..f6646df1 100644 --- a/setup.py +++ b/setup.py @@ -28,7 +28,7 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 2.8.0, <3.0.0dev", + "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.15.0, <2.0.0dev", "protobuf >= 3.19.0, <4.0.0dev", ] diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 6522c7ef..f61f150b 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -4,6 +4,6 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==2.8.0 +google-api-core==1.32.0 proto-plus==1.15.0 protobuf==3.19.0 From 8c136077214f3bb741eb13e77dee383767781489 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 13 Jul 2022 13:35:03 -0400 Subject: [PATCH 172/254] chore(main): release 2.5.1 (#340) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 7 +++++++ setup.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1e16e7c..226118e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.5.1](https://github.com/googleapis/python-language/compare/v2.5.0...v2.5.1) (2022-07-13) + + +### Bug Fixes + +* **deps:** require google-api-core>=1.32.0,>=2.8.0 ([#339](https://github.com/googleapis/python-language/issues/339)) ([b971d59](https://github.com/googleapis/python-language/commit/b971d5995aad01f97ddde1caf2039ea64ae45c31)) + ## [2.5.0](https://github.com/googleapis/python-language/compare/v2.4.3...v2.5.0) (2022-07-07) diff --git a/setup.py b/setup.py index f6646df1..5d27bfde 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.5.0" +version = "2.5.1" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From d1117f49b246e1ff42278442c8210e4aa14b1fd6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 13 Jul 2022 22:36:25 -0400 Subject: [PATCH 173/254] chore(python): allow client documentation to be customized in README (#342) Source-Link: https://github.com/googleapis/synthtool/commit/95d9289ac3dc1ca2edae06619c82fe7a24d555f1 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:c8878270182edaab99f2927969d4f700c3af265accd472c3425deedff2b7fd93 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .github/.OwlBot.lock.yaml | 4 ++-- README.rst | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 1ce60852..58fcbeee 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:e7bb19d47c13839fe8c147e50e02e8b6cf5da8edd1af8b82208cd6f66cc2829c -# created: 2022-07-05T18:31:20.838186805Z + digest: sha256:c8878270182edaab99f2927969d4f700c3af265accd472c3425deedff2b7fd93 +# created: 2022-07-14T01:58:16.015625351Z diff --git a/README.rst b/README.rst index ba9380d5..85553b43 100644 --- a/README.rst +++ b/README.rst @@ -55,18 +55,22 @@ Code samples and snippets live in the `samples/` folder. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Our client libraries are compatible with all current [active](https://devguide.python.org/devcycle/#in-development-main-branch) and [maintenance](https://devguide.python.org/devcycle/#maintenance-branches) versions of +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of Python. Python >= 3.7 +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + Unsupported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Python <= 3.6 -If you are using an [end-of-life](https://devguide.python.org/devcycle/#end-of-life-branches) +If you are using an `end-of-life`_ version of Python, we recommend that you update as soon as possible to an actively supported version. +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches Mac/Linux ^^^^^^^^^ From 4e75f0da4de72132534c4cf756c00ff1ac8d6b02 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 26 Jul 2022 00:46:15 +0000 Subject: [PATCH 174/254] chore: resolve issue with prerelease presubmit [autoapprove] (#343) Source-Link: https://github.com/googleapis/synthtool/commit/1b9ad7694e44ddb4d9844df55ff7af77b51a4435 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:9db98b055a7f8bd82351238ccaacfd3cda58cdf73012ab58b8da146368330021 --- .github/.OwlBot.lock.yaml | 4 ++-- noxfile.py | 33 ++++++++++++++++++--------------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 58fcbeee..0eb02fda 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:c8878270182edaab99f2927969d4f700c3af265accd472c3425deedff2b7fd93 -# created: 2022-07-14T01:58:16.015625351Z + digest: sha256:9db98b055a7f8bd82351238ccaacfd3cda58cdf73012ab58b8da146368330021 +# created: 2022-07-25T16:02:49.174178716Z diff --git a/noxfile.py b/noxfile.py index 94b2f9c2..cc39f3b8 100644 --- a/noxfile.py +++ b/noxfile.py @@ -334,7 +334,8 @@ def prerelease_deps(session): # Install all dependencies session.install("-e", ".[all, tests, tracing]") - session.install(*UNIT_TEST_STANDARD_DEPENDENCIES) + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) system_deps_all = ( SYSTEM_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_EXTERNAL_DEPENDENCIES @@ -363,12 +364,6 @@ def prerelease_deps(session): session.install(*constraints_deps) - if os.path.exists("samples/snippets/requirements.txt"): - session.install("-r", "samples/snippets/requirements.txt") - - if os.path.exists("samples/snippets/requirements-test.txt"): - session.install("-r", "samples/snippets/requirements-test.txt") - prerel_deps = [ "protobuf", # dependency of grpc @@ -405,11 +400,19 @@ def prerelease_deps(session): system_test_folder_path = os.path.join("tests", "system") # Only run system tests if found. - if os.path.exists(system_test_path) or os.path.exists(system_test_folder_path): - session.run("py.test", "tests/system") - - snippets_test_path = os.path.join("samples", "snippets") - - # Only run samples tests if found. - if os.path.exists(snippets_test_path): - session.run("py.test", "samples/snippets") + if os.path.exists(system_test_path): + session.run( + "py.test", + "--verbose", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if os.path.exists(system_test_folder_path): + session.run( + "py.test", + "--verbose", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) From 0ee122f7a8ab29cfa4c13cc30c9e980c67e6ffba Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 2 Aug 2022 17:05:42 +0200 Subject: [PATCH 175/254] chore(deps): update all dependencies (#344) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update all dependencies * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 4 ++-- samples/snippets/classify_text/requirements.txt | 4 ++-- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 08c8a785..9630b7ad 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.50.0 -google-auth==2.7.0 +google-api-python-client==2.55.0 +google-auth==2.9.1 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index f4013916..32c8e5a7 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.4.3 -numpy==1.22.4; python_version > '3.7' +google-cloud-language==2.5.1 +numpy==1.23.1; python_version > '3.7' numpy===1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index 964e9dc4..ed1b691c 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.3 +google-cloud-language==2.5.1 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index 964e9dc4..ed1b691c 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.3 +google-cloud-language==2.5.1 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index 964e9dc4..ed1b691c 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.4.3 +google-cloud-language==2.5.1 From 737d1abd7ee6f29b5f83289d647d0fa7a357d9e8 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Sat, 6 Aug 2022 03:21:59 +0200 Subject: [PATCH 176/254] chore(deps): update all dependencies (#346) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update all dependencies * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 9630b7ad..9f2cf41a 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.55.0 -google-auth==2.9.1 +google-auth==2.10.0 google-auth-httplib2==0.1.0 From becee41a28b0b6cab04aa2786970f3ede4180cf9 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 9 Aug 2022 17:13:10 +0200 Subject: [PATCH 177/254] chore(deps): update all dependencies (#347) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update all dependencies * revert * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Anthonios Partheniou <partheniou@google.com> Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 9f2cf41a..773c3e1e 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.55.0 +google-api-python-client==2.56.0 google-auth==2.10.0 google-auth-httplib2==0.1.0 From 6447cfae91c3afdcd1a8a8e1f878c5752d57dea2 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 9 Aug 2022 16:34:17 +0000 Subject: [PATCH 178/254] chore(deps): update actions/setup-python action to v4 [autoapprove] (#348) Source-Link: https://github.com/googleapis/synthtool/commit/8e55b327bae44b6640c7ab4be91df85fc4d6fe8a Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:c6c965a4bf40c19011b11f87dbc801a66d3a23fbc6704102be064ef31c51f1c3 --- .github/.OwlBot.lock.yaml | 4 ++-- .github/workflows/docs.yml | 4 ++-- .github/workflows/lint.yml | 2 +- .github/workflows/unittest.yml | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0eb02fda..c701359f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:9db98b055a7f8bd82351238ccaacfd3cda58cdf73012ab58b8da146368330021 -# created: 2022-07-25T16:02:49.174178716Z + digest: sha256:c6c965a4bf40c19011b11f87dbc801a66d3a23fbc6704102be064ef31c51f1c3 +# created: 2022-08-09T15:58:56.463048506Z diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b46d7305..7092a139 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -10,7 +10,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Setup Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v4 with: python-version: "3.10" - name: Install nox @@ -26,7 +26,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Setup Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v4 with: python-version: "3.10" - name: Install nox diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index f512a496..d2aee5b7 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -10,7 +10,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Setup Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v4 with: python-version: "3.10" - name: Install nox diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 5531b014..87ade4d5 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -13,7 +13,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Setup Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} - name: Install nox @@ -39,7 +39,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Setup Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v4 with: python-version: "3.10" - name: Install coverage From a9c90c3706a0108db1b0f7924d02d54c507efaf4 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Thu, 11 Aug 2022 14:54:18 -0400 Subject: [PATCH 179/254] fix(deps): allow protobuf < 5.0.0 (#349) fix(deps): require proto-plus >= 1.22.0 --- setup.py | 4 ++-- testing/constraints-3.7.txt | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 5d27bfde..d7b276be 100644 --- a/setup.py +++ b/setup.py @@ -29,8 +29,8 @@ release_status = "Development Status :: 5 - Production/Stable" dependencies = [ "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", - "proto-plus >= 1.15.0, <2.0.0dev", - "protobuf >= 3.19.0, <4.0.0dev", + "proto-plus >= 1.22.0, <2.0.0dev", + "protobuf >= 3.19.0, <5.0.0dev", ] # Setup boilerplate below this line. diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index f61f150b..810c7cb3 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -5,5 +5,5 @@ # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 google-api-core==1.32.0 -proto-plus==1.15.0 +proto-plus==1.22.0 protobuf==3.19.0 From 500048b9ee1a10dacccf5e38280ff0ab84c400dc Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 15 Aug 2022 09:55:35 -0400 Subject: [PATCH 180/254] chore(main): release 2.5.2 (#350) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 8 ++++++++ setup.py | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 226118e6..ade1bc26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.5.2](https://github.com/googleapis/python-language/compare/v2.5.1...v2.5.2) (2022-08-11) + + +### Bug Fixes + +* **deps:** allow protobuf < 5.0.0 ([#349](https://github.com/googleapis/python-language/issues/349)) ([a9c90c3](https://github.com/googleapis/python-language/commit/a9c90c3706a0108db1b0f7924d02d54c507efaf4)) +* **deps:** require proto-plus >= 1.22.0 ([a9c90c3](https://github.com/googleapis/python-language/commit/a9c90c3706a0108db1b0f7924d02d54c507efaf4)) + ## [2.5.1](https://github.com/googleapis/python-language/compare/v2.5.0...v2.5.1) (2022-07-13) diff --git a/setup.py b/setup.py index d7b276be..17866216 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.5.1" +version = "2.5.2" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From e98058854b2a43d472500f8be408bf11cc0effa5 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 16 Aug 2022 17:00:02 +0200 Subject: [PATCH 181/254] chore(deps): update dependency numpy to v1.23.2 (#352) Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/classify_text/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 32c8e5a7..d8f8d384 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ google-cloud-language==2.5.1 -numpy==1.23.1; python_version > '3.7' +numpy==1.23.2; python_version > '3.7' numpy===1.21.4; python_version == '3.7' From acdfe8119626d1e5bd25b3f4f5bfee0285661c04 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 16 Aug 2022 17:53:40 +0200 Subject: [PATCH 182/254] chore(deps): update all dependencies (#353) --- samples/snippets/api/requirements.txt | 2 +- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 773c3e1e..e018afc8 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.56.0 +google-api-python-client==2.57.0 google-auth==2.10.0 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index d8f8d384..fcb7426b 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.5.1 +google-cloud-language==2.5.2 numpy==1.23.2; python_version > '3.7' numpy===1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index ed1b691c..db52d214 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.5.1 +google-cloud-language==2.5.2 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index ed1b691c..db52d214 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.5.1 +google-cloud-language==2.5.2 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index ed1b691c..db52d214 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.5.1 +google-cloud-language==2.5.2 From 301028091a5dc1a68b2671f7350b2d6024e8d573 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 23 Aug 2022 16:29:54 +0200 Subject: [PATCH 183/254] chore(deps): update dependency google-auth to v2.11.0 (#354) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index e018afc8..c69f77e1 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.57.0 -google-auth==2.10.0 +google-auth==2.11.0 google-auth-httplib2==0.1.0 From 0961da7675f1c3452b2641db3e7a629547252a16 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 23 Aug 2022 17:45:44 +0200 Subject: [PATCH 184/254] chore(deps): update dependency google-api-python-client to v2.58.0 (#355) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index c69f77e1..fc34cff2 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.57.0 +google-api-python-client==2.58.0 google-auth==2.11.0 google-auth-httplib2==0.1.0 From 4a1e1a12134733ba1eb5c76ab77976be22a0f628 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 24 Aug 2022 15:56:16 +0000 Subject: [PATCH 185/254] chore: remove 'pip install' statements from python_library templates [autoapprove] (#356) Source-Link: https://github.com/googleapis/synthtool/commit/1f37ce74cbc4897f35c9ba5c40393b102da913b1 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:8e84e0e0d71a0d681668461bba02c9e1394c785f31a10ae3470660235b673086 --- .github/.OwlBot.lock.yaml | 4 +- .kokoro/publish-docs.sh | 4 +- .kokoro/release.sh | 5 +- .kokoro/requirements.in | 8 + .kokoro/requirements.txt | 464 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 476 insertions(+), 9 deletions(-) create mode 100644 .kokoro/requirements.in create mode 100644 .kokoro/requirements.txt diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index c701359f..1c14d7f6 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:c6c965a4bf40c19011b11f87dbc801a66d3a23fbc6704102be064ef31c51f1c3 -# created: 2022-08-09T15:58:56.463048506Z + digest: sha256:8e84e0e0d71a0d681668461bba02c9e1394c785f31a10ae3470660235b673086 +# created: 2022-08-24T15:24:05.205983455Z diff --git a/.kokoro/publish-docs.sh b/.kokoro/publish-docs.sh index 8acb14e8..1c4d6237 100755 --- a/.kokoro/publish-docs.sh +++ b/.kokoro/publish-docs.sh @@ -21,14 +21,12 @@ export PYTHONUNBUFFERED=1 export PATH="${HOME}/.local/bin:${PATH}" # Install nox -python3 -m pip install --user --upgrade --quiet nox +python3 -m pip install --require-hashes -r .kokoro/requirements.txt python3 -m nox --version # build docs nox -s docs -python3 -m pip install --user gcp-docuploader - # create metadata python3 -m docuploader create-metadata \ --name=$(jq --raw-output '.name // empty' .repo-metadata.json) \ diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 9db53208..22d735de 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -16,12 +16,9 @@ set -eo pipefail # Start the releasetool reporter -python3 -m pip install gcp-releasetool +python3 -m pip install --require-hashes -r .kokoro/requirements.txt python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script -# Ensure that we have the latest versions of Twine, Wheel, and Setuptools. -python3 -m pip install --upgrade twine wheel setuptools - # Disable buffering, so that the logs stream through. export PYTHONUNBUFFERED=1 diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in new file mode 100644 index 00000000..7718391a --- /dev/null +++ b/.kokoro/requirements.in @@ -0,0 +1,8 @@ +gcp-docuploader +gcp-releasetool +importlib-metadata +typing-extensions +twine +wheel +setuptools +nox \ No newline at end of file diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt new file mode 100644 index 00000000..c4b824f2 --- /dev/null +++ b/.kokoro/requirements.txt @@ -0,0 +1,464 @@ +# +# This file is autogenerated by pip-compile with python 3.10 +# To update, run: +# +# pip-compile --allow-unsafe --generate-hashes requirements.in +# +argcomplete==2.0.0 \ + --hash=sha256:6372ad78c89d662035101418ae253668445b391755cfe94ea52f1b9d22425b20 \ + --hash=sha256:cffa11ea77999bb0dd27bb25ff6dc142a6796142f68d45b1a26b11f58724561e + # via nox +attrs==22.1.0 \ + --hash=sha256:29adc2665447e5191d0e7c568fde78b21f9672d344281d0c6e1ab085429b22b6 \ + --hash=sha256:86efa402f67bf2df34f51a335487cf46b1ec130d02b8d39fd248abfd30da551c + # via gcp-releasetool +bleach==5.0.1 \ + --hash=sha256:085f7f33c15bd408dd9b17a4ad77c577db66d76203e5984b1bd59baeee948b2a \ + --hash=sha256:0d03255c47eb9bd2f26aa9bb7f2107732e7e8fe195ca2f64709fcf3b0a4a085c + # via readme-renderer +cachetools==5.2.0 \ + --hash=sha256:6a94c6402995a99c3970cc7e4884bb60b4a8639938157eeed436098bf9831757 \ + --hash=sha256:f9f17d2aec496a9aa6b76f53e3b614c965223c061982d434d160f930c698a9db + # via google-auth +certifi==2022.6.15 \ + --hash=sha256:84c85a9078b11105f04f3036a9482ae10e4621616db313fe045dd24743a0820d \ + --hash=sha256:fe86415d55e84719d75f8b69414f6438ac3547d2078ab91b67e779ef69378412 + # via requests +cffi==1.15.1 \ + --hash=sha256:00a9ed42e88df81ffae7a8ab6d9356b371399b91dbdf0c3cb1e84c03a13aceb5 \ + --hash=sha256:03425bdae262c76aad70202debd780501fabeaca237cdfddc008987c0e0f59ef \ + --hash=sha256:04ed324bda3cda42b9b695d51bb7d54b680b9719cfab04227cdd1e04e5de3104 \ + --hash=sha256:0e2642fe3142e4cc4af0799748233ad6da94c62a8bec3a6648bf8ee68b1c7426 \ + --hash=sha256:173379135477dc8cac4bc58f45db08ab45d228b3363adb7af79436135d028405 \ + --hash=sha256:198caafb44239b60e252492445da556afafc7d1e3ab7a1fb3f0584ef6d742375 \ + --hash=sha256:1e74c6b51a9ed6589199c787bf5f9875612ca4a8a0785fb2d4a84429badaf22a \ + --hash=sha256:2012c72d854c2d03e45d06ae57f40d78e5770d252f195b93f581acf3ba44496e \ + --hash=sha256:21157295583fe8943475029ed5abdcf71eb3911894724e360acff1d61c1d54bc \ + --hash=sha256:2470043b93ff09bf8fb1d46d1cb756ce6132c54826661a32d4e4d132e1977adf \ + --hash=sha256:285d29981935eb726a4399badae8f0ffdff4f5050eaa6d0cfc3f64b857b77185 \ + --hash=sha256:30d78fbc8ebf9c92c9b7823ee18eb92f2e6ef79b45ac84db507f52fbe3ec4497 \ + --hash=sha256:320dab6e7cb2eacdf0e658569d2575c4dad258c0fcc794f46215e1e39f90f2c3 \ + --hash=sha256:33ab79603146aace82c2427da5ca6e58f2b3f2fb5da893ceac0c42218a40be35 \ + --hash=sha256:3548db281cd7d2561c9ad9984681c95f7b0e38881201e157833a2342c30d5e8c \ + --hash=sha256:3799aecf2e17cf585d977b780ce79ff0dc9b78d799fc694221ce814c2c19db83 \ + --hash=sha256:39d39875251ca8f612b6f33e6b1195af86d1b3e60086068be9cc053aa4376e21 \ + --hash=sha256:3b926aa83d1edb5aa5b427b4053dc420ec295a08e40911296b9eb1b6170f6cca \ + --hash=sha256:3bcde07039e586f91b45c88f8583ea7cf7a0770df3a1649627bf598332cb6984 \ + --hash=sha256:3d08afd128ddaa624a48cf2b859afef385b720bb4b43df214f85616922e6a5ac \ + --hash=sha256:3eb6971dcff08619f8d91607cfc726518b6fa2a9eba42856be181c6d0d9515fd \ + --hash=sha256:40f4774f5a9d4f5e344f31a32b5096977b5d48560c5592e2f3d2c4374bd543ee \ + --hash=sha256:4289fc34b2f5316fbb762d75362931e351941fa95fa18789191b33fc4cf9504a \ + --hash=sha256:470c103ae716238bbe698d67ad020e1db9d9dba34fa5a899b5e21577e6d52ed2 \ + --hash=sha256:4f2c9f67e9821cad2e5f480bc8d83b8742896f1242dba247911072d4fa94c192 \ + --hash=sha256:50a74364d85fd319352182ef59c5c790484a336f6db772c1a9231f1c3ed0cbd7 \ + --hash=sha256:54a2db7b78338edd780e7ef7f9f6c442500fb0d41a5a4ea24fff1c929d5af585 \ + --hash=sha256:5635bd9cb9731e6d4a1132a498dd34f764034a8ce60cef4f5319c0541159392f \ + --hash=sha256:59c0b02d0a6c384d453fece7566d1c7e6b7bae4fc5874ef2ef46d56776d61c9e \ + --hash=sha256:5d598b938678ebf3c67377cdd45e09d431369c3b1a5b331058c338e201f12b27 \ + --hash=sha256:5df2768244d19ab7f60546d0c7c63ce1581f7af8b5de3eb3004b9b6fc8a9f84b \ + --hash=sha256:5ef34d190326c3b1f822a5b7a45f6c4535e2f47ed06fec77d3d799c450b2651e \ + --hash=sha256:6975a3fac6bc83c4a65c9f9fcab9e47019a11d3d2cf7f3c0d03431bf145a941e \ + --hash=sha256:6c9a799e985904922a4d207a94eae35c78ebae90e128f0c4e521ce339396be9d \ + --hash=sha256:70df4e3b545a17496c9b3f41f5115e69a4f2e77e94e1d2a8e1070bc0c38c8a3c \ + --hash=sha256:7473e861101c9e72452f9bf8acb984947aa1661a7704553a9f6e4baa5ba64415 \ + --hash=sha256:8102eaf27e1e448db915d08afa8b41d6c7ca7a04b7d73af6514df10a3e74bd82 \ + --hash=sha256:87c450779d0914f2861b8526e035c5e6da0a3199d8f1add1a665e1cbc6fc6d02 \ + --hash=sha256:8b7ee99e510d7b66cdb6c593f21c043c248537a32e0bedf02e01e9553a172314 \ + --hash=sha256:91fc98adde3d7881af9b59ed0294046f3806221863722ba7d8d120c575314325 \ + --hash=sha256:94411f22c3985acaec6f83c6df553f2dbe17b698cc7f8ae751ff2237d96b9e3c \ + --hash=sha256:98d85c6a2bef81588d9227dde12db8a7f47f639f4a17c9ae08e773aa9c697bf3 \ + --hash=sha256:9ad5db27f9cabae298d151c85cf2bad1d359a1b9c686a275df03385758e2f914 \ + --hash=sha256:a0b71b1b8fbf2b96e41c4d990244165e2c9be83d54962a9a1d118fd8657d2045 \ + --hash=sha256:a0f100c8912c114ff53e1202d0078b425bee3649ae34d7b070e9697f93c5d52d \ + --hash=sha256:a591fe9e525846e4d154205572a029f653ada1a78b93697f3b5a8f1f2bc055b9 \ + --hash=sha256:a5c84c68147988265e60416b57fc83425a78058853509c1b0629c180094904a5 \ + --hash=sha256:a66d3508133af6e8548451b25058d5812812ec3798c886bf38ed24a98216fab2 \ + --hash=sha256:a8c4917bd7ad33e8eb21e9a5bbba979b49d9a97acb3a803092cbc1133e20343c \ + --hash=sha256:b3bbeb01c2b273cca1e1e0c5df57f12dce9a4dd331b4fa1635b8bec26350bde3 \ + --hash=sha256:cba9d6b9a7d64d4bd46167096fc9d2f835e25d7e4c121fb2ddfc6528fb0413b2 \ + --hash=sha256:cc4d65aeeaa04136a12677d3dd0b1c0c94dc43abac5860ab33cceb42b801c1e8 \ + --hash=sha256:ce4bcc037df4fc5e3d184794f27bdaab018943698f4ca31630bc7f84a7b69c6d \ + --hash=sha256:cec7d9412a9102bdc577382c3929b337320c4c4c4849f2c5cdd14d7368c5562d \ + --hash=sha256:d400bfb9a37b1351253cb402671cea7e89bdecc294e8016a707f6d1d8ac934f9 \ + --hash=sha256:d61f4695e6c866a23a21acab0509af1cdfd2c013cf256bbf5b6b5e2695827162 \ + --hash=sha256:db0fbb9c62743ce59a9ff687eb5f4afbe77e5e8403d6697f7446e5f609976f76 \ + --hash=sha256:dd86c085fae2efd48ac91dd7ccffcfc0571387fe1193d33b6394db7ef31fe2a4 \ + --hash=sha256:e00b098126fd45523dd056d2efba6c5a63b71ffe9f2bbe1a4fe1716e1d0c331e \ + --hash=sha256:e229a521186c75c8ad9490854fd8bbdd9a0c9aa3a524326b55be83b54d4e0ad9 \ + --hash=sha256:e263d77ee3dd201c3a142934a086a4450861778baaeeb45db4591ef65550b0a6 \ + --hash=sha256:ed9cb427ba5504c1dc15ede7d516b84757c3e3d7868ccc85121d9310d27eed0b \ + --hash=sha256:fa6693661a4c91757f4412306191b6dc88c1703f780c8234035eac011922bc01 \ + --hash=sha256:fcd131dd944808b5bdb38e6f5b53013c5aa4f334c5cad0c72742f6eba4b73db0 + # via cryptography +charset-normalizer==2.1.1 \ + --hash=sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845 \ + --hash=sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f + # via requests +click==8.0.4 \ + --hash=sha256:6a7a62563bbfabfda3a38f3023a1db4a35978c0abd76f6c9605ecd6554d6d9b1 \ + --hash=sha256:8458d7b1287c5fb128c90e23381cf99dcde74beaf6c7ff6384ce84d6fe090adb + # via + # gcp-docuploader + # gcp-releasetool +colorlog==6.6.0 \ + --hash=sha256:344f73204009e4c83c5b6beb00b3c45dc70fcdae3c80db919e0a4171d006fde8 \ + --hash=sha256:351c51e866c86c3217f08e4b067a7974a678be78f07f85fc2d55b8babde6d94e + # via + # gcp-docuploader + # nox +commonmark==0.9.1 \ + --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ + --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 + # via rich +cryptography==37.0.4 \ + --hash=sha256:190f82f3e87033821828f60787cfa42bff98404483577b591429ed99bed39d59 \ + --hash=sha256:2be53f9f5505673eeda5f2736bea736c40f051a739bfae2f92d18aed1eb54596 \ + --hash=sha256:30788e070800fec9bbcf9faa71ea6d8068f5136f60029759fd8c3efec3c9dcb3 \ + --hash=sha256:3d41b965b3380f10e4611dbae366f6dc3cefc7c9ac4e8842a806b9672ae9add5 \ + --hash=sha256:4c590ec31550a724ef893c50f9a97a0c14e9c851c85621c5650d699a7b88f7ab \ + --hash=sha256:549153378611c0cca1042f20fd9c5030d37a72f634c9326e225c9f666d472884 \ + --hash=sha256:63f9c17c0e2474ccbebc9302ce2f07b55b3b3fcb211ded18a42d5764f5c10a82 \ + --hash=sha256:6bc95ed67b6741b2607298f9ea4932ff157e570ef456ef7ff0ef4884a134cc4b \ + --hash=sha256:7099a8d55cd49b737ffc99c17de504f2257e3787e02abe6d1a6d136574873441 \ + --hash=sha256:75976c217f10d48a8b5a8de3d70c454c249e4b91851f6838a4e48b8f41eb71aa \ + --hash=sha256:7bc997818309f56c0038a33b8da5c0bfbb3f1f067f315f9abd6fc07ad359398d \ + --hash=sha256:80f49023dd13ba35f7c34072fa17f604d2f19bf0989f292cedf7ab5770b87a0b \ + --hash=sha256:91ce48d35f4e3d3f1d83e29ef4a9267246e6a3be51864a5b7d2247d5086fa99a \ + --hash=sha256:a958c52505c8adf0d3822703078580d2c0456dd1d27fabfb6f76fe63d2971cd6 \ + --hash=sha256:b62439d7cd1222f3da897e9a9fe53bbf5c104fff4d60893ad1355d4c14a24157 \ + --hash=sha256:b7f8dd0d4c1f21759695c05a5ec8536c12f31611541f8904083f3dc582604280 \ + --hash=sha256:d204833f3c8a33bbe11eda63a54b1aad7aa7456ed769a982f21ec599ba5fa282 \ + --hash=sha256:e007f052ed10cc316df59bc90fbb7ff7950d7e2919c9757fd42a2b8ecf8a5f67 \ + --hash=sha256:f2dcb0b3b63afb6df7fd94ec6fbddac81b5492513f7b0436210d390c14d46ee8 \ + --hash=sha256:f721d1885ecae9078c3f6bbe8a88bc0786b6e749bf32ccec1ef2b18929a05046 \ + --hash=sha256:f7a6de3e98771e183645181b3627e2563dcde3ce94a9e42a3f427d2255190327 \ + --hash=sha256:f8c0a6e9e1dd3eb0414ba320f85da6b0dcbd543126e30fcc546e7372a7fbf3b9 + # via + # gcp-releasetool + # secretstorage +distlib==0.3.5 \ + --hash=sha256:a7f75737c70be3b25e2bee06288cec4e4c221de18455b2dd037fe2a795cab2fe \ + --hash=sha256:b710088c59f06338ca514800ad795a132da19fda270e3ce4affc74abf955a26c + # via virtualenv +docutils==0.19 \ + --hash=sha256:33995a6753c30b7f577febfc2c50411fec6aac7f7ffeb7c4cfe5991072dcf9e6 \ + --hash=sha256:5e1de4d849fee02c63b040a4a3fd567f4ab104defd8a5511fbbc24a8a017efbc + # via readme-renderer +filelock==3.8.0 \ + --hash=sha256:55447caa666f2198c5b6b13a26d2084d26fa5b115c00d065664b2124680c4edc \ + --hash=sha256:617eb4e5eedc82fc5f47b6d61e4d11cb837c56cb4544e39081099fa17ad109d4 + # via virtualenv +gcp-docuploader==0.6.3 \ + --hash=sha256:ba8c9d76b3bbac54b0311c503a373b00edc2dc02d6d54ea9507045adb8e870f7 \ + --hash=sha256:c0f5aaa82ce1854a386197e4e359b120ad6d4e57ae2c812fce42219a3288026b + # via -r requirements.in +gcp-releasetool==1.8.6 \ + --hash=sha256:42e51ab8e2e789bc8e22a03c09352962cd3452951c801a2230d564816630304a \ + --hash=sha256:a3518b79d1b243c494eac392a01c7fd65187fd6d52602dcab9b529bc934d4da1 + # via -r requirements.in +google-api-core==2.8.2 \ + --hash=sha256:06f7244c640322b508b125903bb5701bebabce8832f85aba9335ec00b3d02edc \ + --hash=sha256:93c6a91ccac79079ac6bbf8b74ee75db970cc899278b97d53bc012f35908cf50 + # via + # google-cloud-core + # google-cloud-storage +google-auth==2.11.0 \ + --hash=sha256:be62acaae38d0049c21ca90f27a23847245c9f161ff54ede13af2cb6afecbac9 \ + --hash=sha256:ed65ecf9f681832298e29328e1ef0a3676e3732b2e56f41532d45f70a22de0fb + # via + # gcp-releasetool + # google-api-core + # google-cloud-core + # google-cloud-storage +google-cloud-core==2.3.2 \ + --hash=sha256:8417acf6466be2fa85123441696c4badda48db314c607cf1e5d543fa8bdc22fe \ + --hash=sha256:b9529ee7047fd8d4bf4a2182de619154240df17fbe60ead399078c1ae152af9a + # via google-cloud-storage +google-cloud-storage==2.5.0 \ + --hash=sha256:19a26c66c317ce542cea0830b7e787e8dac2588b6bfa4d3fd3b871ba16305ab0 \ + --hash=sha256:382f34b91de2212e3c2e7b40ec079d27ee2e3dbbae99b75b1bcd8c63063ce235 + # via gcp-docuploader +google-crc32c==1.3.0 \ + --hash=sha256:04e7c220798a72fd0f08242bc8d7a05986b2a08a0573396187fd32c1dcdd58b3 \ + --hash=sha256:05340b60bf05b574159e9bd940152a47d38af3fb43803ffe71f11d704b7696a6 \ + --hash=sha256:12674a4c3b56b706153a358eaa1018c4137a5a04635b92b4652440d3d7386206 \ + --hash=sha256:127f9cc3ac41b6a859bd9dc4321097b1a4f6aa7fdf71b4f9227b9e3ebffb4422 \ + --hash=sha256:13af315c3a0eec8bb8b8d80b8b128cb3fcd17d7e4edafc39647846345a3f003a \ + --hash=sha256:1926fd8de0acb9d15ee757175ce7242e235482a783cd4ec711cc999fc103c24e \ + --hash=sha256:226f2f9b8e128a6ca6a9af9b9e8384f7b53a801907425c9a292553a3a7218ce0 \ + --hash=sha256:276de6273eb074a35bc598f8efbc00c7869c5cf2e29c90748fccc8c898c244df \ + --hash=sha256:318f73f5484b5671f0c7f5f63741ab020a599504ed81d209b5c7129ee4667407 \ + --hash=sha256:3bbce1be3687bbfebe29abdb7631b83e6b25da3f4e1856a1611eb21854b689ea \ + --hash=sha256:42ae4781333e331a1743445931b08ebdad73e188fd554259e772556fc4937c48 \ + --hash=sha256:58be56ae0529c664cc04a9c76e68bb92b091e0194d6e3c50bea7e0f266f73713 \ + --hash=sha256:5da2c81575cc3ccf05d9830f9e8d3c70954819ca9a63828210498c0774fda1a3 \ + --hash=sha256:6311853aa2bba4064d0c28ca54e7b50c4d48e3de04f6770f6c60ebda1e975267 \ + --hash=sha256:650e2917660e696041ab3dcd7abac160b4121cd9a484c08406f24c5964099829 \ + --hash=sha256:6a4db36f9721fdf391646685ecffa404eb986cbe007a3289499020daf72e88a2 \ + --hash=sha256:779cbf1ce375b96111db98fca913c1f5ec11b1d870e529b1dc7354b2681a8c3a \ + --hash=sha256:7f6fe42536d9dcd3e2ffb9d3053f5d05221ae3bbcefbe472bdf2c71c793e3183 \ + --hash=sha256:891f712ce54e0d631370e1f4997b3f182f3368179198efc30d477c75d1f44942 \ + --hash=sha256:95c68a4b9b7828ba0428f8f7e3109c5d476ca44996ed9a5f8aac6269296e2d59 \ + --hash=sha256:96a8918a78d5d64e07c8ea4ed2bc44354e3f93f46a4866a40e8db934e4c0d74b \ + --hash=sha256:9c3cf890c3c0ecfe1510a452a165431b5831e24160c5fcf2071f0f85ca5a47cd \ + --hash=sha256:9f58099ad7affc0754ae42e6d87443299f15d739b0ce03c76f515153a5cda06c \ + --hash=sha256:a0b9e622c3b2b8d0ce32f77eba617ab0d6768b82836391e4f8f9e2074582bf02 \ + --hash=sha256:a7f9cbea4245ee36190f85fe1814e2d7b1e5f2186381b082f5d59f99b7f11328 \ + --hash=sha256:bab4aebd525218bab4ee615786c4581952eadc16b1ff031813a2fd51f0cc7b08 \ + --hash=sha256:c124b8c8779bf2d35d9b721e52d4adb41c9bfbde45e6a3f25f0820caa9aba73f \ + --hash=sha256:c9da0a39b53d2fab3e5467329ed50e951eb91386e9d0d5b12daf593973c3b168 \ + --hash=sha256:ca60076c388728d3b6ac3846842474f4250c91efbfe5afa872d3ffd69dd4b318 \ + --hash=sha256:cb6994fff247987c66a8a4e550ef374671c2b82e3c0d2115e689d21e511a652d \ + --hash=sha256:d1c1d6236feab51200272d79b3d3e0f12cf2cbb12b208c835b175a21efdb0a73 \ + --hash=sha256:dd7760a88a8d3d705ff562aa93f8445ead54f58fd482e4f9e2bafb7e177375d4 \ + --hash=sha256:dda4d8a3bb0b50f540f6ff4b6033f3a74e8bf0bd5320b70fab2c03e512a62812 \ + --hash=sha256:e0f1ff55dde0ebcfbef027edc21f71c205845585fffe30d4ec4979416613e9b3 \ + --hash=sha256:e7a539b9be7b9c00f11ef16b55486141bc2cdb0c54762f84e3c6fc091917436d \ + --hash=sha256:eb0b14523758e37802f27b7f8cd973f5f3d33be7613952c0df904b68c4842f0e \ + --hash=sha256:ed447680ff21c14aaceb6a9f99a5f639f583ccfe4ce1a5e1d48eb41c3d6b3217 \ + --hash=sha256:f52a4ad2568314ee713715b1e2d79ab55fab11e8b304fd1462ff5cccf4264b3e \ + --hash=sha256:fbd60c6aaa07c31d7754edbc2334aef50601b7f1ada67a96eb1eb57c7c72378f \ + --hash=sha256:fc28e0db232c62ca0c3600884933178f0825c99be4474cdd645e378a10588125 \ + --hash=sha256:fe31de3002e7b08eb20823b3735b97c86c5926dd0581c7710a680b418a8709d4 \ + --hash=sha256:fec221a051150eeddfdfcff162e6db92c65ecf46cb0f7bb1bf812a1520ec026b \ + --hash=sha256:ff71073ebf0e42258a42a0b34f2c09ec384977e7f6808999102eedd5b49920e3 + # via google-resumable-media +google-resumable-media==2.3.3 \ + --hash=sha256:27c52620bd364d1c8116eaac4ea2afcbfb81ae9139fb3199652fcac1724bfb6c \ + --hash=sha256:5b52774ea7a829a8cdaa8bd2d4c3d4bc660c91b30857ab2668d0eb830f4ea8c5 + # via google-cloud-storage +googleapis-common-protos==1.56.4 \ + --hash=sha256:8eb2cbc91b69feaf23e32452a7ae60e791e09967d81d4fcc7fc388182d1bd394 \ + --hash=sha256:c25873c47279387cfdcbdafa36149887901d36202cb645a0e4f29686bf6e4417 + # via google-api-core +idna==3.3 \ + --hash=sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff \ + --hash=sha256:9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d + # via requests +importlib-metadata==4.12.0 \ + --hash=sha256:637245b8bab2b6502fcbc752cc4b7a6f6243bb02b31c5c26156ad103d3d45670 \ + --hash=sha256:7401a975809ea1fdc658c3aa4f78cc2195a0e019c5cbc4c06122884e9ae80c23 + # via + # -r requirements.in + # twine +jeepney==0.8.0 \ + --hash=sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806 \ + --hash=sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755 + # via + # keyring + # secretstorage +jinja2==3.1.2 \ + --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ + --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 + # via gcp-releasetool +keyring==23.8.2 \ + --hash=sha256:0d9973f8891850f1ade5f26aafd06bb16865fbbae3fc56b0defb6a14a2624003 \ + --hash=sha256:10d2a8639663fe2090705a00b8c47c687cacdf97598ea9c11456679fa974473a + # via + # gcp-releasetool + # twine +markupsafe==2.1.1 \ + --hash=sha256:0212a68688482dc52b2d45013df70d169f542b7394fc744c02a57374a4207003 \ + --hash=sha256:089cf3dbf0cd6c100f02945abeb18484bd1ee57a079aefd52cffd17fba910b88 \ + --hash=sha256:10c1bfff05d95783da83491be968e8fe789263689c02724e0c691933c52994f5 \ + --hash=sha256:33b74d289bd2f5e527beadcaa3f401e0df0a89927c1559c8566c066fa4248ab7 \ + --hash=sha256:3799351e2336dc91ea70b034983ee71cf2f9533cdff7c14c90ea126bfd95d65a \ + --hash=sha256:3ce11ee3f23f79dbd06fb3d63e2f6af7b12db1d46932fe7bd8afa259a5996603 \ + --hash=sha256:421be9fbf0ffe9ffd7a378aafebbf6f4602d564d34be190fc19a193232fd12b1 \ + --hash=sha256:43093fb83d8343aac0b1baa75516da6092f58f41200907ef92448ecab8825135 \ + --hash=sha256:46d00d6cfecdde84d40e572d63735ef81423ad31184100411e6e3388d405e247 \ + --hash=sha256:4a33dea2b688b3190ee12bd7cfa29d39c9ed176bda40bfa11099a3ce5d3a7ac6 \ + --hash=sha256:4b9fe39a2ccc108a4accc2676e77da025ce383c108593d65cc909add5c3bd601 \ + --hash=sha256:56442863ed2b06d19c37f94d999035e15ee982988920e12a5b4ba29b62ad1f77 \ + --hash=sha256:671cd1187ed5e62818414afe79ed29da836dde67166a9fac6d435873c44fdd02 \ + --hash=sha256:694deca8d702d5db21ec83983ce0bb4b26a578e71fbdbd4fdcd387daa90e4d5e \ + --hash=sha256:6a074d34ee7a5ce3effbc526b7083ec9731bb3cbf921bbe1d3005d4d2bdb3a63 \ + --hash=sha256:6d0072fea50feec76a4c418096652f2c3238eaa014b2f94aeb1d56a66b41403f \ + --hash=sha256:6fbf47b5d3728c6aea2abb0589b5d30459e369baa772e0f37a0320185e87c980 \ + --hash=sha256:7f91197cc9e48f989d12e4e6fbc46495c446636dfc81b9ccf50bb0ec74b91d4b \ + --hash=sha256:86b1f75c4e7c2ac2ccdaec2b9022845dbb81880ca318bb7a0a01fbf7813e3812 \ + --hash=sha256:8dc1c72a69aa7e082593c4a203dcf94ddb74bb5c8a731e4e1eb68d031e8498ff \ + --hash=sha256:8e3dcf21f367459434c18e71b2a9532d96547aef8a871872a5bd69a715c15f96 \ + --hash=sha256:8e576a51ad59e4bfaac456023a78f6b5e6e7651dcd383bcc3e18d06f9b55d6d1 \ + --hash=sha256:96e37a3dc86e80bf81758c152fe66dbf60ed5eca3d26305edf01892257049925 \ + --hash=sha256:97a68e6ada378df82bc9f16b800ab77cbf4b2fada0081794318520138c088e4a \ + --hash=sha256:99a2a507ed3ac881b975a2976d59f38c19386d128e7a9a18b7df6fff1fd4c1d6 \ + --hash=sha256:a49907dd8420c5685cfa064a1335b6754b74541bbb3706c259c02ed65b644b3e \ + --hash=sha256:b09bf97215625a311f669476f44b8b318b075847b49316d3e28c08e41a7a573f \ + --hash=sha256:b7bd98b796e2b6553da7225aeb61f447f80a1ca64f41d83612e6139ca5213aa4 \ + --hash=sha256:b87db4360013327109564f0e591bd2a3b318547bcef31b468a92ee504d07ae4f \ + --hash=sha256:bcb3ed405ed3222f9904899563d6fc492ff75cce56cba05e32eff40e6acbeaa3 \ + --hash=sha256:d4306c36ca495956b6d568d276ac11fdd9c30a36f1b6eb928070dc5360b22e1c \ + --hash=sha256:d5ee4f386140395a2c818d149221149c54849dfcfcb9f1debfe07a8b8bd63f9a \ + --hash=sha256:dda30ba7e87fbbb7eab1ec9f58678558fd9a6b8b853530e176eabd064da81417 \ + --hash=sha256:e04e26803c9c3851c931eac40c695602c6295b8d432cbe78609649ad9bd2da8a \ + --hash=sha256:e1c0b87e09fa55a220f058d1d49d3fb8df88fbfab58558f1198e08c1e1de842a \ + --hash=sha256:e72591e9ecd94d7feb70c1cbd7be7b3ebea3f548870aa91e2732960fa4d57a37 \ + --hash=sha256:e8c843bbcda3a2f1e3c2ab25913c80a3c5376cd00c6e8c4a86a89a28c8dc5452 \ + --hash=sha256:efc1913fd2ca4f334418481c7e595c00aad186563bbc1ec76067848c7ca0a933 \ + --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \ + --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7 + # via jinja2 +nox==2022.8.7 \ + --hash=sha256:1b894940551dc5c389f9271d197ca5d655d40bdc6ccf93ed6880e4042760a34b \ + --hash=sha256:96cca88779e08282a699d672258ec01eb7c792d35bbbf538c723172bce23212c + # via -r requirements.in +packaging==21.3 \ + --hash=sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb \ + --hash=sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522 + # via + # gcp-releasetool + # nox +pkginfo==1.8.3 \ + --hash=sha256:848865108ec99d4901b2f7e84058b6e7660aae8ae10164e015a6dcf5b242a594 \ + --hash=sha256:a84da4318dd86f870a9447a8c98340aa06216bfc6f2b7bdc4b8766984ae1867c + # via twine +platformdirs==2.5.2 \ + --hash=sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788 \ + --hash=sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19 + # via virtualenv +protobuf==3.20.1 \ + --hash=sha256:06059eb6953ff01e56a25cd02cca1a9649a75a7e65397b5b9b4e929ed71d10cf \ + --hash=sha256:097c5d8a9808302fb0da7e20edf0b8d4703274d140fd25c5edabddcde43e081f \ + --hash=sha256:284f86a6207c897542d7e956eb243a36bb8f9564c1742b253462386e96c6b78f \ + --hash=sha256:32ca378605b41fd180dfe4e14d3226386d8d1b002ab31c969c366549e66a2bb7 \ + --hash=sha256:3cc797c9d15d7689ed507b165cd05913acb992d78b379f6014e013f9ecb20996 \ + --hash=sha256:62f1b5c4cd6c5402b4e2d63804ba49a327e0c386c99b1675c8a0fefda23b2067 \ + --hash=sha256:69ccfdf3657ba59569c64295b7d51325f91af586f8d5793b734260dfe2e94e2c \ + --hash=sha256:6f50601512a3d23625d8a85b1638d914a0970f17920ff39cec63aaef80a93fb7 \ + --hash=sha256:7403941f6d0992d40161aa8bb23e12575637008a5a02283a930addc0508982f9 \ + --hash=sha256:755f3aee41354ae395e104d62119cb223339a8f3276a0cd009ffabfcdd46bb0c \ + --hash=sha256:77053d28427a29987ca9caf7b72ccafee011257561259faba8dd308fda9a8739 \ + --hash=sha256:7e371f10abe57cee5021797126c93479f59fccc9693dafd6bd5633ab67808a91 \ + --hash=sha256:9016d01c91e8e625141d24ec1b20fed584703e527d28512aa8c8707f105a683c \ + --hash=sha256:9be73ad47579abc26c12024239d3540e6b765182a91dbc88e23658ab71767153 \ + --hash=sha256:adc31566d027f45efe3f44eeb5b1f329da43891634d61c75a5944e9be6dd42c9 \ + --hash=sha256:adfc6cf69c7f8c50fd24c793964eef18f0ac321315439d94945820612849c388 \ + --hash=sha256:af0ebadc74e281a517141daad9d0f2c5d93ab78e9d455113719a45a49da9db4e \ + --hash=sha256:cb29edb9eab15742d791e1025dd7b6a8f6fcb53802ad2f6e3adcb102051063ab \ + --hash=sha256:cd68be2559e2a3b84f517fb029ee611546f7812b1fdd0aa2ecc9bc6ec0e4fdde \ + --hash=sha256:cdee09140e1cd184ba9324ec1df410e7147242b94b5f8b0c64fc89e38a8ba531 \ + --hash=sha256:db977c4ca738dd9ce508557d4fce0f5aebd105e158c725beec86feb1f6bc20d8 \ + --hash=sha256:dd5789b2948ca702c17027c84c2accb552fc30f4622a98ab5c51fcfe8c50d3e7 \ + --hash=sha256:e250a42f15bf9d5b09fe1b293bdba2801cd520a9f5ea2d7fb7536d4441811d20 \ + --hash=sha256:ff8d8fa42675249bb456f5db06c00de6c2f4c27a065955917b28c4f15978b9c3 + # via + # gcp-docuploader + # gcp-releasetool + # google-api-core +py==1.11.0 \ + --hash=sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719 \ + --hash=sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378 + # via nox +pyasn1==0.4.8 \ + --hash=sha256:39c7e2ec30515947ff4e87fb6f456dfc6e84857d34be479c9d4a4ba4bf46aa5d \ + --hash=sha256:aef77c9fb94a3ac588e87841208bdec464471d9871bd5050a287cc9a475cd0ba + # via + # pyasn1-modules + # rsa +pyasn1-modules==0.2.8 \ + --hash=sha256:905f84c712230b2c592c19470d3ca8d552de726050d1d1716282a1f6146be65e \ + --hash=sha256:a50b808ffeb97cb3601dd25981f6b016cbb3d31fbf57a8b8a87428e6158d0c74 + # via google-auth +pycparser==2.21 \ + --hash=sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9 \ + --hash=sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206 + # via cffi +pygments==2.13.0 \ + --hash=sha256:56a8508ae95f98e2b9bdf93a6be5ae3f7d8af858b43e02c5a2ff083726be40c1 \ + --hash=sha256:f643f331ab57ba3c9d89212ee4a2dabc6e94f117cf4eefde99a0574720d14c42 + # via + # readme-renderer + # rich +pyjwt==2.4.0 \ + --hash=sha256:72d1d253f32dbd4f5c88eaf1fdc62f3a19f676ccbadb9dbc5d07e951b2b26daf \ + --hash=sha256:d42908208c699b3b973cbeb01a969ba6a96c821eefb1c5bfe4c390c01d67abba + # via gcp-releasetool +pyparsing==3.0.9 \ + --hash=sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb \ + --hash=sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc + # via packaging +pyperclip==1.8.2 \ + --hash=sha256:105254a8b04934f0bc84e9c24eb360a591aaf6535c9def5f29d92af107a9bf57 + # via gcp-releasetool +python-dateutil==2.8.2 \ + --hash=sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86 \ + --hash=sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9 + # via gcp-releasetool +readme-renderer==37.0 \ + --hash=sha256:07b7ea234e03e58f77cc222e206e6abb8f4c0435becce5104794ee591f9301c5 \ + --hash=sha256:9fa416704703e509eeb900696751c908ddeb2011319d93700d8f18baff887a69 + # via twine +requests==2.28.1 \ + --hash=sha256:7c5599b102feddaa661c826c56ab4fee28bfd17f5abca1ebbe3e7f19d7c97983 \ + --hash=sha256:8fefa2a1a1365bf5520aac41836fbee479da67864514bdb821f31ce07ce65349 + # via + # gcp-releasetool + # google-api-core + # google-cloud-storage + # requests-toolbelt + # twine +requests-toolbelt==0.9.1 \ + --hash=sha256:380606e1d10dc85c3bd47bf5a6095f815ec007be7a8b69c878507068df059e6f \ + --hash=sha256:968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0 + # via twine +rfc3986==2.0.0 \ + --hash=sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd \ + --hash=sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c + # via twine +rich==12.5.1 \ + --hash=sha256:2eb4e6894cde1e017976d2975ac210ef515d7548bc595ba20e195fb9628acdeb \ + --hash=sha256:63a5c5ce3673d3d5fbbf23cd87e11ab84b6b451436f1b7f19ec54b6bc36ed7ca + # via twine +rsa==4.9 \ + --hash=sha256:90260d9058e514786967344d0ef75fa8727eed8a7d2e43ce9f4bcf1b536174f7 \ + --hash=sha256:e38464a49c6c85d7f1351b0126661487a7e0a14a50f1675ec50eb34d4f20ef21 + # via google-auth +secretstorage==3.3.3 \ + --hash=sha256:2403533ef369eca6d2ba81718576c5e0f564d5cca1b58f73a8b23e7d4eeebd77 \ + --hash=sha256:f356e6628222568e3af06f2eba8df495efa13b3b63081dafd4f7d9a7b7bc9f99 + # via keyring +six==1.16.0 \ + --hash=sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926 \ + --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254 + # via + # bleach + # gcp-docuploader + # google-auth + # python-dateutil +twine==4.0.1 \ + --hash=sha256:42026c18e394eac3e06693ee52010baa5313e4811d5a11050e7d48436cf41b9e \ + --hash=sha256:96b1cf12f7ae611a4a40b6ae8e9570215daff0611828f5fe1f37a16255ab24a0 + # via -r requirements.in +typing-extensions==4.3.0 \ + --hash=sha256:25642c956049920a5aa49edcdd6ab1e06d7e5d467fc00e0506c44ac86fbfca02 \ + --hash=sha256:e6d2677a32f47fc7eb2795db1dd15c1f34eff616bcaf2cfb5e997f854fa1c4a6 + # via -r requirements.in +urllib3==1.26.12 \ + --hash=sha256:3fa96cf423e6987997fc326ae8df396db2a8b7c667747d47ddd8ecba91f4a74e \ + --hash=sha256:b930dd878d5a8afb066a637fbb35144fe7901e3b209d1cd4f524bd0e9deee997 + # via + # requests + # twine +virtualenv==20.16.3 \ + --hash=sha256:4193b7bc8a6cd23e4eb251ac64f29b4398ab2c233531e66e40b19a6b7b0d30c1 \ + --hash=sha256:d86ea0bb50e06252d79e6c241507cb904fcd66090c3271381372d6221a3970f9 + # via nox +webencodings==0.5.1 \ + --hash=sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78 \ + --hash=sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923 + # via bleach +wheel==0.37.1 \ + --hash=sha256:4bdcd7d840138086126cd09254dc6195fb4fc6f01c050a1d7236f2630db1d22a \ + --hash=sha256:e9a504e793efbca1b8e0e9cb979a249cf4a0a7b5b8c9e8b65a5e39d49529c1c4 + # via -r requirements.in +zipp==3.8.1 \ + --hash=sha256:05b45f1ee8f807d0cc928485ca40a07cb491cf092ff587c0df9cb1fd154848d2 \ + --hash=sha256:47c40d7fe183a6f21403a199b3e4192cca5774656965b0a4988ad2f8feb5f009 + # via importlib-metadata + +# The following packages are considered to be unsafe in a requirements file: +setuptools==65.2.0 \ + --hash=sha256:7f4bc85450898a09f76ebf28b72fa25bc7111f6c7d665d514a60bba9c75ef2a9 \ + --hash=sha256:a3ca5857c89f82f5c9410e8508cb32f4872a3bafd4aa7ae122a24ca33bccc750 + # via -r requirements.in From 79a18da79cf4945a5991417741679b64f2402bd8 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 24 Aug 2022 19:48:17 +0000 Subject: [PATCH 186/254] chore(python): exclude path in renovate.json [autoapprove] (#359) Source-Link: https://github.com/googleapis/synthtool/commit/69fabaee9eca28af7ecaa02c86895e606fbbebd6 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:562802bfac02e012a6ac34eda282f81d06e77326b82a32d7bbb1369ff552b387 --- .github/.OwlBot.lock.yaml | 4 ++-- renovate.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 1c14d7f6..c6acdf3f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:8e84e0e0d71a0d681668461bba02c9e1394c785f31a10ae3470660235b673086 -# created: 2022-08-24T15:24:05.205983455Z + digest: sha256:562802bfac02e012a6ac34eda282f81d06e77326b82a32d7bbb1369ff552b387 +# created: 2022-08-24T17:07:22.006876712Z diff --git a/renovate.json b/renovate.json index c21036d3..566a70f3 100644 --- a/renovate.json +++ b/renovate.json @@ -5,7 +5,7 @@ ":preserveSemverRanges", ":disableDependencyDashboard" ], - "ignorePaths": [".pre-commit-config.yaml"], + "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt"], "pip_requirements": { "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] } From ec097e00ad3fd547fcae5379d769491dde18ac33 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 29 Aug 2022 18:08:30 +0000 Subject: [PATCH 187/254] chore(python): exclude grpcio==1.49.0rc1 in tests [autoapprove] (#360) Source-Link: https://github.com/googleapis/synthtool/commit/c4dd5953003d13b239f872d329c3146586bb417e Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:ce3c1686bc81145c81dd269bd12c4025c6b275b22d14641358827334fddb1d72 --- .github/.OwlBot.lock.yaml | 4 ++-- .kokoro/requirements.txt | 6 +++--- noxfile.py | 7 +++++-- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index c6acdf3f..23e106b6 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:562802bfac02e012a6ac34eda282f81d06e77326b82a32d7bbb1369ff552b387 -# created: 2022-08-24T17:07:22.006876712Z + digest: sha256:ce3c1686bc81145c81dd269bd12c4025c6b275b22d14641358827334fddb1d72 +# created: 2022-08-29T17:28:30.441852797Z diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index c4b824f2..4b29ef24 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -136,9 +136,9 @@ cryptography==37.0.4 \ # via # gcp-releasetool # secretstorage -distlib==0.3.5 \ - --hash=sha256:a7f75737c70be3b25e2bee06288cec4e4c221de18455b2dd037fe2a795cab2fe \ - --hash=sha256:b710088c59f06338ca514800ad795a132da19fda270e3ce4affc74abf955a26c +distlib==0.3.6 \ + --hash=sha256:14bad2d9b04d3a36127ac97f30b12a19268f211063d8f8ee4f47108896e11b46 \ + --hash=sha256:f35c4b692542ca110de7ef0bea44d73981caeb34ca0b9b6b2e6d7790dda8f80e # via virtualenv docutils==0.19 \ --hash=sha256:33995a6753c30b7f577febfc2c50411fec6aac7f7ffeb7c4cfe5991072dcf9e6 \ diff --git a/noxfile.py b/noxfile.py index cc39f3b8..ffe9f354 100644 --- a/noxfile.py +++ b/noxfile.py @@ -189,7 +189,9 @@ def unit(session): def install_systemtest_dependencies(session, *constraints): # Use pre-release gRPC for system tests. - session.install("--pre", "grpcio") + # Exclude version 1.49.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/pull/30642 + session.install("--pre", "grpcio!=1.49.0rc1") session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) @@ -369,7 +371,8 @@ def prerelease_deps(session): # dependency of grpc "six", "googleapis-common-protos", - "grpcio", + # Exclude version 1.49.0rc1 which has a known issue. See https://github.com/grpc/grpc/pull/30642 + "grpcio!=1.49.0rc1", "grpcio-status", "google-api-core", "proto-plus", From 7c1c6faeab2db991dd1d611dfff31ac9ce08f64b Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 1 Sep 2022 19:16:14 +0000 Subject: [PATCH 188/254] ci(python): fix path to requirements.txt in release script (#361) Source-Link: https://github.com/googleapis/synthtool/commit/fdba3ed145bdb2f4f3eff434d4284b1d03b80d34 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:1f0dbd02745fb7cf255563dab5968345989308544e52b7f460deadd5e78e63b0 --- .github/.OwlBot.lock.yaml | 3 +-- .kokoro/release.sh | 2 +- .kokoro/requirements.txt | 24 ++++++++++++------------ 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 23e106b6..0d9eb2af 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ce3c1686bc81145c81dd269bd12c4025c6b275b22d14641358827334fddb1d72 -# created: 2022-08-29T17:28:30.441852797Z + digest: sha256:1f0dbd02745fb7cf255563dab5968345989308544e52b7f460deadd5e78e63b0 diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 22d735de..02cc73b0 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -16,7 +16,7 @@ set -eo pipefail # Start the releasetool reporter -python3 -m pip install --require-hashes -r .kokoro/requirements.txt +python3 -m pip install --require-hashes -r github/python-language/.kokoro/requirements.txt python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script # Disable buffering, so that the logs stream through. diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 4b29ef24..92b2f727 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -100,9 +100,9 @@ click==8.0.4 \ # via # gcp-docuploader # gcp-releasetool -colorlog==6.6.0 \ - --hash=sha256:344f73204009e4c83c5b6beb00b3c45dc70fcdae3c80db919e0a4171d006fde8 \ - --hash=sha256:351c51e866c86c3217f08e4b067a7974a678be78f07f85fc2d55b8babde6d94e +colorlog==6.7.0 \ + --hash=sha256:0d33ca236784a1ba3ff9c532d4964126d8a2c44f1f0cb1d2b0728196f512f662 \ + --hash=sha256:bd94bd21c1e13fac7bd3153f4bc3a7dc0eb0974b8bc2fdf1a989e474f6e582e5 # via # gcp-docuploader # nox @@ -152,9 +152,9 @@ gcp-docuploader==0.6.3 \ --hash=sha256:ba8c9d76b3bbac54b0311c503a373b00edc2dc02d6d54ea9507045adb8e870f7 \ --hash=sha256:c0f5aaa82ce1854a386197e4e359b120ad6d4e57ae2c812fce42219a3288026b # via -r requirements.in -gcp-releasetool==1.8.6 \ - --hash=sha256:42e51ab8e2e789bc8e22a03c09352962cd3452951c801a2230d564816630304a \ - --hash=sha256:a3518b79d1b243c494eac392a01c7fd65187fd6d52602dcab9b529bc934d4da1 +gcp-releasetool==1.8.7 \ + --hash=sha256:3d2a67c9db39322194afb3b427e9cb0476ce8f2a04033695f0aeb63979fc2b37 \ + --hash=sha256:5e4d28f66e90780d77f3ecf1e9155852b0c3b13cbccb08ab07e66b2357c8da8d # via -r requirements.in google-api-core==2.8.2 \ --hash=sha256:06f7244c640322b508b125903bb5701bebabce8832f85aba9335ec00b3d02edc \ @@ -251,9 +251,9 @@ jinja2==3.1.2 \ --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 # via gcp-releasetool -keyring==23.8.2 \ - --hash=sha256:0d9973f8891850f1ade5f26aafd06bb16865fbbae3fc56b0defb6a14a2624003 \ - --hash=sha256:10d2a8639663fe2090705a00b8c47c687cacdf97598ea9c11456679fa974473a +keyring==23.9.0 \ + --hash=sha256:4c32a31174faaee48f43a7e2c7e9c3216ec5e95acf22a2bebfb4a1d05056ee44 \ + --hash=sha256:98f060ec95ada2ab910c195a2d4317be6ef87936a766b239c46aa3c7aac4f0db # via # gcp-releasetool # twine @@ -440,9 +440,9 @@ urllib3==1.26.12 \ # via # requests # twine -virtualenv==20.16.3 \ - --hash=sha256:4193b7bc8a6cd23e4eb251ac64f29b4398ab2c233531e66e40b19a6b7b0d30c1 \ - --hash=sha256:d86ea0bb50e06252d79e6c241507cb904fcd66090c3271381372d6221a3970f9 +virtualenv==20.16.4 \ + --hash=sha256:014f766e4134d0008dcaa1f95bafa0fb0f575795d07cae50b1bee514185d6782 \ + --hash=sha256:035ed57acce4ac35c82c9d8802202b0e71adac011a511ff650cbcf9635006a22 # via nox webencodings==0.5.1 \ --hash=sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78 \ From de9fd19acd99582f28c72368e9d337c829eb276a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 2 Sep 2022 00:46:29 +0000 Subject: [PATCH 189/254] chore(python): update .kokoro/requirements.txt (#362) Source-Link: https://github.com/googleapis/synthtool/commit/703554a14c7479542335b62fa69279f93a9e38ec Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:94961fdc5c9ca6d13530a6a414a49d2f607203168215d074cdb0a1df9ec31c0b --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/requirements.txt | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0d9eb2af..2fa0f7c4 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:1f0dbd02745fb7cf255563dab5968345989308544e52b7f460deadd5e78e63b0 + digest: sha256:94961fdc5c9ca6d13530a6a414a49d2f607203168215d074cdb0a1df9ec31c0b diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 92b2f727..385f2d4d 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -241,6 +241,10 @@ importlib-metadata==4.12.0 \ # via # -r requirements.in # twine +jaraco-classes==3.2.2 \ + --hash=sha256:6745f113b0b588239ceb49532aa09c3ebb947433ce311ef2f8e3ad64ebb74594 \ + --hash=sha256:e6ef6fd3fcf4579a7a019d87d1e56a883f4e4c35cfe925f86731abc58804e647 + # via keyring jeepney==0.8.0 \ --hash=sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806 \ --hash=sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755 @@ -299,6 +303,10 @@ markupsafe==2.1.1 \ --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \ --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7 # via jinja2 +more-itertools==8.14.0 \ + --hash=sha256:1bc4f91ee5b1b31ac7ceacc17c09befe6a40a503907baf9c839c229b5095cfd2 \ + --hash=sha256:c09443cd3d5438b8dafccd867a6bc1cb0894389e90cb53d227456b0b0bccb750 + # via jaraco-classes nox==2022.8.7 \ --hash=sha256:1b894940551dc5c389f9271d197ca5d655d40bdc6ccf93ed6880e4042760a34b \ --hash=sha256:96cca88779e08282a699d672258ec01eb7c792d35bbbf538c723172bce23212c From e6271ddab6b0f5df1fdf10018cf4b53d79487d5c Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 2 Sep 2022 18:50:22 +0000 Subject: [PATCH 190/254] chore(python): exclude setup.py in renovate config (#365) Source-Link: https://github.com/googleapis/synthtool/commit/56da63e80c384a871356d1ea6640802017f213b4 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:993a058718e84a82fda04c3177e58f0a43281a996c7c395e0a56ccc4d6d210d7 --- .github/.OwlBot.lock.yaml | 2 +- renovate.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 2fa0f7c4..b8dcb4a4 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:94961fdc5c9ca6d13530a6a414a49d2f607203168215d074cdb0a1df9ec31c0b + digest: sha256:993a058718e84a82fda04c3177e58f0a43281a996c7c395e0a56ccc4d6d210d7 diff --git a/renovate.json b/renovate.json index 566a70f3..39b2a0ec 100644 --- a/renovate.json +++ b/renovate.json @@ -5,7 +5,7 @@ ":preserveSemverRanges", ":disableDependencyDashboard" ], - "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt"], + "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt", "setup.py"], "pip_requirements": { "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] } From 9d9e98d29b72d2d40b8c4524ea81d8316a174bf7 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 6 Sep 2022 17:41:18 +0200 Subject: [PATCH 191/254] chore(deps): update dependency pytest to v7.1.3 (#366) --- samples/snippets/api/requirements-test.txt | 2 +- samples/snippets/classify_text/requirements-test.txt | 2 +- samples/snippets/cloud-client/v1/requirements-test.txt | 2 +- samples/snippets/generated-samples/v1/requirements-test.txt | 2 +- samples/snippets/sentiment/requirements-test.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt index d00689e0..e0716850 100644 --- a/samples/snippets/api/requirements-test.txt +++ b/samples/snippets/api/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.2 +pytest==7.1.3 diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt index d00689e0..e0716850 100644 --- a/samples/snippets/classify_text/requirements-test.txt +++ b/samples/snippets/classify_text/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.2 +pytest==7.1.3 diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt index d00689e0..e0716850 100644 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ b/samples/snippets/cloud-client/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.2 +pytest==7.1.3 diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt index d00689e0..e0716850 100644 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ b/samples/snippets/generated-samples/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.2 +pytest==7.1.3 diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt index d00689e0..e0716850 100644 --- a/samples/snippets/sentiment/requirements-test.txt +++ b/samples/snippets/sentiment/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.2 +pytest==7.1.3 From bcf2e69e712b1ce5e79650909cfe3b26c6231c95 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 6 Sep 2022 21:36:36 +0200 Subject: [PATCH 192/254] chore(deps): update dependency google-api-python-client to v2.60.0 (#367) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index fc34cff2..0304f99b 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.58.0 +google-api-python-client==2.60.0 google-auth==2.11.0 google-auth-httplib2==0.1.0 From f3d849df05f752160d798c270b4f09916f23f50e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 7 Sep 2022 14:14:23 +0000 Subject: [PATCH 193/254] chore: Bump gapic-generator-python version to 1.3.0 (#368) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 472561635 Source-Link: https://github.com/googleapis/googleapis/commit/332ecf599f8e747d8d1213b77ae7db26eff12814 Source-Link: https://github.com/googleapis/googleapis-gen/commit/4313d682880fd9d7247291164d4e9d3d5bd9f177 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDMxM2Q2ODI4ODBmZDlkNzI0NzI5MTE2NGQ0ZTlkM2Q1YmQ5ZjE3NyJ9 --- .../services/language_service/async_client.py | 42 +++ .../services/language_service/client.py | 42 +++ .../services/language_service/async_client.py | 42 +++ .../services/language_service/client.py | 42 +++ mypy.ini | 2 +- ...language_service_analyze_entities_async.py | 7 + ..._language_service_analyze_entities_sync.py | 7 + ..._service_analyze_entity_sentiment_async.py | 7 + ...e_service_analyze_entity_sentiment_sync.py | 7 + ...anguage_service_analyze_sentiment_async.py | 7 + ...language_service_analyze_sentiment_sync.py | 7 + ...d_language_service_analyze_syntax_async.py | 7 + ...ed_language_service_analyze_syntax_sync.py | 7 + ...ed_language_service_annotate_text_async.py | 7 + ...ted_language_service_annotate_text_sync.py | 7 + ...ed_language_service_classify_text_async.py | 7 + ...ted_language_service_classify_text_sync.py | 7 + ...language_service_analyze_entities_async.py | 7 + ..._language_service_analyze_entities_sync.py | 7 + ..._service_analyze_entity_sentiment_async.py | 7 + ...e_service_analyze_entity_sentiment_sync.py | 7 + ...anguage_service_analyze_sentiment_async.py | 7 + ...language_service_analyze_sentiment_sync.py | 7 + ...d_language_service_analyze_syntax_async.py | 7 + ...ed_language_service_analyze_syntax_sync.py | 7 + ...ed_language_service_annotate_text_async.py | 7 + ...ted_language_service_annotate_text_sync.py | 7 + ...ed_language_service_classify_text_async.py | 7 + ...ted_language_service_classify_text_sync.py | 7 + .../snippet_metadata_language_v1.json | 240 +++++++++--------- .../snippet_metadata_language_v1beta2.json | 240 +++++++++--------- 31 files changed, 577 insertions(+), 241 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 3c778545..9657c9ed 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -216,6 +216,13 @@ async def analyze_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 async def sample_analyze_sentiment(): @@ -329,6 +336,13 @@ async def analyze_entities( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 async def sample_analyze_entities(): @@ -439,6 +453,13 @@ async def analyze_entity_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 async def sample_analyze_entity_sentiment(): @@ -551,6 +572,13 @@ async def analyze_syntax( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 async def sample_analyze_syntax(): @@ -657,6 +685,13 @@ async def classify_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 async def sample_classify_text(): @@ -761,6 +796,13 @@ async def annotate_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 async def sample_annotate_text(): diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 89bc8b53..e19359b8 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -421,6 +421,13 @@ def analyze_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 def sample_analyze_sentiment(): @@ -524,6 +531,13 @@ def analyze_entities( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 def sample_analyze_entities(): @@ -624,6 +638,13 @@ def analyze_entity_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 def sample_analyze_entity_sentiment(): @@ -726,6 +747,13 @@ def analyze_syntax( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 def sample_analyze_syntax(): @@ -822,6 +850,13 @@ def classify_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 def sample_classify_text(): @@ -916,6 +951,13 @@ def annotate_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 def sample_annotate_text(): diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 52542d57..9eadd09c 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -216,6 +216,13 @@ async def analyze_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 async def sample_analyze_sentiment(): @@ -330,6 +337,13 @@ async def analyze_entities( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 async def sample_analyze_entities(): @@ -440,6 +454,13 @@ async def analyze_entity_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 async def sample_analyze_entity_sentiment(): @@ -552,6 +573,13 @@ async def analyze_syntax( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 async def sample_analyze_syntax(): @@ -658,6 +686,13 @@ async def classify_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 async def sample_classify_text(): @@ -762,6 +797,13 @@ async def annotate_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 async def sample_annotate_text(): diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 526359b6..d6b37867 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -421,6 +421,13 @@ def analyze_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 def sample_analyze_sentiment(): @@ -525,6 +532,13 @@ def analyze_entities( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 def sample_analyze_entities(): @@ -625,6 +639,13 @@ def analyze_entity_sentiment( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 def sample_analyze_entity_sentiment(): @@ -727,6 +748,13 @@ def analyze_syntax( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 def sample_analyze_syntax(): @@ -823,6 +851,13 @@ def classify_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 def sample_classify_text(): @@ -917,6 +952,13 @@ def annotate_text( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 def sample_annotate_text(): diff --git a/mypy.ini b/mypy.ini index 4505b485..574c5aed 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,3 +1,3 @@ [mypy] -python_version = 3.6 +python_version = 3.7 namespace_packages = True diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py index 32be0c31..71f2d049 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeEntities_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py index 4321949c..14beb557 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeEntities_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py index ed70384b..a8a1b59b 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeEntitySentiment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py index 59315468..c6d27ac8 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py index 2391f11c..6b65f274 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeSentiment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py index c588371f..c9a48df7 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeSentiment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py index ea004078..31640e52 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeSyntax_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py index 01df9c51..947613db 100644 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnalyzeSyntax_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py index 0edccb1a..02a54aee 100644 --- a/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnnotateText_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py index 2ccfc4dd..9d90a0f0 100644 --- a/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_AnnotateText_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py index 1ceb7247..a6497c09 100644 --- a/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py +++ b/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_ClassifyText_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py index 335d74a1..e1d32646 100644 --- a/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py +++ b/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py @@ -24,6 +24,13 @@ # [START language_v1_generated_LanguageService_ClassifyText_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py index f69b7fbd..ef2d4a6d 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeEntities_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py index 77dc2c4f..b8c2694b 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeEntities_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py index ec6b1a8e..818d4209 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py index 74815762..cabc3ff5 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py index bea0b0d8..b60e606a 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeSentiment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py index 55031f69..df735913 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py index 481b9d99..e42a0728 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeSyntax_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py index 73d34c96..f9ed77cc 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py index fc3619c5..5b17e2b1 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnnotateText_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py index ac8a7636..701c94e5 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_AnnotateText_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py index 72d76f60..94b5ebcc 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_ClassifyText_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py index 9d000fc2..f9415093 100644 --- a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py +++ b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py @@ -24,6 +24,13 @@ # [START language_v1beta2_generated_LanguageService_ClassifyText_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import language_v1beta2 diff --git a/samples/generated_samples/snippet_metadata_language_v1.json b/samples/generated_samples/snippet_metadata_language_v1.json index c1e4dd61..f633a498 100644 --- a/samples/generated_samples/snippet_metadata_language_v1.json +++ b/samples/generated_samples/snippet_metadata_language_v1.json @@ -63,33 +63,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -147,33 +147,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -232,33 +232,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -316,33 +316,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -401,33 +401,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -485,33 +485,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -570,33 +570,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -654,33 +654,33 @@ "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -743,33 +743,33 @@ "regionTag": "language_v1_generated_LanguageService_AnnotateText_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -831,33 +831,33 @@ "regionTag": "language_v1_generated_LanguageService_AnnotateText_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -912,33 +912,33 @@ "regionTag": "language_v1_generated_LanguageService_ClassifyText_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -992,33 +992,33 @@ "regionTag": "language_v1_generated_LanguageService_ClassifyText_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], diff --git a/samples/generated_samples/snippet_metadata_language_v1beta2.json b/samples/generated_samples/snippet_metadata_language_v1beta2.json index bf3a59ca..2184122a 100644 --- a/samples/generated_samples/snippet_metadata_language_v1beta2.json +++ b/samples/generated_samples/snippet_metadata_language_v1beta2.json @@ -63,33 +63,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -147,33 +147,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -232,33 +232,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -316,33 +316,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -401,33 +401,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -485,33 +485,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -570,33 +570,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -654,33 +654,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -743,33 +743,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -831,33 +831,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -912,33 +912,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_async", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -992,33 +992,33 @@ "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_sync", "segments": [ { - "end": 47, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 54, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 41, - "start": 34, + "end": 48, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 42, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], From 3d7ceb8c496aa3ffa95543ddeed58a3cca78e1f1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 8 Sep 2022 13:54:25 +0000 Subject: [PATCH 194/254] chore: use gapic-generator-python 1.3.1 (#369) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 472772457 Source-Link: https://github.com/googleapis/googleapis/commit/855b74d203deeb0f7a0215f9454cdde62a1f9b86 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b64b1e7da3e138f15ca361552ef0545e54891b4f Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjY0YjFlN2RhM2UxMzhmMTVjYTM2MTU1MmVmMDU0NWU1NDg5MWI0ZiJ9 --- tests/unit/gapic/language_v1/test_language_service.py | 4 ++-- tests/unit/gapic/language_v1beta2/test_language_service.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index e6b6ecc9..80d385a2 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -18,8 +18,8 @@ # try/except added for compatibility with python < 3.8 try: from unittest import mock - from unittest.mock import AsyncMock -except ImportError: + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER import mock import math diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 0415d87d..b7c5e814 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -18,8 +18,8 @@ # try/except added for compatibility with python < 3.8 try: from unittest import mock - from unittest.mock import AsyncMock -except ImportError: + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER import mock import math From cbf83f9beeb3cdb9a5794f9cc42a1aa8d1b9ca11 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Mon, 12 Sep 2022 16:43:52 +0200 Subject: [PATCH 195/254] chore(deps): update dependency numpy to v1.23.3 (#370) --- samples/snippets/classify_text/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index fcb7426b..954099ff 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ google-cloud-language==2.5.2 -numpy==1.23.2; python_version > '3.7' +numpy==1.23.3; python_version > '3.7' numpy===1.21.4; python_version == '3.7' From fda4821144e890832d34a03b0ea1093bfdddd507 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 13 Sep 2022 10:39:26 -0400 Subject: [PATCH 196/254] chore: use gapic generator python 1.4.1 (#371) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: integrate gapic-generator-python-1.4.1 and enable more py_test targets PiperOrigin-RevId: 473833416 Source-Link: https://github.com/googleapis/googleapis/commit/565a5508869557a3228b871101e4e4ebd8f93d11 Source-Link: https://github.com/googleapis/googleapis-gen/commit/1ee1a06c6de3ca8b843572c1fde0548f84236989 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMWVlMWEwNmM2ZGUzY2E4Yjg0MzU3MmMxZmRlMDU0OGY4NDIzNjk4OSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- tests/unit/gapic/language_v1/test_language_service.py | 1 + tests/unit/gapic/language_v1beta2/test_language_service.py | 1 + 2 files changed, 2 insertions(+) diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 80d385a2..2e656801 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -33,6 +33,7 @@ from google.oauth2 import service_account import grpc from grpc.experimental import aio +from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index b7c5e814..ae913b69 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -33,6 +33,7 @@ from google.oauth2 import service_account import grpc from grpc.experimental import aio +from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest From f5e22723e7aba94d1d16e32ff85c5be55eaf9298 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 13 Sep 2022 16:18:28 +0000 Subject: [PATCH 197/254] chore: detect samples tests in nested directories (#372) Source-Link: https://github.com/googleapis/synthtool/commit/50db768f450a50d7c1fd62513c113c9bb96fd434 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:e09366bdf0fd9c8976592988390b24d53583dd9f002d476934da43725adbb978 --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 6 ++++-- samples/snippets/classify_text/noxfile.py | 6 ++++-- samples/snippets/cloud-client/v1/noxfile.py | 6 ++++-- samples/snippets/generated-samples/v1/noxfile.py | 6 ++++-- samples/snippets/sentiment/noxfile.py | 6 ++++-- 6 files changed, 21 insertions(+), 11 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index b8dcb4a4..aa547962 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:993a058718e84a82fda04c3177e58f0a43281a996c7c395e0a56ccc4d6d210d7 + digest: sha256:e09366bdf0fd9c8976592988390b24d53583dd9f002d476934da43725adbb978 diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index e9eb1cbf..c1715136 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -207,8 +207,10 @@ def _session_tests( session: nox.sessions.Session, post_install: Callable = None ) -> None: # check for presence of tests - test_list = glob.glob("*_test.py") + glob.glob("test_*.py") - test_list.extend(glob.glob("tests")) + test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( + "**/test_*.py", recursive=True + ) + test_list.extend(glob.glob("**/tests", recursive=True)) if len(test_list) == 0: print("No tests found, skipping directory.") diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index e9eb1cbf..c1715136 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -207,8 +207,10 @@ def _session_tests( session: nox.sessions.Session, post_install: Callable = None ) -> None: # check for presence of tests - test_list = glob.glob("*_test.py") + glob.glob("test_*.py") - test_list.extend(glob.glob("tests")) + test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( + "**/test_*.py", recursive=True + ) + test_list.extend(glob.glob("**/tests", recursive=True)) if len(test_list) == 0: print("No tests found, skipping directory.") diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index e9eb1cbf..c1715136 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -207,8 +207,10 @@ def _session_tests( session: nox.sessions.Session, post_install: Callable = None ) -> None: # check for presence of tests - test_list = glob.glob("*_test.py") + glob.glob("test_*.py") - test_list.extend(glob.glob("tests")) + test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( + "**/test_*.py", recursive=True + ) + test_list.extend(glob.glob("**/tests", recursive=True)) if len(test_list) == 0: print("No tests found, skipping directory.") diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index e9eb1cbf..c1715136 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -207,8 +207,10 @@ def _session_tests( session: nox.sessions.Session, post_install: Callable = None ) -> None: # check for presence of tests - test_list = glob.glob("*_test.py") + glob.glob("test_*.py") - test_list.extend(glob.glob("tests")) + test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( + "**/test_*.py", recursive=True + ) + test_list.extend(glob.glob("**/tests", recursive=True)) if len(test_list) == 0: print("No tests found, skipping directory.") diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index e9eb1cbf..c1715136 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -207,8 +207,10 @@ def _session_tests( session: nox.sessions.Session, post_install: Callable = None ) -> None: # check for presence of tests - test_list = glob.glob("*_test.py") + glob.glob("test_*.py") - test_list.extend(glob.glob("tests")) + test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( + "**/test_*.py", recursive=True + ) + test_list.extend(glob.glob("**/tests", recursive=True)) if len(test_list) == 0: print("No tests found, skipping directory.") From b82cf8d4481cabf7b1bafa35c3c83c0b0539aa91 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 14 Sep 2022 15:54:19 +0200 Subject: [PATCH 198/254] chore(deps): update dependency google-api-python-client to v2.61.0 (#373) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 0304f99b..6328b5f1 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.60.0 +google-api-python-client==2.61.0 google-auth==2.11.0 google-auth-httplib2==0.1.0 From 0a0910418bc34aa19925c426bd90512930fa978f Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 20 Sep 2022 13:40:47 +0200 Subject: [PATCH 199/254] chore(deps): update dependency google-auth to v2.11.1 (#374) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 6328b5f1..30939e16 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.61.0 -google-auth==2.11.0 +google-auth==2.11.1 google-auth-httplib2==0.1.0 From 752e6b95f1f89fc00e84102f0e2c787053542157 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 20 Sep 2022 13:51:02 +0200 Subject: [PATCH 200/254] chore(deps): update dependency google-api-python-client to v2.62.0 (#375) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 30939e16..3b659116 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.61.0 +google-api-python-client==2.62.0 google-auth==2.11.1 google-auth-httplib2==0.1.0 From 3ba5c568179b04326ef9cc9874f2d18da99e51d6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 26 Sep 2022 10:45:29 -0400 Subject: [PATCH 201/254] feat: Add support for V1 and V2 classification models (#376) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Add support for V1 and V2 classification models for the V1 API PiperOrigin-RevId: 475599241 Source-Link: https://github.com/googleapis/googleapis/commit/05b99f982df9837c294ea3475a571a9252c68326 Source-Link: https://github.com/googleapis/googleapis-gen/commit/3dcdbed8d968f634be0a2d3107237d232ee8b061 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiM2RjZGJlZDhkOTY4ZjYzNGJlMGEyZDMxMDcyMzdkMjMyZWU4YjA2MSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * feat: Add support for V1 and V2 classification models for the V1Beta2 API PiperOrigin-RevId: 475604619 Source-Link: https://github.com/googleapis/googleapis/commit/044a15c14b1a1939684ad271c13ac84c5ac6a2c7 Source-Link: https://github.com/googleapis/googleapis-gen/commit/410020af934c7248f7804770d6f8ec4571bfa551 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDEwMDIwYWY5MzRjNzI0OGY3ODA0NzcwZDZmOGVjNDU3MWJmYTU1MSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * docs: fix docstring formatting Committer: @parthea PiperOrigin-RevId: 476410563 Source-Link: https://github.com/googleapis/googleapis/commit/7f579ee5968051f12c86a2ea50bcdeb1fbd5df94 Source-Link: https://github.com/googleapis/googleapis-gen/commit/ae0240e097a196c070e15deaae66464b42c8e014 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYWUwMjQwZTA5N2ExOTZjMDcwZTE1ZGVhYWU2NjQ2NGI0MmM4ZTAxNCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- google/cloud/language/__init__.py | 2 + google/cloud/language_v1/__init__.py | 2 + .../services/language_service/async_client.py | 14 +-- .../services/language_service/client.py | 14 +-- google/cloud/language_v1/types/__init__.py | 2 + .../language_v1/types/language_service.py | 96 +++++++++++++-- google/cloud/language_v1beta2/__init__.py | 2 + .../services/language_service/async_client.py | 2 +- .../services/language_service/client.py | 2 +- .../language_service/transports/grpc.py | 2 +- .../transports/grpc_asyncio.py | 2 +- .../cloud/language_v1beta2/types/__init__.py | 2 + .../types/language_service.py | 109 +++++++++++++++++- scripts/fixup_language_v1_keywords.py | 2 +- scripts/fixup_language_v1beta2_keywords.py | 2 +- 15 files changed, 227 insertions(+), 28 deletions(-) diff --git a/google/cloud/language/__init__.py b/google/cloud/language/__init__.py index 60d1431a..74c4351e 100644 --- a/google/cloud/language/__init__.py +++ b/google/cloud/language/__init__.py @@ -32,6 +32,7 @@ AnnotateTextRequest, AnnotateTextResponse, ClassificationCategory, + ClassificationModelOptions, ClassifyTextRequest, ClassifyTextResponse, DependencyEdge, @@ -60,6 +61,7 @@ "AnnotateTextRequest", "AnnotateTextResponse", "ClassificationCategory", + "ClassificationModelOptions", "ClassifyTextRequest", "ClassifyTextResponse", "DependencyEdge", diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py index 9e99392d..acafe86d 100644 --- a/google/cloud/language_v1/__init__.py +++ b/google/cloud/language_v1/__init__.py @@ -27,6 +27,7 @@ AnnotateTextRequest, AnnotateTextResponse, ClassificationCategory, + ClassificationModelOptions, ClassifyTextRequest, ClassifyTextResponse, DependencyEdge, @@ -54,6 +55,7 @@ "AnnotateTextRequest", "AnnotateTextResponse", "ClassificationCategory", + "ClassificationModelOptions", "ClassifyTextRequest", "ClassifyTextResponse", "DependencyEdge", diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 9657c9ed..6a7f7172 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -248,7 +248,7 @@ async def sample_analyze_sentiment(): The request object. The sentiment analysis request message. document (:class:`google.cloud.language_v1.types.Document`): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -367,7 +367,7 @@ async def sample_analyze_entities(): request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. document (:class:`google.cloud.language_v1.types.Document`): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -485,7 +485,7 @@ async def sample_analyze_entity_sentiment(): The request object. The entity-level sentiment analysis request message. document (:class:`google.cloud.language_v1.types.Document`): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -603,7 +603,7 @@ async def sample_analyze_syntax(): request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. document (:class:`google.cloud.language_v1.types.Document`): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -717,7 +717,7 @@ async def sample_classify_text(): The request object. The document classification request message. document (:class:`google.cloud.language_v1.types.Document`): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -829,12 +829,12 @@ async def sample_annotate_text(): annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. document (:class:`google.cloud.language_v1.types.Document`): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. features (:class:`google.cloud.language_v1.types.AnnotateTextRequest.Features`): - The enabled features. + Required. The enabled features. This corresponds to the ``features`` field on the ``request`` instance; if ``request`` is provided, this should not be set. diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index e19359b8..9b67ea6a 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -453,7 +453,7 @@ def sample_analyze_sentiment(): The request object. The sentiment analysis request message. document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -562,7 +562,7 @@ def sample_analyze_entities(): request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): The request object. The entity analysis request message. document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -670,7 +670,7 @@ def sample_analyze_entity_sentiment(): The request object. The entity-level sentiment analysis request message. document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -778,7 +778,7 @@ def sample_analyze_syntax(): request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): The request object. The syntax analysis request message. document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -882,7 +882,7 @@ def sample_classify_text(): The request object. The document classification request message. document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -984,12 +984,12 @@ def sample_annotate_text(): annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. features (google.cloud.language_v1.types.AnnotateTextRequest.Features): - The enabled features. + Required. The enabled features. This corresponds to the ``features`` field on the ``request`` instance; if ``request`` is provided, this should not be set. diff --git a/google/cloud/language_v1/types/__init__.py b/google/cloud/language_v1/types/__init__.py index 0f35f2e3..b4b20c9c 100644 --- a/google/cloud/language_v1/types/__init__.py +++ b/google/cloud/language_v1/types/__init__.py @@ -25,6 +25,7 @@ AnnotateTextRequest, AnnotateTextResponse, ClassificationCategory, + ClassificationModelOptions, ClassifyTextRequest, ClassifyTextResponse, DependencyEdge, @@ -51,6 +52,7 @@ "AnnotateTextRequest", "AnnotateTextResponse", "ClassificationCategory", + "ClassificationModelOptions", "ClassifyTextRequest", "ClassifyTextResponse", "DependencyEdge", diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 2cd79d57..431fa9f1 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -29,6 +29,7 @@ "EntityMention", "TextSpan", "ClassificationCategory", + "ClassificationModelOptions", "AnalyzeSentimentRequest", "AnalyzeSentimentResponse", "AnalyzeEntitySentimentRequest", @@ -728,12 +729,76 @@ class ClassificationCategory(proto.Message): ) +class ClassificationModelOptions(proto.Message): + r"""Model options available for classification requests. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + v1_model (google.cloud.language_v1.types.ClassificationModelOptions.V1Model): + Setting this field will use the V1 model and + V1 content categories version. The V1 model is a + legacy model; support for this will be + discontinued in the future. + + This field is a member of `oneof`_ ``model_type``. + v2_model (google.cloud.language_v1.types.ClassificationModelOptions.V2Model): + Setting this field will use the V2 model with + the appropriate content categories version. The + V2 model is a better performing model. + + This field is a member of `oneof`_ ``model_type``. + """ + + class V1Model(proto.Message): + r"""Options for the V1 model.""" + + class V2Model(proto.Message): + r"""Options for the V2 model. + + Attributes: + content_categories_version (google.cloud.language_v1.types.ClassificationModelOptions.V2Model.ContentCategoriesVersion): + The content categories used for + classification. + """ + + class ContentCategoriesVersion(proto.Enum): + r"""The content categories used for classification.""" + CONTENT_CATEGORIES_VERSION_UNSPECIFIED = 0 + V1 = 1 + V2 = 2 + + content_categories_version = proto.Field( + proto.ENUM, + number=1, + enum="ClassificationModelOptions.V2Model.ContentCategoriesVersion", + ) + + v1_model = proto.Field( + proto.MESSAGE, + number=1, + oneof="model_type", + message=V1Model, + ) + v2_model = proto.Field( + proto.MESSAGE, + number=2, + oneof="model_type", + message=V2Model, + ) + + class AnalyzeSentimentRequest(proto.Message): r"""The sentiment analysis request message. Attributes: document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. encoding_type (google.cloud.language_v1.types.EncodingType): The encoding type used by the API to calculate sentence offsets. @@ -789,7 +854,7 @@ class AnalyzeEntitySentimentRequest(proto.Message): Attributes: document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. encoding_type (google.cloud.language_v1.types.EncodingType): The encoding type used by the API to calculate offsets. @@ -838,7 +903,7 @@ class AnalyzeEntitiesRequest(proto.Message): Attributes: document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. encoding_type (google.cloud.language_v1.types.EncodingType): The encoding type used by the API to calculate offsets. @@ -887,7 +952,7 @@ class AnalyzeSyntaxRequest(proto.Message): Attributes: document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. encoding_type (google.cloud.language_v1.types.EncodingType): The encoding type used by the API to calculate offsets. @@ -943,7 +1008,10 @@ class ClassifyTextRequest(proto.Message): Attributes: document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. + classification_model_options (google.cloud.language_v1.types.ClassificationModelOptions): + Model options to use for classification. + Defaults to v1 options if not specified. """ document = proto.Field( @@ -951,6 +1019,11 @@ class ClassifyTextRequest(proto.Message): number=1, message="Document", ) + classification_model_options = proto.Field( + proto.MESSAGE, + number=3, + message="ClassificationModelOptions", + ) class ClassifyTextResponse(proto.Message): @@ -975,9 +1048,9 @@ class AnnotateTextRequest(proto.Message): Attributes: document (google.cloud.language_v1.types.Document): - Input document. + Required. Input document. features (google.cloud.language_v1.types.AnnotateTextRequest.Features): - The enabled features. + Required. The enabled features. encoding_type (google.cloud.language_v1.types.EncodingType): The encoding type used by the API to calculate offsets. @@ -1000,6 +1073,10 @@ class Features(proto.Message): sentiment. classify_text (bool): Classify the full document into categories. + classification_model_options (google.cloud.language_v1.types.ClassificationModelOptions): + The model options to use for classification. Defaults to v1 + options if not specified. Only used if ``classify_text`` is + set to true. """ extract_syntax = proto.Field( @@ -1022,6 +1099,11 @@ class Features(proto.Message): proto.BOOL, number=6, ) + classification_model_options = proto.Field( + proto.MESSAGE, + number=10, + message="ClassificationModelOptions", + ) document = proto.Field( proto.MESSAGE, diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py index 9e99392d..acafe86d 100644 --- a/google/cloud/language_v1beta2/__init__.py +++ b/google/cloud/language_v1beta2/__init__.py @@ -27,6 +27,7 @@ AnnotateTextRequest, AnnotateTextResponse, ClassificationCategory, + ClassificationModelOptions, ClassifyTextRequest, ClassifyTextResponse, DependencyEdge, @@ -54,6 +55,7 @@ "AnnotateTextRequest", "AnnotateTextResponse", "ClassificationCategory", + "ClassificationModelOptions", "ClassifyTextRequest", "ClassifyTextResponse", "DependencyEdge", diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 9eadd09c..db5180ac 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -568,7 +568,7 @@ async def analyze_syntax( metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part-of-speech + boundaries and tokenization along with part of speech tags, dependency trees, and other properties. .. code-block:: python diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index d6b37867..10e8b064 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -743,7 +743,7 @@ def analyze_syntax( metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part-of-speech + boundaries and tokenization along with part of speech tags, dependency trees, and other properties. .. code-block:: python diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 42cf6f63..3d1de3e0 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -331,7 +331,7 @@ def analyze_syntax( r"""Return a callable for the analyze syntax method over gRPC. Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part-of-speech + boundaries and tokenization along with part of speech tags, dependency trees, and other properties. Returns: diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 2ae5171b..72f07a70 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -335,7 +335,7 @@ def analyze_syntax( r"""Return a callable for the analyze syntax method over gRPC. Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part-of-speech + boundaries and tokenization along with part of speech tags, dependency trees, and other properties. Returns: diff --git a/google/cloud/language_v1beta2/types/__init__.py b/google/cloud/language_v1beta2/types/__init__.py index 0f35f2e3..b4b20c9c 100644 --- a/google/cloud/language_v1beta2/types/__init__.py +++ b/google/cloud/language_v1beta2/types/__init__.py @@ -25,6 +25,7 @@ AnnotateTextRequest, AnnotateTextResponse, ClassificationCategory, + ClassificationModelOptions, ClassifyTextRequest, ClassifyTextResponse, DependencyEdge, @@ -51,6 +52,7 @@ "AnnotateTextRequest", "AnnotateTextResponse", "ClassificationCategory", + "ClassificationModelOptions", "ClassifyTextRequest", "ClassifyTextResponse", "DependencyEdge", diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index b43b62ed..63f87cc8 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -29,6 +29,7 @@ "EntityMention", "TextSpan", "ClassificationCategory", + "ClassificationModelOptions", "AnalyzeSentimentRequest", "AnalyzeSentimentResponse", "AnalyzeEntitySentimentRequest", @@ -95,6 +96,16 @@ class Document(proto.Message): the language (either specified by the caller or automatically detected) is not supported by the called API method, an ``INVALID_ARGUMENT`` error is returned. + reference_web_uri (str): + The web URI where the document comes from. + This URI is not used for fetching the content, + but as a hint for analyzing the document. + boilerplate_handling (google.cloud.language_v1beta2.types.Document.BoilerplateHandling): + Indicates how detected boilerplate(e.g. + advertisements, copyright declarations, banners) + should be handled for this document. If not + specified, boilerplate will be treated the same + as content. """ class Type(proto.Enum): @@ -103,6 +114,12 @@ class Type(proto.Enum): PLAIN_TEXT = 1 HTML = 2 + class BoilerplateHandling(proto.Enum): + r"""Ways of handling boilerplate detected in the document""" + BOILERPLATE_HANDLING_UNSPECIFIED = 0 + SKIP_BOILERPLATE = 1 + KEEP_BOILERPLATE = 2 + type_ = proto.Field( proto.ENUM, number=1, @@ -122,6 +139,15 @@ class Type(proto.Enum): proto.STRING, number=4, ) + reference_web_uri = proto.Field( + proto.STRING, + number=5, + ) + boilerplate_handling = proto.Field( + proto.ENUM, + number=6, + enum=BoilerplateHandling, + ) class Sentence(proto.Message): @@ -725,6 +751,70 @@ class ClassificationCategory(proto.Message): ) +class ClassificationModelOptions(proto.Message): + r"""Model options available for classification requests. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + v1_model (google.cloud.language_v1beta2.types.ClassificationModelOptions.V1Model): + Setting this field will use the V1 model and + V1 content categories version. The V1 model is a + legacy model; support for this will be + discontinued in the future. + + This field is a member of `oneof`_ ``model_type``. + v2_model (google.cloud.language_v1beta2.types.ClassificationModelOptions.V2Model): + Setting this field will use the V2 model with + the appropriate content categories version. The + V2 model is a better performing model. + + This field is a member of `oneof`_ ``model_type``. + """ + + class V1Model(proto.Message): + r"""Options for the V1 model.""" + + class V2Model(proto.Message): + r"""Options for the V2 model. + + Attributes: + content_categories_version (google.cloud.language_v1beta2.types.ClassificationModelOptions.V2Model.ContentCategoriesVersion): + The content categories used for + classification. + """ + + class ContentCategoriesVersion(proto.Enum): + r"""The content categories used for classification.""" + CONTENT_CATEGORIES_VERSION_UNSPECIFIED = 0 + V1 = 1 + V2 = 2 + + content_categories_version = proto.Field( + proto.ENUM, + number=1, + enum="ClassificationModelOptions.V2Model.ContentCategoriesVersion", + ) + + v1_model = proto.Field( + proto.MESSAGE, + number=1, + oneof="model_type", + message=V1Model, + ) + v2_model = proto.Field( + proto.MESSAGE, + number=2, + oneof="model_type", + message=V2Model, + ) + + class AnalyzeSentimentRequest(proto.Message): r"""The sentiment analysis request message. @@ -942,6 +1032,9 @@ class ClassifyTextRequest(proto.Message): Attributes: document (google.cloud.language_v1beta2.types.Document): Required. Input document. + classification_model_options (google.cloud.language_v1beta2.types.ClassificationModelOptions): + Model options to use for classification. + Defaults to v1 options if not specified. """ document = proto.Field( @@ -949,6 +1042,11 @@ class ClassifyTextRequest(proto.Message): number=1, message="Document", ) + classification_model_options = proto.Field( + proto.MESSAGE, + number=3, + message="ClassificationModelOptions", + ) class ClassifyTextResponse(proto.Message): @@ -984,7 +1082,7 @@ class AnnotateTextRequest(proto.Message): class Features(proto.Message): r"""All available features for sentiment, syntax, and semantic analysis. Setting each one to true will enable that specific - analysis for the input. Next ID: 10 + analysis for the input. Next ID: 11 Attributes: extract_syntax (bool): @@ -1001,6 +1099,10 @@ class Features(proto.Message): the API will use the default model which classifies into a `predefined taxonomy <https://cloud.google.com/natural-language/docs/categories>`__. + classification_model_options (google.cloud.language_v1beta2.types.ClassificationModelOptions): + The model options to use for classification. Defaults to v1 + options if not specified. Only used if ``classify_text`` is + set to true. """ extract_syntax = proto.Field( @@ -1023,6 +1125,11 @@ class Features(proto.Message): proto.BOOL, number=6, ) + classification_model_options = proto.Field( + proto.MESSAGE, + number=10, + message="ClassificationModelOptions", + ) document = proto.Field( proto.MESSAGE, diff --git a/scripts/fixup_language_v1_keywords.py b/scripts/fixup_language_v1_keywords.py index e4268c0f..fc15df57 100644 --- a/scripts/fixup_language_v1_keywords.py +++ b/scripts/fixup_language_v1_keywords.py @@ -44,7 +44,7 @@ class languageCallTransformer(cst.CSTTransformer): 'analyze_sentiment': ('document', 'encoding_type', ), 'analyze_syntax': ('document', 'encoding_type', ), 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', ), + 'classify_text': ('document', 'classification_model_options', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/scripts/fixup_language_v1beta2_keywords.py b/scripts/fixup_language_v1beta2_keywords.py index e4268c0f..fc15df57 100644 --- a/scripts/fixup_language_v1beta2_keywords.py +++ b/scripts/fixup_language_v1beta2_keywords.py @@ -44,7 +44,7 @@ class languageCallTransformer(cst.CSTTransformer): 'analyze_sentiment': ('document', 'encoding_type', ), 'analyze_syntax': ('document', 'encoding_type', ), 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', ), + 'classify_text': ('document', 'classification_model_options', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: From 73670e27e2c2056f4a53d1225bb99399e8cbd05e Mon Sep 17 00:00:00 2001 From: wizeng23 <william.f.zeng@gmail.com> Date: Tue, 27 Sep 2022 07:58:25 -0700 Subject: [PATCH 202/254] docs: update classification sample to use v2 model (#378) * docs: update classification sample to use v2 model * fix: update classification test to use v2 model Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/v1/language_classify_text.py | 15 ++++++++++++--- samples/v1/test/classifying_content.test.yaml | 10 +++++----- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/samples/v1/language_classify_text.py b/samples/v1/language_classify_text.py index 6fe2aaa4..fe2b5671 100644 --- a/samples/v1/language_classify_text.py +++ b/samples/v1/language_classify_text.py @@ -32,12 +32,12 @@ def sample_classify_text(text_content): Classifying Content in a String Args: - text_content The text content to analyze. Must include at least 20 words. + text_content The text content to analyze. """ client = language_v1.LanguageServiceClient() - # text_content = 'That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows.' + # text_content = "That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows." # Available types: PLAIN_TEXT, HTML type_ = language_v1.Document.Type.PLAIN_TEXT @@ -48,7 +48,16 @@ def sample_classify_text(text_content): language = "en" document = {"content": text_content, "type_": type_, "language": language} - response = client.classify_text(request = {'document': document}) + content_categories_version = ( + language_v1.ClassificationModelOptions.V2Model.ContentCategoriesVersion.V2) + response = client.classify_text(request = { + "document": document, + "classification_model_options": { + "v2_model": { + "content_categories_version": content_categories_version + } + } + }) # Loop through classified categories returned from the API for category in response.categories: # Get the name of the category representing the document. diff --git a/samples/v1/test/classifying_content.test.yaml b/samples/v1/test/classifying_content.test.yaml index 5cfc7669..4b5f121d 100644 --- a/samples/v1/test/classifying_content.test.yaml +++ b/samples/v1/test/classifying_content.test.yaml @@ -16,15 +16,15 @@ test: - name: language_classify_text - Classifying Content of a text string (*custom value*) spec: - # Custom value: "Let's drink coffee and eat bagels at a coffee shop. I want muffins, croisants, coffee and baked goods." + # Custom value: "Dungeons and dragons and loot, oh my!" - call: sample: language_classify_text params: - text_content: {literal: "Let's drink coffee and eat bagels at a coffee shop. I want muffins, croisants, coffee and baked goods."} + text_content: {literal: "Dungeons and dragons and loot, oh my!"} - assert_contains_any: - - {literal: "Food"} - - {literal: "Drink"} - - {literal: "Coffee"} + - {literal: "Games"} + - {literal: "Roleplaying"} + - {literal: "Computer"} - name: language_classify_gcs - Classifying Content of text file in GCS (default value) spec: From 06f74b0cba8d3a5191caf5bee814c15bd0371813 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 29 Sep 2022 13:53:14 -0400 Subject: [PATCH 203/254] fix(deps): require protobuf >= 3.20.2 (#381) * chore: exclude requirements.txt file from renovate-bot Source-Link: https://github.com/googleapis/synthtool/commit/f58d3135a2fab20e225d98741dbc06d57459b816 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:7a40313731a7cb1454eef6b33d3446ebb121836738dc3ab3d2d3ded5268c35b6 * update constraints files * fix(deps): require protobuf 3.20.2 Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/requirements.txt | 49 ++++++++++++++++++------------------- setup.py | 2 +- testing/constraints-3.7.txt | 2 +- 4 files changed, 27 insertions(+), 28 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index aa547962..3815c983 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:e09366bdf0fd9c8976592988390b24d53583dd9f002d476934da43725adbb978 + digest: sha256:7a40313731a7cb1454eef6b33d3446ebb121836738dc3ab3d2d3ded5268c35b6 diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 385f2d4d..d15994ba 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -325,31 +325,30 @@ platformdirs==2.5.2 \ --hash=sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788 \ --hash=sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19 # via virtualenv -protobuf==3.20.1 \ - --hash=sha256:06059eb6953ff01e56a25cd02cca1a9649a75a7e65397b5b9b4e929ed71d10cf \ - --hash=sha256:097c5d8a9808302fb0da7e20edf0b8d4703274d140fd25c5edabddcde43e081f \ - --hash=sha256:284f86a6207c897542d7e956eb243a36bb8f9564c1742b253462386e96c6b78f \ - --hash=sha256:32ca378605b41fd180dfe4e14d3226386d8d1b002ab31c969c366549e66a2bb7 \ - --hash=sha256:3cc797c9d15d7689ed507b165cd05913acb992d78b379f6014e013f9ecb20996 \ - --hash=sha256:62f1b5c4cd6c5402b4e2d63804ba49a327e0c386c99b1675c8a0fefda23b2067 \ - --hash=sha256:69ccfdf3657ba59569c64295b7d51325f91af586f8d5793b734260dfe2e94e2c \ - --hash=sha256:6f50601512a3d23625d8a85b1638d914a0970f17920ff39cec63aaef80a93fb7 \ - --hash=sha256:7403941f6d0992d40161aa8bb23e12575637008a5a02283a930addc0508982f9 \ - --hash=sha256:755f3aee41354ae395e104d62119cb223339a8f3276a0cd009ffabfcdd46bb0c \ - --hash=sha256:77053d28427a29987ca9caf7b72ccafee011257561259faba8dd308fda9a8739 \ - --hash=sha256:7e371f10abe57cee5021797126c93479f59fccc9693dafd6bd5633ab67808a91 \ - --hash=sha256:9016d01c91e8e625141d24ec1b20fed584703e527d28512aa8c8707f105a683c \ - --hash=sha256:9be73ad47579abc26c12024239d3540e6b765182a91dbc88e23658ab71767153 \ - --hash=sha256:adc31566d027f45efe3f44eeb5b1f329da43891634d61c75a5944e9be6dd42c9 \ - --hash=sha256:adfc6cf69c7f8c50fd24c793964eef18f0ac321315439d94945820612849c388 \ - --hash=sha256:af0ebadc74e281a517141daad9d0f2c5d93ab78e9d455113719a45a49da9db4e \ - --hash=sha256:cb29edb9eab15742d791e1025dd7b6a8f6fcb53802ad2f6e3adcb102051063ab \ - --hash=sha256:cd68be2559e2a3b84f517fb029ee611546f7812b1fdd0aa2ecc9bc6ec0e4fdde \ - --hash=sha256:cdee09140e1cd184ba9324ec1df410e7147242b94b5f8b0c64fc89e38a8ba531 \ - --hash=sha256:db977c4ca738dd9ce508557d4fce0f5aebd105e158c725beec86feb1f6bc20d8 \ - --hash=sha256:dd5789b2948ca702c17027c84c2accb552fc30f4622a98ab5c51fcfe8c50d3e7 \ - --hash=sha256:e250a42f15bf9d5b09fe1b293bdba2801cd520a9f5ea2d7fb7536d4441811d20 \ - --hash=sha256:ff8d8fa42675249bb456f5db06c00de6c2f4c27a065955917b28c4f15978b9c3 +protobuf==3.20.2 \ + --hash=sha256:03d76b7bd42ac4a6e109742a4edf81ffe26ffd87c5993126d894fe48a120396a \ + --hash=sha256:09e25909c4297d71d97612f04f41cea8fa8510096864f2835ad2f3b3df5a5559 \ + --hash=sha256:18e34a10ae10d458b027d7638a599c964b030c1739ebd035a1dfc0e22baa3bfe \ + --hash=sha256:291fb4307094bf5ccc29f424b42268640e00d5240bf0d9b86bf3079f7576474d \ + --hash=sha256:2c0b040d0b5d5d207936ca2d02f00f765906622c07d3fa19c23a16a8ca71873f \ + --hash=sha256:384164994727f274cc34b8abd41a9e7e0562801361ee77437099ff6dfedd024b \ + --hash=sha256:3cb608e5a0eb61b8e00fe641d9f0282cd0eedb603be372f91f163cbfbca0ded0 \ + --hash=sha256:5d9402bf27d11e37801d1743eada54372f986a372ec9679673bfcc5c60441151 \ + --hash=sha256:712dca319eee507a1e7df3591e639a2b112a2f4a62d40fe7832a16fd19151750 \ + --hash=sha256:7a5037af4e76c975b88c3becdf53922b5ffa3f2cddf657574a4920a3b33b80f3 \ + --hash=sha256:8228e56a865c27163d5d1d1771d94b98194aa6917bcfb6ce139cbfa8e3c27334 \ + --hash=sha256:84a1544252a933ef07bb0b5ef13afe7c36232a774affa673fc3636f7cee1db6c \ + --hash=sha256:84fe5953b18a383fd4495d375fe16e1e55e0a3afe7b4f7b4d01a3a0649fcda9d \ + --hash=sha256:9c673c8bfdf52f903081816b9e0e612186684f4eb4c17eeb729133022d6032e3 \ + --hash=sha256:9f876a69ca55aed879b43c295a328970306e8e80a263ec91cf6e9189243c613b \ + --hash=sha256:a9e5ae5a8e8985c67e8944c23035a0dff2c26b0f5070b2f55b217a1c33bbe8b1 \ + --hash=sha256:b4fdb29c5a7406e3f7ef176b2a7079baa68b5b854f364c21abe327bbeec01cdb \ + --hash=sha256:c184485e0dfba4dfd451c3bd348c2e685d6523543a0f91b9fd4ae90eb09e8422 \ + --hash=sha256:c9cdf251c582c16fd6a9f5e95836c90828d51b0069ad22f463761d27c6c19019 \ + --hash=sha256:e39cf61bb8582bda88cdfebc0db163b774e7e03364bbf9ce1ead13863e81e359 \ + --hash=sha256:e8fbc522303e09036c752a0afcc5c0603e917222d8bedc02813fd73b4b4ed804 \ + --hash=sha256:f34464ab1207114e73bba0794d1257c150a2b89b7a9faf504e00af7c9fd58978 \ + --hash=sha256:f52dabc96ca99ebd2169dadbe018824ebda08a795c7684a0b7d203a290f3adb0 # via # gcp-docuploader # gcp-releasetool diff --git a/setup.py b/setup.py index 17866216..57fa10e9 100644 --- a/setup.py +++ b/setup.py @@ -30,7 +30,7 @@ dependencies = [ "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.22.0, <2.0.0dev", - "protobuf >= 3.19.0, <5.0.0dev", + "protobuf >= 3.20.2, <5.0.0dev", ] # Setup boilerplate below this line. diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 810c7cb3..df8564de 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -6,4 +6,4 @@ # Then this file should have google-cloud-foo==1.14.0 google-api-core==1.32.0 proto-plus==1.22.0 -protobuf==3.19.0 +protobuf==3.20.2 From 6094ee3b7dcaf43ade856f20287256509c1397e5 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 29 Sep 2022 16:01:20 -0400 Subject: [PATCH 204/254] chore(main): release 2.6.0 (#380) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 17 +++++++++++++++++ setup.py | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ade1bc26..8e9acb54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.6.0](https://github.com/googleapis/python-language/compare/v2.5.2...v2.6.0) (2022-09-29) + + +### Features + +* Add support for V1 and V2 classification models ([#376](https://github.com/googleapis/python-language/issues/376)) ([3ba5c56](https://github.com/googleapis/python-language/commit/3ba5c568179b04326ef9cc9874f2d18da99e51d6)) + + +### Bug Fixes + +* **deps:** Require protobuf >= 3.20.2 ([#381](https://github.com/googleapis/python-language/issues/381)) ([06f74b0](https://github.com/googleapis/python-language/commit/06f74b0cba8d3a5191caf5bee814c15bd0371813)) + + +### Documentation + +* Update classification sample to use v2 model ([#378](https://github.com/googleapis/python-language/issues/378)) ([73670e2](https://github.com/googleapis/python-language/commit/73670e27e2c2056f4a53d1225bb99399e8cbd05e)) + ## [2.5.2](https://github.com/googleapis/python-language/compare/v2.5.1...v2.5.2) (2022-08-11) diff --git a/setup.py b/setup.py index 57fa10e9..2a36d10a 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.5.2" +version = "2.6.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 6c788b7a3f1b7b75754330f014013d3fd6240f60 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Mon, 3 Oct 2022 19:06:35 +0200 Subject: [PATCH 205/254] chore(deps): update all dependencies (#382) Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 3b659116..fca4e863 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.62.0 -google-auth==2.11.1 +google-api-python-client==2.63.0 +google-auth==2.12.0 google-auth-httplib2==0.1.0 From 7d6b91a023c6afc63560b236f3b2e86a575c0610 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 4 Oct 2022 02:53:52 +0200 Subject: [PATCH 206/254] chore(deps): update dependency google-cloud-language to v2.6.0 (#383) --- samples/snippets/classify_text/requirements.txt | 2 +- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 954099ff..933b1bf8 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.5.2 +google-cloud-language==2.6.0 numpy==1.23.3; python_version > '3.7' numpy===1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index db52d214..b9a49269 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.5.2 +google-cloud-language==2.6.0 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index db52d214..b9a49269 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.5.2 +google-cloud-language==2.6.0 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index db52d214..b9a49269 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.5.2 +google-cloud-language==2.6.0 From 327c2472cd63c0e353dd135c71031b24034ac69b Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 4 Oct 2022 20:19:14 +0200 Subject: [PATCH 207/254] chore(deps): update dependency google-api-python-client to v2.64.0 (#384) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index fca4e863..3cc81ab8 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.63.0 +google-api-python-client==2.64.0 google-auth==2.12.0 google-auth-httplib2==0.1.0 From 99e1907440c08894c213e7d7c9a29618a4b3d0d8 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Mon, 10 Oct 2022 13:22:58 -0400 Subject: [PATCH 208/254] fix(deps): allow protobuf 3.19.5 (#385) * fix(deps): allow protobuf 3.19.5 * explicitly exclude protobuf 4.21.0 --- setup.py | 2 +- testing/constraints-3.7.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 2a36d10a..75df3318 100644 --- a/setup.py +++ b/setup.py @@ -30,7 +30,7 @@ dependencies = [ "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.22.0, <2.0.0dev", - "protobuf >= 3.20.2, <5.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] # Setup boilerplate below this line. diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index df8564de..4005dc5b 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -6,4 +6,4 @@ # Then this file should have google-cloud-foo==1.14.0 google-api-core==1.32.0 proto-plus==1.22.0 -protobuf==3.20.2 +protobuf==3.19.5 From ce8ac5c654b8673d9acf9678cbef3fdddd14350a Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 10 Oct 2022 13:58:41 -0400 Subject: [PATCH 209/254] chore(main): release 2.6.1 (#386) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- CHANGELOG.md | 7 +++++++ setup.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e9acb54..030ec01e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.6.1](https://github.com/googleapis/python-language/compare/v2.6.0...v2.6.1) (2022-10-10) + + +### Bug Fixes + +* **deps:** Allow protobuf 3.19.5 ([#385](https://github.com/googleapis/python-language/issues/385)) ([99e1907](https://github.com/googleapis/python-language/commit/99e1907440c08894c213e7d7c9a29618a4b3d0d8)) + ## [2.6.0](https://github.com/googleapis/python-language/compare/v2.5.2...v2.6.0) (2022-09-29) diff --git a/setup.py b/setup.py index 75df3318..ae220ed8 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-language" description = "Google Cloud Natural Language API client library" -version = "2.6.0" +version = "2.6.1" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' From 5471472d47b0e84b284c452491c87bed0177d20b Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 18 Oct 2022 15:23:47 +0200 Subject: [PATCH 210/254] chore(deps): update all dependencies (#387) --- samples/snippets/api/requirements.txt | 2 +- samples/snippets/classify_text/requirements.txt | 4 ++-- samples/snippets/cloud-client/v1/requirements.txt | 2 +- samples/snippets/generated-samples/v1/requirements.txt | 2 +- samples/snippets/sentiment/requirements.txt | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 3cc81ab8..d5bb9dbf 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.64.0 -google-auth==2.12.0 +google-auth==2.13.0 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index 933b1bf8..f53284c6 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-language==2.6.0 -numpy==1.23.3; python_version > '3.7' +google-cloud-language==2.6.1 +numpy==1.23.4; python_version > '3.7' numpy===1.21.4; python_version == '3.7' diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt index b9a49269..c3458e3d 100644 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ b/samples/snippets/cloud-client/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.6.0 +google-cloud-language==2.6.1 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt index b9a49269..c3458e3d 100644 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ b/samples/snippets/generated-samples/v1/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.6.0 +google-cloud-language==2.6.1 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt index b9a49269..c3458e3d 100644 --- a/samples/snippets/sentiment/requirements.txt +++ b/samples/snippets/sentiment/requirements.txt @@ -1 +1 @@ -google-cloud-language==2.6.0 +google-cloud-language==2.6.1 From 7c70628a1c73a12db486cfe3a263ab0f99981d87 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 19 Oct 2022 16:04:27 +0200 Subject: [PATCH 211/254] chore(deps): update dependency google-api-python-client to v2.65.0 (#389) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index d5bb9dbf..8d79b994 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.64.0 +google-api-python-client==2.65.0 google-auth==2.13.0 google-auth-httplib2==0.1.0 From ba95fd4e6470bd4568f007523f5926ad12096aab Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Wed, 26 Oct 2022 12:48:50 +0200 Subject: [PATCH 212/254] chore(deps): update dependency pytest to v7.2.0 (#390) --- samples/snippets/api/requirements-test.txt | 2 +- samples/snippets/classify_text/requirements-test.txt | 2 +- samples/snippets/cloud-client/v1/requirements-test.txt | 2 +- samples/snippets/generated-samples/v1/requirements-test.txt | 2 +- samples/snippets/sentiment/requirements-test.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt index e0716850..49780e03 100644 --- a/samples/snippets/api/requirements-test.txt +++ b/samples/snippets/api/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.3 +pytest==7.2.0 diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt index e0716850..49780e03 100644 --- a/samples/snippets/classify_text/requirements-test.txt +++ b/samples/snippets/classify_text/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.3 +pytest==7.2.0 diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt index e0716850..49780e03 100644 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ b/samples/snippets/cloud-client/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.3 +pytest==7.2.0 diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt index e0716850..49780e03 100644 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ b/samples/snippets/generated-samples/v1/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.3 +pytest==7.2.0 diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt index e0716850..49780e03 100644 --- a/samples/snippets/sentiment/requirements-test.txt +++ b/samples/snippets/sentiment/requirements-test.txt @@ -1 +1 @@ -pytest==7.1.3 +pytest==7.2.0 From cb5290723a1f13d6ea3929cdf2fce103ee464910 Mon Sep 17 00:00:00 2001 From: Yu-Han Liu <yuhanliu@google.com> Date: Mon, 31 Oct 2022 13:43:51 -0700 Subject: [PATCH 213/254] chore: release-please updates snippet metadata (#393) --- release-please-config.json | 20 +++++++++++++++++++ .../snippet_metadata_language_v1.json | 3 ++- .../snippet_metadata_language_v1beta2.json | 3 ++- 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 release-please-config.json diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 00000000..1744dcba --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,20 @@ +{ + "$schema": +"https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": {}, + "release-type": "python", + "extra-files": [ + "**/gapic_version.py", + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata*.json", + "jsonpath": "$.clientLibrary.version" + } + ], + "plugins": [ + { + "type": "sentence-case" + } + ], + "initial-version": "0.1.0" +} diff --git a/samples/generated_samples/snippet_metadata_language_v1.json b/samples/generated_samples/snippet_metadata_language_v1.json index f633a498..936a8b70 100644 --- a/samples/generated_samples/snippet_metadata_language_v1.json +++ b/samples/generated_samples/snippet_metadata_language_v1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-language" + "name": "google-cloud-language", + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_language_v1beta2.json b/samples/generated_samples/snippet_metadata_language_v1beta2.json index 2184122a..a4368f2d 100644 --- a/samples/generated_samples/snippet_metadata_language_v1beta2.json +++ b/samples/generated_samples/snippet_metadata_language_v1beta2.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-language" + "name": "google-cloud-language", + "version": "0.1.0" }, "snippets": [ { From 9abca704ddeed317bd46432189d037db70e39521 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate <bot@renovateapp.com> Date: Tue, 1 Nov 2022 14:12:01 +0100 Subject: [PATCH 214/254] chore(deps): update dependency google-auth to v2.14.0 (#395) --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 8d79b994..8cef7de4 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.65.0 -google-auth==2.13.0 +google-auth==2.14.0 google-auth-httplib2==0.1.0 From 05b579e7c4a7a54d2b66267a23acdeda1a14e206 Mon Sep 17 00:00:00 2001 From: Yu-Han Liu <yuhanliu@google.com> Date: Thu, 3 Nov 2022 14:34:11 -0700 Subject: [PATCH 215/254] chore: add release-please manifest (#396) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: add release-please manifest * linter * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .release-please-manifest.json | 3 +++ google/cloud/language/gapic_version.py | 16 +++++++++++ release-please-config.json | 27 ++++++++++++------- ...et_metadata_google.cloud.language.v1.json} | 0 ...tadata_google.cloud.language.v1beta2.json} | 0 5 files changed, 37 insertions(+), 9 deletions(-) create mode 100644 .release-please-manifest.json create mode 100644 google/cloud/language/gapic_version.py rename samples/generated_samples/{snippet_metadata_language_v1.json => snippet_metadata_google.cloud.language.v1.json} (100%) rename samples/generated_samples/{snippet_metadata_language_v1beta2.json => snippet_metadata_google.cloud.language.v1beta2.json} (100%) diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 00000000..96d9691c --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.1.0" +} diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/google/cloud/language/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/release-please-config.json b/release-please-config.json index 1744dcba..dd7d4d91 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,16 +1,25 @@ { "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", - "packages": {}, - "release-type": "python", - "extra-files": [ - "**/gapic_version.py", - { - "type": "json", - "path": "samples/generated_samples/snippet_metadata*.json", - "jsonpath": "$.clientLibrary.version" + "packages": { + ".": { + "release-type": "python", + "extra-files": [ + "google/cloud/language/gapic_version.py", + { + "type": "json", + "path": "ssamples/generated_samples/snippet_metadata_google.cloud.language.v1.json", + "jsonpath": "$.clientLibrary.version" + }, + { + "type": "json", + "path": "ssamples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json", + "jsonpath": "$.clientLibrary.version" + } + ] } - ], + }, + "release-type": "python", "plugins": [ { "type": "sentence-case" diff --git a/samples/generated_samples/snippet_metadata_language_v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json similarity index 100% rename from samples/generated_samples/snippet_metadata_language_v1.json rename to samples/generated_samples/snippet_metadata_google.cloud.language.v1.json diff --git a/samples/generated_samples/snippet_metadata_language_v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json similarity index 100% rename from samples/generated_samples/snippet_metadata_language_v1beta2.json rename to samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json From ee8813036e9a480631d34e2769ed736e101e94a9 Mon Sep 17 00:00:00 2001 From: Yu-Han Liu <yuhanliu@google.com> Date: Fri, 4 Nov 2022 13:39:46 -0700 Subject: [PATCH 216/254] chore: enable manifest for release-please (#397) --- .github/release-please.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/release-please.yml b/.github/release-please.yml index 29601ad4..fe749ff6 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,5 +1,6 @@ releaseType: python handleGHRelease: true +manifest: true # NOTE: this section is generated by synthtool.languages.python # See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py branches: From 4757163cc28475d022d72f063af7bedf9484f6d2 Mon Sep 17 00:00:00 2001 From: Yu-Han Liu <yuhanliu@google.com> Date: Fri, 4 Nov 2022 13:55:26 -0700 Subject: [PATCH 217/254] chore: Update release-please-config.json (#398) --- release-please-config.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/release-please-config.json b/release-please-config.json index dd7d4d91..8a8c9d0e 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -8,12 +8,12 @@ "google/cloud/language/gapic_version.py", { "type": "json", - "path": "ssamples/generated_samples/snippet_metadata_google.cloud.language.v1.json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1.json", "jsonpath": "$.clientLibrary.version" }, { "type": "json", - "path": "ssamples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json", "jsonpath": "$.clientLibrary.version" } ] From 18c876052aa66b2c5dc4a547502ef86e6aeb57bf Mon Sep 17 00:00:00 2001 From: Yu-Han Liu <yuhanliu@google.com> Date: Fri, 4 Nov 2022 14:14:07 -0700 Subject: [PATCH 218/254] chore: copy version from setup.py to google/cloud/language/gapic_version.py (#399) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update gapic_version.py * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * Update release-please.yml * update .release-please-manifest.json version Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- google/cloud/language/gapic_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 96d9691c..cb7c2b22 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.1.0" + ".": "2.6.1" } diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index 405b1ceb..e253e532 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.0" # {x-release-please-version} +__version__ = "2.6.1" # {x-release-please-version} From ebf224c3acfaa8f210b853556f97cc8c5555d239 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 8 Nov 2022 02:18:27 +0000 Subject: [PATCH 219/254] chore(python): update dependencies in .kokoro/requirements.txt [autoapprove] (#400) Source-Link: https://togithub.com/googleapis/synthtool/commit/e3a1277ac35fc88c09db1930533e24292b132ced Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:452901c74a22f9b9a3bd02bce780b8e8805c97270d424684bff809ce5be8c2a2 --- .github/.OwlBot.lock.yaml | 2 +- .github/release-please.yml | 1 - .kokoro/requirements.txt | 325 ++++++++++++++++++++----------------- noxfile.py | 11 +- 4 files changed, 187 insertions(+), 152 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 3815c983..12edee77 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:7a40313731a7cb1454eef6b33d3446ebb121836738dc3ab3d2d3ded5268c35b6 + digest: sha256:452901c74a22f9b9a3bd02bce780b8e8805c97270d424684bff809ce5be8c2a2 diff --git a/.github/release-please.yml b/.github/release-please.yml index fe749ff6..29601ad4 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,6 +1,5 @@ releaseType: python handleGHRelease: true -manifest: true # NOTE: this section is generated by synthtool.languages.python # See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py branches: diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index d15994ba..31425f16 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -20,9 +20,9 @@ cachetools==5.2.0 \ --hash=sha256:6a94c6402995a99c3970cc7e4884bb60b4a8639938157eeed436098bf9831757 \ --hash=sha256:f9f17d2aec496a9aa6b76f53e3b614c965223c061982d434d160f930c698a9db # via google-auth -certifi==2022.6.15 \ - --hash=sha256:84c85a9078b11105f04f3036a9482ae10e4621616db313fe045dd24743a0820d \ - --hash=sha256:fe86415d55e84719d75f8b69414f6438ac3547d2078ab91b67e779ef69378412 +certifi==2022.9.24 \ + --hash=sha256:0d9c601124e5a6ba9712dbc60d9c53c21e34f5f641fe83002317394311bdce14 \ + --hash=sha256:90c1a32f1d68f940488354e36370f6cca89f0f106db09518524c88d6ed83f382 # via requests cffi==1.15.1 \ --hash=sha256:00a9ed42e88df81ffae7a8ab6d9356b371399b91dbdf0c3cb1e84c03a13aceb5 \ @@ -110,29 +110,33 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==37.0.4 \ - --hash=sha256:190f82f3e87033821828f60787cfa42bff98404483577b591429ed99bed39d59 \ - --hash=sha256:2be53f9f5505673eeda5f2736bea736c40f051a739bfae2f92d18aed1eb54596 \ - --hash=sha256:30788e070800fec9bbcf9faa71ea6d8068f5136f60029759fd8c3efec3c9dcb3 \ - --hash=sha256:3d41b965b3380f10e4611dbae366f6dc3cefc7c9ac4e8842a806b9672ae9add5 \ - --hash=sha256:4c590ec31550a724ef893c50f9a97a0c14e9c851c85621c5650d699a7b88f7ab \ - --hash=sha256:549153378611c0cca1042f20fd9c5030d37a72f634c9326e225c9f666d472884 \ - --hash=sha256:63f9c17c0e2474ccbebc9302ce2f07b55b3b3fcb211ded18a42d5764f5c10a82 \ - --hash=sha256:6bc95ed67b6741b2607298f9ea4932ff157e570ef456ef7ff0ef4884a134cc4b \ - --hash=sha256:7099a8d55cd49b737ffc99c17de504f2257e3787e02abe6d1a6d136574873441 \ - --hash=sha256:75976c217f10d48a8b5a8de3d70c454c249e4b91851f6838a4e48b8f41eb71aa \ - --hash=sha256:7bc997818309f56c0038a33b8da5c0bfbb3f1f067f315f9abd6fc07ad359398d \ - --hash=sha256:80f49023dd13ba35f7c34072fa17f604d2f19bf0989f292cedf7ab5770b87a0b \ - --hash=sha256:91ce48d35f4e3d3f1d83e29ef4a9267246e6a3be51864a5b7d2247d5086fa99a \ - --hash=sha256:a958c52505c8adf0d3822703078580d2c0456dd1d27fabfb6f76fe63d2971cd6 \ - --hash=sha256:b62439d7cd1222f3da897e9a9fe53bbf5c104fff4d60893ad1355d4c14a24157 \ - --hash=sha256:b7f8dd0d4c1f21759695c05a5ec8536c12f31611541f8904083f3dc582604280 \ - --hash=sha256:d204833f3c8a33bbe11eda63a54b1aad7aa7456ed769a982f21ec599ba5fa282 \ - --hash=sha256:e007f052ed10cc316df59bc90fbb7ff7950d7e2919c9757fd42a2b8ecf8a5f67 \ - --hash=sha256:f2dcb0b3b63afb6df7fd94ec6fbddac81b5492513f7b0436210d390c14d46ee8 \ - --hash=sha256:f721d1885ecae9078c3f6bbe8a88bc0786b6e749bf32ccec1ef2b18929a05046 \ - --hash=sha256:f7a6de3e98771e183645181b3627e2563dcde3ce94a9e42a3f427d2255190327 \ - --hash=sha256:f8c0a6e9e1dd3eb0414ba320f85da6b0dcbd543126e30fcc546e7372a7fbf3b9 +cryptography==38.0.3 \ + --hash=sha256:068147f32fa662c81aebab95c74679b401b12b57494872886eb5c1139250ec5d \ + --hash=sha256:06fc3cc7b6f6cca87bd56ec80a580c88f1da5306f505876a71c8cfa7050257dd \ + --hash=sha256:25c1d1f19729fb09d42e06b4bf9895212292cb27bb50229f5aa64d039ab29146 \ + --hash=sha256:402852a0aea73833d982cabb6d0c3bb582c15483d29fb7085ef2c42bfa7e38d7 \ + --hash=sha256:4e269dcd9b102c5a3d72be3c45d8ce20377b8076a43cbed6f660a1afe365e436 \ + --hash=sha256:5419a127426084933076132d317911e3c6eb77568a1ce23c3ac1e12d111e61e0 \ + --hash=sha256:554bec92ee7d1e9d10ded2f7e92a5d70c1f74ba9524947c0ba0c850c7b011828 \ + --hash=sha256:5e89468fbd2fcd733b5899333bc54d0d06c80e04cd23d8c6f3e0542358c6060b \ + --hash=sha256:65535bc550b70bd6271984d9863a37741352b4aad6fb1b3344a54e6950249b55 \ + --hash=sha256:6ab9516b85bebe7aa83f309bacc5f44a61eeb90d0b4ec125d2d003ce41932d36 \ + --hash=sha256:6addc3b6d593cd980989261dc1cce38263c76954d758c3c94de51f1e010c9a50 \ + --hash=sha256:728f2694fa743a996d7784a6194da430f197d5c58e2f4e278612b359f455e4a2 \ + --hash=sha256:785e4056b5a8b28f05a533fab69febf5004458e20dad7e2e13a3120d8ecec75a \ + --hash=sha256:78cf5eefac2b52c10398a42765bfa981ce2372cbc0457e6bf9658f41ec3c41d8 \ + --hash=sha256:7f836217000342d448e1c9a342e9163149e45d5b5eca76a30e84503a5a96cab0 \ + --hash=sha256:8d41a46251bf0634e21fac50ffd643216ccecfaf3701a063257fe0b2be1b6548 \ + --hash=sha256:984fe150f350a3c91e84de405fe49e688aa6092b3525f407a18b9646f6612320 \ + --hash=sha256:9b24bcff7853ed18a63cfb0c2b008936a9554af24af2fb146e16d8e1aed75748 \ + --hash=sha256:b1b35d9d3a65542ed2e9d90115dfd16bbc027b3f07ee3304fc83580f26e43249 \ + --hash=sha256:b1b52c9e5f8aa2b802d48bd693190341fae201ea51c7a167d69fc48b60e8a959 \ + --hash=sha256:bbf203f1a814007ce24bd4d51362991d5cb90ba0c177a9c08825f2cc304d871f \ + --hash=sha256:be243c7e2bfcf6cc4cb350c0d5cdf15ca6383bbcb2a8ef51d3c9411a9d4386f0 \ + --hash=sha256:bfbe6ee19615b07a98b1d2287d6a6073f734735b49ee45b11324d85efc4d5cbd \ + --hash=sha256:c46837ea467ed1efea562bbeb543994c2d1f6e800785bd5a2c98bc096f5cb220 \ + --hash=sha256:dfb4f4dd568de1b6af9f4cda334adf7d72cf5bc052516e1b2608b683375dd95c \ + --hash=sha256:ed7b00096790213e09eb11c97cc6e2b757f15f3d2f85833cd2d3ec3fe37c1722 # via # gcp-releasetool # secretstorage @@ -148,23 +152,23 @@ filelock==3.8.0 \ --hash=sha256:55447caa666f2198c5b6b13a26d2084d26fa5b115c00d065664b2124680c4edc \ --hash=sha256:617eb4e5eedc82fc5f47b6d61e4d11cb837c56cb4544e39081099fa17ad109d4 # via virtualenv -gcp-docuploader==0.6.3 \ - --hash=sha256:ba8c9d76b3bbac54b0311c503a373b00edc2dc02d6d54ea9507045adb8e870f7 \ - --hash=sha256:c0f5aaa82ce1854a386197e4e359b120ad6d4e57ae2c812fce42219a3288026b +gcp-docuploader==0.6.4 \ + --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ + --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf # via -r requirements.in -gcp-releasetool==1.8.7 \ - --hash=sha256:3d2a67c9db39322194afb3b427e9cb0476ce8f2a04033695f0aeb63979fc2b37 \ - --hash=sha256:5e4d28f66e90780d77f3ecf1e9155852b0c3b13cbccb08ab07e66b2357c8da8d +gcp-releasetool==1.9.1 \ + --hash=sha256:952f4055d5d986b070ae2a71c4410b250000f9cc5a1e26398fcd55a5bbc5a15f \ + --hash=sha256:d0d3c814a97c1a237517e837d8cfa668ced8df4b882452578ecef4a4e79c583b # via -r requirements.in -google-api-core==2.8.2 \ - --hash=sha256:06f7244c640322b508b125903bb5701bebabce8832f85aba9335ec00b3d02edc \ - --hash=sha256:93c6a91ccac79079ac6bbf8b74ee75db970cc899278b97d53bc012f35908cf50 +google-api-core==2.10.2 \ + --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ + --hash=sha256:34f24bd1d5f72a8c4519773d99ca6bf080a6c4e041b4e9f024fe230191dda62e # via # google-cloud-core # google-cloud-storage -google-auth==2.11.0 \ - --hash=sha256:be62acaae38d0049c21ca90f27a23847245c9f161ff54ede13af2cb6afecbac9 \ - --hash=sha256:ed65ecf9f681832298e29328e1ef0a3676e3732b2e56f41532d45f70a22de0fb +google-auth==2.14.0 \ + --hash=sha256:1ad5b0e6eba5f69645971abb3d2c197537d5914070a8c6d30299dfdb07c5c700 \ + --hash=sha256:cf24817855d874ede2efd071aa22125445f555de1685b739a9782fcf408c2a3d # via # gcp-releasetool # google-api-core @@ -178,72 +182,97 @@ google-cloud-storage==2.5.0 \ --hash=sha256:19a26c66c317ce542cea0830b7e787e8dac2588b6bfa4d3fd3b871ba16305ab0 \ --hash=sha256:382f34b91de2212e3c2e7b40ec079d27ee2e3dbbae99b75b1bcd8c63063ce235 # via gcp-docuploader -google-crc32c==1.3.0 \ - --hash=sha256:04e7c220798a72fd0f08242bc8d7a05986b2a08a0573396187fd32c1dcdd58b3 \ - --hash=sha256:05340b60bf05b574159e9bd940152a47d38af3fb43803ffe71f11d704b7696a6 \ - --hash=sha256:12674a4c3b56b706153a358eaa1018c4137a5a04635b92b4652440d3d7386206 \ - --hash=sha256:127f9cc3ac41b6a859bd9dc4321097b1a4f6aa7fdf71b4f9227b9e3ebffb4422 \ - --hash=sha256:13af315c3a0eec8bb8b8d80b8b128cb3fcd17d7e4edafc39647846345a3f003a \ - --hash=sha256:1926fd8de0acb9d15ee757175ce7242e235482a783cd4ec711cc999fc103c24e \ - --hash=sha256:226f2f9b8e128a6ca6a9af9b9e8384f7b53a801907425c9a292553a3a7218ce0 \ - --hash=sha256:276de6273eb074a35bc598f8efbc00c7869c5cf2e29c90748fccc8c898c244df \ - --hash=sha256:318f73f5484b5671f0c7f5f63741ab020a599504ed81d209b5c7129ee4667407 \ - --hash=sha256:3bbce1be3687bbfebe29abdb7631b83e6b25da3f4e1856a1611eb21854b689ea \ - --hash=sha256:42ae4781333e331a1743445931b08ebdad73e188fd554259e772556fc4937c48 \ - --hash=sha256:58be56ae0529c664cc04a9c76e68bb92b091e0194d6e3c50bea7e0f266f73713 \ - --hash=sha256:5da2c81575cc3ccf05d9830f9e8d3c70954819ca9a63828210498c0774fda1a3 \ - --hash=sha256:6311853aa2bba4064d0c28ca54e7b50c4d48e3de04f6770f6c60ebda1e975267 \ - --hash=sha256:650e2917660e696041ab3dcd7abac160b4121cd9a484c08406f24c5964099829 \ - --hash=sha256:6a4db36f9721fdf391646685ecffa404eb986cbe007a3289499020daf72e88a2 \ - --hash=sha256:779cbf1ce375b96111db98fca913c1f5ec11b1d870e529b1dc7354b2681a8c3a \ - --hash=sha256:7f6fe42536d9dcd3e2ffb9d3053f5d05221ae3bbcefbe472bdf2c71c793e3183 \ - --hash=sha256:891f712ce54e0d631370e1f4997b3f182f3368179198efc30d477c75d1f44942 \ - --hash=sha256:95c68a4b9b7828ba0428f8f7e3109c5d476ca44996ed9a5f8aac6269296e2d59 \ - --hash=sha256:96a8918a78d5d64e07c8ea4ed2bc44354e3f93f46a4866a40e8db934e4c0d74b \ - --hash=sha256:9c3cf890c3c0ecfe1510a452a165431b5831e24160c5fcf2071f0f85ca5a47cd \ - --hash=sha256:9f58099ad7affc0754ae42e6d87443299f15d739b0ce03c76f515153a5cda06c \ - --hash=sha256:a0b9e622c3b2b8d0ce32f77eba617ab0d6768b82836391e4f8f9e2074582bf02 \ - --hash=sha256:a7f9cbea4245ee36190f85fe1814e2d7b1e5f2186381b082f5d59f99b7f11328 \ - --hash=sha256:bab4aebd525218bab4ee615786c4581952eadc16b1ff031813a2fd51f0cc7b08 \ - --hash=sha256:c124b8c8779bf2d35d9b721e52d4adb41c9bfbde45e6a3f25f0820caa9aba73f \ - --hash=sha256:c9da0a39b53d2fab3e5467329ed50e951eb91386e9d0d5b12daf593973c3b168 \ - --hash=sha256:ca60076c388728d3b6ac3846842474f4250c91efbfe5afa872d3ffd69dd4b318 \ - --hash=sha256:cb6994fff247987c66a8a4e550ef374671c2b82e3c0d2115e689d21e511a652d \ - --hash=sha256:d1c1d6236feab51200272d79b3d3e0f12cf2cbb12b208c835b175a21efdb0a73 \ - --hash=sha256:dd7760a88a8d3d705ff562aa93f8445ead54f58fd482e4f9e2bafb7e177375d4 \ - --hash=sha256:dda4d8a3bb0b50f540f6ff4b6033f3a74e8bf0bd5320b70fab2c03e512a62812 \ - --hash=sha256:e0f1ff55dde0ebcfbef027edc21f71c205845585fffe30d4ec4979416613e9b3 \ - --hash=sha256:e7a539b9be7b9c00f11ef16b55486141bc2cdb0c54762f84e3c6fc091917436d \ - --hash=sha256:eb0b14523758e37802f27b7f8cd973f5f3d33be7613952c0df904b68c4842f0e \ - --hash=sha256:ed447680ff21c14aaceb6a9f99a5f639f583ccfe4ce1a5e1d48eb41c3d6b3217 \ - --hash=sha256:f52a4ad2568314ee713715b1e2d79ab55fab11e8b304fd1462ff5cccf4264b3e \ - --hash=sha256:fbd60c6aaa07c31d7754edbc2334aef50601b7f1ada67a96eb1eb57c7c72378f \ - --hash=sha256:fc28e0db232c62ca0c3600884933178f0825c99be4474cdd645e378a10588125 \ - --hash=sha256:fe31de3002e7b08eb20823b3735b97c86c5926dd0581c7710a680b418a8709d4 \ - --hash=sha256:fec221a051150eeddfdfcff162e6db92c65ecf46cb0f7bb1bf812a1520ec026b \ - --hash=sha256:ff71073ebf0e42258a42a0b34f2c09ec384977e7f6808999102eedd5b49920e3 +google-crc32c==1.5.0 \ + --hash=sha256:024894d9d3cfbc5943f8f230e23950cd4906b2fe004c72e29b209420a1e6b05a \ + --hash=sha256:02c65b9817512edc6a4ae7c7e987fea799d2e0ee40c53ec573a692bee24de876 \ + --hash=sha256:02ebb8bf46c13e36998aeaad1de9b48f4caf545e91d14041270d9dca767b780c \ + --hash=sha256:07eb3c611ce363c51a933bf6bd7f8e3878a51d124acfc89452a75120bc436289 \ + --hash=sha256:1034d91442ead5a95b5aaef90dbfaca8633b0247d1e41621d1e9f9db88c36298 \ + --hash=sha256:116a7c3c616dd14a3de8c64a965828b197e5f2d121fedd2f8c5585c547e87b02 \ + --hash=sha256:19e0a019d2c4dcc5e598cd4a4bc7b008546b0358bd322537c74ad47a5386884f \ + --hash=sha256:1c7abdac90433b09bad6c43a43af253e688c9cfc1c86d332aed13f9a7c7f65e2 \ + --hash=sha256:1e986b206dae4476f41bcec1faa057851f3889503a70e1bdb2378d406223994a \ + --hash=sha256:272d3892a1e1a2dbc39cc5cde96834c236d5327e2122d3aaa19f6614531bb6eb \ + --hash=sha256:278d2ed7c16cfc075c91378c4f47924c0625f5fc84b2d50d921b18b7975bd210 \ + --hash=sha256:2ad40e31093a4af319dadf503b2467ccdc8f67c72e4bcba97f8c10cb078207b5 \ + --hash=sha256:2e920d506ec85eb4ba50cd4228c2bec05642894d4c73c59b3a2fe20346bd00ee \ + --hash=sha256:3359fc442a743e870f4588fcf5dcbc1bf929df1fad8fb9905cd94e5edb02e84c \ + --hash=sha256:37933ec6e693e51a5b07505bd05de57eee12f3e8c32b07da7e73669398e6630a \ + --hash=sha256:398af5e3ba9cf768787eef45c803ff9614cc3e22a5b2f7d7ae116df8b11e3314 \ + --hash=sha256:3b747a674c20a67343cb61d43fdd9207ce5da6a99f629c6e2541aa0e89215bcd \ + --hash=sha256:461665ff58895f508e2866824a47bdee72497b091c730071f2b7575d5762ab65 \ + --hash=sha256:4c6fdd4fccbec90cc8a01fc00773fcd5fa28db683c116ee3cb35cd5da9ef6c37 \ + --hash=sha256:5829b792bf5822fd0a6f6eb34c5f81dd074f01d570ed7f36aa101d6fc7a0a6e4 \ + --hash=sha256:596d1f98fc70232fcb6590c439f43b350cb762fb5d61ce7b0e9db4539654cc13 \ + --hash=sha256:5ae44e10a8e3407dbe138984f21e536583f2bba1be9491239f942c2464ac0894 \ + --hash=sha256:635f5d4dd18758a1fbd1049a8e8d2fee4ffed124462d837d1a02a0e009c3ab31 \ + --hash=sha256:64e52e2b3970bd891309c113b54cf0e4384762c934d5ae56e283f9a0afcd953e \ + --hash=sha256:66741ef4ee08ea0b2cc3c86916ab66b6aef03768525627fd6a1b34968b4e3709 \ + --hash=sha256:67b741654b851abafb7bc625b6d1cdd520a379074e64b6a128e3b688c3c04740 \ + --hash=sha256:6ac08d24c1f16bd2bf5eca8eaf8304812f44af5cfe5062006ec676e7e1d50afc \ + --hash=sha256:6f998db4e71b645350b9ac28a2167e6632c239963ca9da411523bb439c5c514d \ + --hash=sha256:72218785ce41b9cfd2fc1d6a017dc1ff7acfc4c17d01053265c41a2c0cc39b8c \ + --hash=sha256:74dea7751d98034887dbd821b7aae3e1d36eda111d6ca36c206c44478035709c \ + --hash=sha256:759ce4851a4bb15ecabae28f4d2e18983c244eddd767f560165563bf9aefbc8d \ + --hash=sha256:77e2fd3057c9d78e225fa0a2160f96b64a824de17840351b26825b0848022906 \ + --hash=sha256:7c074fece789b5034b9b1404a1f8208fc2d4c6ce9decdd16e8220c5a793e6f61 \ + --hash=sha256:7c42c70cd1d362284289c6273adda4c6af8039a8ae12dc451dcd61cdabb8ab57 \ + --hash=sha256:7f57f14606cd1dd0f0de396e1e53824c371e9544a822648cd76c034d209b559c \ + --hash=sha256:83c681c526a3439b5cf94f7420471705bbf96262f49a6fe546a6db5f687a3d4a \ + --hash=sha256:8485b340a6a9e76c62a7dce3c98e5f102c9219f4cfbf896a00cf48caf078d438 \ + --hash=sha256:84e6e8cd997930fc66d5bb4fde61e2b62ba19d62b7abd7a69920406f9ecca946 \ + --hash=sha256:89284716bc6a5a415d4eaa11b1726d2d60a0cd12aadf5439828353662ede9dd7 \ + --hash=sha256:8b87e1a59c38f275c0e3676fc2ab6d59eccecfd460be267ac360cc31f7bcde96 \ + --hash=sha256:8f24ed114432de109aa9fd317278518a5af2d31ac2ea6b952b2f7782b43da091 \ + --hash=sha256:98cb4d057f285bd80d8778ebc4fde6b4d509ac3f331758fb1528b733215443ae \ + --hash=sha256:998679bf62b7fb599d2878aa3ed06b9ce688b8974893e7223c60db155f26bd8d \ + --hash=sha256:9ba053c5f50430a3fcfd36f75aff9caeba0440b2d076afdb79a318d6ca245f88 \ + --hash=sha256:9c99616c853bb585301df6de07ca2cadad344fd1ada6d62bb30aec05219c45d2 \ + --hash=sha256:a1fd716e7a01f8e717490fbe2e431d2905ab8aa598b9b12f8d10abebb36b04dd \ + --hash=sha256:a2355cba1f4ad8b6988a4ca3feed5bff33f6af2d7f134852cf279c2aebfde541 \ + --hash=sha256:b1f8133c9a275df5613a451e73f36c2aea4fe13c5c8997e22cf355ebd7bd0728 \ + --hash=sha256:b8667b48e7a7ef66afba2c81e1094ef526388d35b873966d8a9a447974ed9178 \ + --hash=sha256:ba1eb1843304b1e5537e1fca632fa894d6f6deca8d6389636ee5b4797affb968 \ + --hash=sha256:be82c3c8cfb15b30f36768797a640e800513793d6ae1724aaaafe5bf86f8f346 \ + --hash=sha256:c02ec1c5856179f171e032a31d6f8bf84e5a75c45c33b2e20a3de353b266ebd8 \ + --hash=sha256:c672d99a345849301784604bfeaeba4db0c7aae50b95be04dd651fd2a7310b93 \ + --hash=sha256:c6c777a480337ac14f38564ac88ae82d4cd238bf293f0a22295b66eb89ffced7 \ + --hash=sha256:cae0274952c079886567f3f4f685bcaf5708f0a23a5f5216fdab71f81a6c0273 \ + --hash=sha256:cd67cf24a553339d5062eff51013780a00d6f97a39ca062781d06b3a73b15462 \ + --hash=sha256:d3515f198eaa2f0ed49f8819d5732d70698c3fa37384146079b3799b97667a94 \ + --hash=sha256:d5280312b9af0976231f9e317c20e4a61cd2f9629b7bfea6a693d1878a264ebd \ + --hash=sha256:de06adc872bcd8c2a4e0dc51250e9e65ef2ca91be023b9d13ebd67c2ba552e1e \ + --hash=sha256:e1674e4307fa3024fc897ca774e9c7562c957af85df55efe2988ed9056dc4e57 \ + --hash=sha256:e2096eddb4e7c7bdae4bd69ad364e55e07b8316653234a56552d9c988bd2d61b \ + --hash=sha256:e560628513ed34759456a416bf86b54b2476c59144a9138165c9a1575801d0d9 \ + --hash=sha256:edfedb64740750e1a3b16152620220f51d58ff1b4abceb339ca92e934775c27a \ + --hash=sha256:f13cae8cc389a440def0c8c52057f37359014ccbc9dc1f0827936bcd367c6100 \ + --hash=sha256:f314013e7dcd5cf45ab1945d92e713eec788166262ae8deb2cfacd53def27325 \ + --hash=sha256:f583edb943cf2e09c60441b910d6a20b4d9d626c75a36c8fcac01a6c96c01183 \ + --hash=sha256:fd8536e902db7e365f49e7d9029283403974ccf29b13fc7028b97e2295b33556 \ + --hash=sha256:fe70e325aa68fa4b5edf7d1a4b6f691eb04bbccac0ace68e34820d283b5f80d4 # via google-resumable-media -google-resumable-media==2.3.3 \ - --hash=sha256:27c52620bd364d1c8116eaac4ea2afcbfb81ae9139fb3199652fcac1724bfb6c \ - --hash=sha256:5b52774ea7a829a8cdaa8bd2d4c3d4bc660c91b30857ab2668d0eb830f4ea8c5 +google-resumable-media==2.4.0 \ + --hash=sha256:2aa004c16d295c8f6c33b2b4788ba59d366677c0a25ae7382436cb30f776deaa \ + --hash=sha256:8d5518502f92b9ecc84ac46779bd4f09694ecb3ba38a3e7ca737a86d15cbca1f # via google-cloud-storage googleapis-common-protos==1.56.4 \ --hash=sha256:8eb2cbc91b69feaf23e32452a7ae60e791e09967d81d4fcc7fc388182d1bd394 \ --hash=sha256:c25873c47279387cfdcbdafa36149887901d36202cb645a0e4f29686bf6e4417 # via google-api-core -idna==3.3 \ - --hash=sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff \ - --hash=sha256:9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d +idna==3.4 \ + --hash=sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4 \ + --hash=sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2 # via requests -importlib-metadata==4.12.0 \ - --hash=sha256:637245b8bab2b6502fcbc752cc4b7a6f6243bb02b31c5c26156ad103d3d45670 \ - --hash=sha256:7401a975809ea1fdc658c3aa4f78cc2195a0e019c5cbc4c06122884e9ae80c23 +importlib-metadata==5.0.0 \ + --hash=sha256:da31db32b304314d044d3c12c79bd59e307889b287ad12ff387b3500835fc2ab \ + --hash=sha256:ddb0e35065e8938f867ed4928d0ae5bf2a53b7773871bfe6bcc7e4fcdc7dea43 # via # -r requirements.in # twine -jaraco-classes==3.2.2 \ - --hash=sha256:6745f113b0b588239ceb49532aa09c3ebb947433ce311ef2f8e3ad64ebb74594 \ - --hash=sha256:e6ef6fd3fcf4579a7a019d87d1e56a883f4e4c35cfe925f86731abc58804e647 +jaraco-classes==3.2.3 \ + --hash=sha256:2353de3288bc6b82120752201c6b1c1a14b058267fa424ed5ce5984e3b922158 \ + --hash=sha256:89559fa5c1d3c34eff6f631ad80bb21f378dbcbb35dd161fd2c6b93f5be2f98a # via keyring jeepney==0.8.0 \ --hash=sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806 \ @@ -255,9 +284,9 @@ jinja2==3.1.2 \ --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 # via gcp-releasetool -keyring==23.9.0 \ - --hash=sha256:4c32a31174faaee48f43a7e2c7e9c3216ec5e95acf22a2bebfb4a1d05056ee44 \ - --hash=sha256:98f060ec95ada2ab910c195a2d4317be6ef87936a766b239c46aa3c7aac4f0db +keyring==23.9.3 \ + --hash=sha256:69732a15cb1433bdfbc3b980a8a36a04878a6cfd7cb99f497b573f31618001c0 \ + --hash=sha256:69b01dd83c42f590250fe7a1f503fc229b14de83857314b1933a3ddbf595c4a5 # via # gcp-releasetool # twine @@ -303,9 +332,9 @@ markupsafe==2.1.1 \ --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \ --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7 # via jinja2 -more-itertools==8.14.0 \ - --hash=sha256:1bc4f91ee5b1b31ac7ceacc17c09befe6a40a503907baf9c839c229b5095cfd2 \ - --hash=sha256:c09443cd3d5438b8dafccd867a6bc1cb0894389e90cb53d227456b0b0bccb750 +more-itertools==9.0.0 \ + --hash=sha256:250e83d7e81d0c87ca6bd942e6aeab8cc9daa6096d12c5308f3f92fa5e5c1f41 \ + --hash=sha256:5a6257e40878ef0520b1803990e3e22303a41b5714006c32a3fd8304b26ea1ab # via jaraco-classes nox==2022.8.7 \ --hash=sha256:1b894940551dc5c389f9271d197ca5d655d40bdc6ccf93ed6880e4042760a34b \ @@ -325,34 +354,34 @@ platformdirs==2.5.2 \ --hash=sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788 \ --hash=sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19 # via virtualenv -protobuf==3.20.2 \ - --hash=sha256:03d76b7bd42ac4a6e109742a4edf81ffe26ffd87c5993126d894fe48a120396a \ - --hash=sha256:09e25909c4297d71d97612f04f41cea8fa8510096864f2835ad2f3b3df5a5559 \ - --hash=sha256:18e34a10ae10d458b027d7638a599c964b030c1739ebd035a1dfc0e22baa3bfe \ - --hash=sha256:291fb4307094bf5ccc29f424b42268640e00d5240bf0d9b86bf3079f7576474d \ - --hash=sha256:2c0b040d0b5d5d207936ca2d02f00f765906622c07d3fa19c23a16a8ca71873f \ - --hash=sha256:384164994727f274cc34b8abd41a9e7e0562801361ee77437099ff6dfedd024b \ - --hash=sha256:3cb608e5a0eb61b8e00fe641d9f0282cd0eedb603be372f91f163cbfbca0ded0 \ - --hash=sha256:5d9402bf27d11e37801d1743eada54372f986a372ec9679673bfcc5c60441151 \ - --hash=sha256:712dca319eee507a1e7df3591e639a2b112a2f4a62d40fe7832a16fd19151750 \ - --hash=sha256:7a5037af4e76c975b88c3becdf53922b5ffa3f2cddf657574a4920a3b33b80f3 \ - --hash=sha256:8228e56a865c27163d5d1d1771d94b98194aa6917bcfb6ce139cbfa8e3c27334 \ - --hash=sha256:84a1544252a933ef07bb0b5ef13afe7c36232a774affa673fc3636f7cee1db6c \ - --hash=sha256:84fe5953b18a383fd4495d375fe16e1e55e0a3afe7b4f7b4d01a3a0649fcda9d \ - --hash=sha256:9c673c8bfdf52f903081816b9e0e612186684f4eb4c17eeb729133022d6032e3 \ - --hash=sha256:9f876a69ca55aed879b43c295a328970306e8e80a263ec91cf6e9189243c613b \ - --hash=sha256:a9e5ae5a8e8985c67e8944c23035a0dff2c26b0f5070b2f55b217a1c33bbe8b1 \ - --hash=sha256:b4fdb29c5a7406e3f7ef176b2a7079baa68b5b854f364c21abe327bbeec01cdb \ - --hash=sha256:c184485e0dfba4dfd451c3bd348c2e685d6523543a0f91b9fd4ae90eb09e8422 \ - --hash=sha256:c9cdf251c582c16fd6a9f5e95836c90828d51b0069ad22f463761d27c6c19019 \ - --hash=sha256:e39cf61bb8582bda88cdfebc0db163b774e7e03364bbf9ce1ead13863e81e359 \ - --hash=sha256:e8fbc522303e09036c752a0afcc5c0603e917222d8bedc02813fd73b4b4ed804 \ - --hash=sha256:f34464ab1207114e73bba0794d1257c150a2b89b7a9faf504e00af7c9fd58978 \ - --hash=sha256:f52dabc96ca99ebd2169dadbe018824ebda08a795c7684a0b7d203a290f3adb0 +protobuf==3.20.3 \ + --hash=sha256:03038ac1cfbc41aa21f6afcbcd357281d7521b4157926f30ebecc8d4ea59dcb7 \ + --hash=sha256:28545383d61f55b57cf4df63eebd9827754fd2dc25f80c5253f9184235db242c \ + --hash=sha256:2e3427429c9cffebf259491be0af70189607f365c2f41c7c3764af6f337105f2 \ + --hash=sha256:398a9e0c3eaceb34ec1aee71894ca3299605fa8e761544934378bbc6c97de23b \ + --hash=sha256:44246bab5dd4b7fbd3c0c80b6f16686808fab0e4aca819ade6e8d294a29c7050 \ + --hash=sha256:447d43819997825d4e71bf5769d869b968ce96848b6479397e29fc24c4a5dfe9 \ + --hash=sha256:67a3598f0a2dcbc58d02dd1928544e7d88f764b47d4a286202913f0b2801c2e7 \ + --hash=sha256:74480f79a023f90dc6e18febbf7b8bac7508420f2006fabd512013c0c238f454 \ + --hash=sha256:819559cafa1a373b7096a482b504ae8a857c89593cf3a25af743ac9ecbd23480 \ + --hash=sha256:899dc660cd599d7352d6f10d83c95df430a38b410c1b66b407a6b29265d66469 \ + --hash=sha256:8c0c984a1b8fef4086329ff8dd19ac77576b384079247c770f29cc8ce3afa06c \ + --hash=sha256:9aae4406ea63d825636cc11ffb34ad3379335803216ee3a856787bcf5ccc751e \ + --hash=sha256:a7ca6d488aa8ff7f329d4c545b2dbad8ac31464f1d8b1c87ad1346717731e4db \ + --hash=sha256:b6cc7ba72a8850621bfec987cb72623e703b7fe2b9127a161ce61e61558ad905 \ + --hash=sha256:bf01b5720be110540be4286e791db73f84a2b721072a3711efff6c324cdf074b \ + --hash=sha256:c02ce36ec760252242a33967d51c289fd0e1c0e6e5cc9397e2279177716add86 \ + --hash=sha256:d9e4432ff660d67d775c66ac42a67cf2453c27cb4d738fc22cb53b5d84c135d4 \ + --hash=sha256:daa564862dd0d39c00f8086f88700fdbe8bc717e993a21e90711acfed02f2402 \ + --hash=sha256:de78575669dddf6099a8a0f46a27e82a1783c557ccc38ee620ed8cc96d3be7d7 \ + --hash=sha256:e64857f395505ebf3d2569935506ae0dfc4a15cb80dc25261176c784662cdcc4 \ + --hash=sha256:f4bd856d702e5b0d96a00ec6b307b0f51c1982c2bf9c0052cf9019e9a544ba99 \ + --hash=sha256:f4c42102bc82a51108e449cbb32b19b180022941c727bac0cfd50170341f16ee # via # gcp-docuploader # gcp-releasetool # google-api-core + # googleapis-common-protos py==1.11.0 \ --hash=sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719 \ --hash=sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378 @@ -377,9 +406,9 @@ pygments==2.13.0 \ # via # readme-renderer # rich -pyjwt==2.4.0 \ - --hash=sha256:72d1d253f32dbd4f5c88eaf1fdc62f3a19f676ccbadb9dbc5d07e951b2b26daf \ - --hash=sha256:d42908208c699b3b973cbeb01a969ba6a96c821eefb1c5bfe4c390c01d67abba +pyjwt==2.6.0 \ + --hash=sha256:69285c7e31fc44f68a1feb309e948e0df53259d579295e6cfe2b1792329f05fd \ + --hash=sha256:d83c3d892a77bbb74d3e1a2cfa90afaadb60945205d1095d9221f04466f64c14 # via gcp-releasetool pyparsing==3.0.9 \ --hash=sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb \ @@ -392,9 +421,9 @@ python-dateutil==2.8.2 \ --hash=sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86 \ --hash=sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9 # via gcp-releasetool -readme-renderer==37.0 \ - --hash=sha256:07b7ea234e03e58f77cc222e206e6abb8f4c0435becce5104794ee591f9301c5 \ - --hash=sha256:9fa416704703e509eeb900696751c908ddeb2011319d93700d8f18baff887a69 +readme-renderer==37.3 \ + --hash=sha256:cd653186dfc73055656f090f227f5cb22a046d7f71a841dfa305f55c9a513273 \ + --hash=sha256:f67a16caedfa71eef48a31b39708637a6f4664c4394801a7b0d6432d13907343 # via twine requests==2.28.1 \ --hash=sha256:7c5599b102feddaa661c826c56ab4fee28bfd17f5abca1ebbe3e7f19d7c97983 \ @@ -405,17 +434,17 @@ requests==2.28.1 \ # google-cloud-storage # requests-toolbelt # twine -requests-toolbelt==0.9.1 \ - --hash=sha256:380606e1d10dc85c3bd47bf5a6095f815ec007be7a8b69c878507068df059e6f \ - --hash=sha256:968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0 +requests-toolbelt==0.10.1 \ + --hash=sha256:18565aa58116d9951ac39baa288d3adb5b3ff975c4f25eee78555d89e8f247f7 \ + --hash=sha256:62e09f7ff5ccbda92772a29f394a49c3ad6cb181d568b1337626b2abb628a63d # via twine rfc3986==2.0.0 \ --hash=sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd \ --hash=sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c # via twine -rich==12.5.1 \ - --hash=sha256:2eb4e6894cde1e017976d2975ac210ef515d7548bc595ba20e195fb9628acdeb \ - --hash=sha256:63a5c5ce3673d3d5fbbf23cd87e11ab84b6b451436f1b7f19ec54b6bc36ed7ca +rich==12.6.0 \ + --hash=sha256:a4eb26484f2c82589bd9a17c73d32a010b1e29d89f1604cd9bf3a2097b81bb5e \ + --hash=sha256:ba3a3775974105c221d31141f2c116f4fd65c5ceb0698657a11e9f295ec93fd0 # via twine rsa==4.9 \ --hash=sha256:90260d9058e514786967344d0ef75fa8727eed8a7d2e43ce9f4bcf1b536174f7 \ @@ -437,9 +466,9 @@ twine==4.0.1 \ --hash=sha256:42026c18e394eac3e06693ee52010baa5313e4811d5a11050e7d48436cf41b9e \ --hash=sha256:96b1cf12f7ae611a4a40b6ae8e9570215daff0611828f5fe1f37a16255ab24a0 # via -r requirements.in -typing-extensions==4.3.0 \ - --hash=sha256:25642c956049920a5aa49edcdd6ab1e06d7e5d467fc00e0506c44ac86fbfca02 \ - --hash=sha256:e6d2677a32f47fc7eb2795db1dd15c1f34eff616bcaf2cfb5e997f854fa1c4a6 +typing-extensions==4.4.0 \ + --hash=sha256:1511434bb92bf8dd198c12b1cc812e800d4181cfcb867674e0f8279cc93087aa \ + --hash=sha256:16fa4864408f655d35ec496218b85f79b3437c829e93320c7c9215ccfd92489e # via -r requirements.in urllib3==1.26.12 \ --hash=sha256:3fa96cf423e6987997fc326ae8df396db2a8b7c667747d47ddd8ecba91f4a74e \ @@ -447,9 +476,9 @@ urllib3==1.26.12 \ # via # requests # twine -virtualenv==20.16.4 \ - --hash=sha256:014f766e4134d0008dcaa1f95bafa0fb0f575795d07cae50b1bee514185d6782 \ - --hash=sha256:035ed57acce4ac35c82c9d8802202b0e71adac011a511ff650cbcf9635006a22 +virtualenv==20.16.6 \ + --hash=sha256:186ca84254abcbde98180fd17092f9628c5fe742273c02724972a1d8a2035108 \ + --hash=sha256:530b850b523c6449406dfba859d6345e48ef19b8439606c5d74d7d3c9e14d76e # via nox webencodings==0.5.1 \ --hash=sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78 \ @@ -459,13 +488,13 @@ wheel==0.37.1 \ --hash=sha256:4bdcd7d840138086126cd09254dc6195fb4fc6f01c050a1d7236f2630db1d22a \ --hash=sha256:e9a504e793efbca1b8e0e9cb979a249cf4a0a7b5b8c9e8b65a5e39d49529c1c4 # via -r requirements.in -zipp==3.8.1 \ - --hash=sha256:05b45f1ee8f807d0cc928485ca40a07cb491cf092ff587c0df9cb1fd154848d2 \ - --hash=sha256:47c40d7fe183a6f21403a199b3e4192cca5774656965b0a4988ad2f8feb5f009 +zipp==3.10.0 \ + --hash=sha256:4fcb6f278987a6605757302a6e40e896257570d11c51628968ccb2a47e80c6c1 \ + --hash=sha256:7a7262fd930bd3e36c50b9a64897aec3fafff3dfdeec9623ae22b40e93f99bb8 # via importlib-metadata # The following packages are considered to be unsafe in a requirements file: -setuptools==65.2.0 \ - --hash=sha256:7f4bc85450898a09f76ebf28b72fa25bc7111f6c7d665d514a60bba9c75ef2a9 \ - --hash=sha256:a3ca5857c89f82f5c9410e8508cb32f4872a3bafd4aa7ae122a24ca33bccc750 +setuptools==65.5.0 \ + --hash=sha256:512e5536220e38146176efb833d4a62aa726b7bbff82cfbc8ba9eaa3996e0b17 \ + --hash=sha256:f62ea9da9ed6289bfe868cd6845968a2c854d1427f8548d52cae02a42b4f0356 # via -r requirements.in diff --git a/noxfile.py b/noxfile.py index ffe9f354..29d02000 100644 --- a/noxfile.py +++ b/noxfile.py @@ -278,7 +278,11 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") + session.install( + "sphinx==4.0.1", + "alabaster", + "recommonmark", + ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -301,7 +305,10 @@ def docfx(session): session.install("-e", ".") session.install( - "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml" + "sphinx==4.0.1", + "alabaster", + "recommonmark", + "gcp-sphinx-docfx-yaml", ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) From ab96687fb5834fe8905b00d342f181d15954dee1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 18 Nov 2022 11:48:34 +0000 Subject: [PATCH 220/254] chore(python): update release script dependencies [autoapprove] (#404) Source-Link: https://togithub.com/googleapis/synthtool/commit/25083af347468dd5f90f69627420f7d452b6c50e Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:e6cbd61f1838d9ff6a31436dfc13717f372a7482a82fc1863ca954ec47bff8c8 --- .github/.OwlBot.lock.yaml | 2 +- .github/workflows/docs.yml | 4 +-- .github/workflows/lint.yml | 2 +- .github/workflows/unittest.yml | 2 +- .kokoro/docker/docs/Dockerfile | 12 +++---- .kokoro/requirements.in | 4 ++- .kokoro/requirements.txt | 61 ++++++++++++++++++---------------- noxfile.py | 4 +-- 8 files changed, 48 insertions(+), 43 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 12edee77..3f1ccc08 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:452901c74a22f9b9a3bd02bce780b8e8805c97270d424684bff809ce5be8c2a2 + digest: sha256:e6cbd61f1838d9ff6a31436dfc13717f372a7482a82fc1863ca954ec47bff8c8 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 7092a139..e97d89e4 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -12,7 +12,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.9" - name: Install nox run: | python -m pip install --upgrade setuptools pip wheel @@ -28,7 +28,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.9" - name: Install nox run: | python -m pip install --upgrade setuptools pip wheel diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index d2aee5b7..16d5a9e9 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -12,7 +12,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.8" - name: Install nox run: | python -m pip install --upgrade setuptools pip wheel diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 87ade4d5..23000c05 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -41,7 +41,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.8" - name: Install coverage run: | python -m pip install --upgrade setuptools pip wheel diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile index 238b87b9..f8137d0a 100644 --- a/.kokoro/docker/docs/Dockerfile +++ b/.kokoro/docker/docs/Dockerfile @@ -60,16 +60,16 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* \ && rm -f /var/cache/apt/archives/*.deb -###################### Install python 3.8.11 +###################### Install python 3.9.13 -# Download python 3.8.11 -RUN wget https://www.python.org/ftp/python/3.8.11/Python-3.8.11.tgz +# Download python 3.9.13 +RUN wget https://www.python.org/ftp/python/3.9.13/Python-3.9.13.tgz # Extract files -RUN tar -xvf Python-3.8.11.tgz +RUN tar -xvf Python-3.9.13.tgz -# Install python 3.8.11 -RUN ./Python-3.8.11/configure --enable-optimizations +# Install python 3.9.13 +RUN ./Python-3.9.13/configure --enable-optimizations RUN make altinstall ###################### Install pip diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in index 7718391a..cbd7e77f 100644 --- a/.kokoro/requirements.in +++ b/.kokoro/requirements.in @@ -5,4 +5,6 @@ typing-extensions twine wheel setuptools -nox \ No newline at end of file +nox +charset-normalizer<3 +click<8.1.0 diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 31425f16..9c1b9be3 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -93,11 +93,14 @@ cffi==1.15.1 \ charset-normalizer==2.1.1 \ --hash=sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845 \ --hash=sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f - # via requests + # via + # -r requirements.in + # requests click==8.0.4 \ --hash=sha256:6a7a62563bbfabfda3a38f3023a1db4a35978c0abd76f6c9605ecd6554d6d9b1 \ --hash=sha256:8458d7b1287c5fb128c90e23381cf99dcde74beaf6c7ff6384ce84d6fe090adb # via + # -r requirements.in # gcp-docuploader # gcp-releasetool colorlog==6.7.0 \ @@ -156,9 +159,9 @@ gcp-docuploader==0.6.4 \ --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf # via -r requirements.in -gcp-releasetool==1.9.1 \ - --hash=sha256:952f4055d5d986b070ae2a71c4410b250000f9cc5a1e26398fcd55a5bbc5a15f \ - --hash=sha256:d0d3c814a97c1a237517e837d8cfa668ced8df4b882452578ecef4a4e79c583b +gcp-releasetool==1.10.0 \ + --hash=sha256:72a38ca91b59c24f7e699e9227c90cbe4dd71b789383cb0164b088abae294c83 \ + --hash=sha256:8c7c99320208383d4bb2b808c6880eb7a81424afe7cdba3c8d84b25f4f0e097d # via -r requirements.in google-api-core==2.10.2 \ --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ @@ -166,9 +169,9 @@ google-api-core==2.10.2 \ # via # google-cloud-core # google-cloud-storage -google-auth==2.14.0 \ - --hash=sha256:1ad5b0e6eba5f69645971abb3d2c197537d5914070a8c6d30299dfdb07c5c700 \ - --hash=sha256:cf24817855d874ede2efd071aa22125445f555de1685b739a9782fcf408c2a3d +google-auth==2.14.1 \ + --hash=sha256:ccaa901f31ad5cbb562615eb8b664b3dd0bf5404a67618e642307f00613eda4d \ + --hash=sha256:f5d8701633bebc12e0deea4df8abd8aff31c28b355360597f7f2ee60f2e4d016 # via # gcp-releasetool # google-api-core @@ -178,9 +181,9 @@ google-cloud-core==2.3.2 \ --hash=sha256:8417acf6466be2fa85123441696c4badda48db314c607cf1e5d543fa8bdc22fe \ --hash=sha256:b9529ee7047fd8d4bf4a2182de619154240df17fbe60ead399078c1ae152af9a # via google-cloud-storage -google-cloud-storage==2.5.0 \ - --hash=sha256:19a26c66c317ce542cea0830b7e787e8dac2588b6bfa4d3fd3b871ba16305ab0 \ - --hash=sha256:382f34b91de2212e3c2e7b40ec079d27ee2e3dbbae99b75b1bcd8c63063ce235 +google-cloud-storage==2.6.0 \ + --hash=sha256:104ca28ae61243b637f2f01455cc8a05e8f15a2a18ced96cb587241cdd3820f5 \ + --hash=sha256:4ad0415ff61abdd8bb2ae81c1f8f7ec7d91a1011613f2db87c614c550f97bfe9 # via gcp-docuploader google-crc32c==1.5.0 \ --hash=sha256:024894d9d3cfbc5943f8f230e23950cd4906b2fe004c72e29b209420a1e6b05a \ @@ -256,9 +259,9 @@ google-resumable-media==2.4.0 \ --hash=sha256:2aa004c16d295c8f6c33b2b4788ba59d366677c0a25ae7382436cb30f776deaa \ --hash=sha256:8d5518502f92b9ecc84ac46779bd4f09694ecb3ba38a3e7ca737a86d15cbca1f # via google-cloud-storage -googleapis-common-protos==1.56.4 \ - --hash=sha256:8eb2cbc91b69feaf23e32452a7ae60e791e09967d81d4fcc7fc388182d1bd394 \ - --hash=sha256:c25873c47279387cfdcbdafa36149887901d36202cb645a0e4f29686bf6e4417 +googleapis-common-protos==1.57.0 \ + --hash=sha256:27a849d6205838fb6cc3c1c21cb9800707a661bb21c6ce7fb13e99eb1f8a0c46 \ + --hash=sha256:a9f4a1d7f6d9809657b7f1316a1aa527f6664891531bcfcc13b6696e685f443c # via google-api-core idna==3.4 \ --hash=sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4 \ @@ -269,6 +272,7 @@ importlib-metadata==5.0.0 \ --hash=sha256:ddb0e35065e8938f867ed4928d0ae5bf2a53b7773871bfe6bcc7e4fcdc7dea43 # via # -r requirements.in + # keyring # twine jaraco-classes==3.2.3 \ --hash=sha256:2353de3288bc6b82120752201c6b1c1a14b058267fa424ed5ce5984e3b922158 \ @@ -284,9 +288,9 @@ jinja2==3.1.2 \ --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 # via gcp-releasetool -keyring==23.9.3 \ - --hash=sha256:69732a15cb1433bdfbc3b980a8a36a04878a6cfd7cb99f497b573f31618001c0 \ - --hash=sha256:69b01dd83c42f590250fe7a1f503fc229b14de83857314b1933a3ddbf595c4a5 +keyring==23.11.0 \ + --hash=sha256:3dd30011d555f1345dec2c262f0153f2f0ca6bca041fb1dc4588349bb4c0ac1e \ + --hash=sha256:ad192263e2cdd5f12875dedc2da13534359a7e760e77f8d04b50968a821c2361 # via # gcp-releasetool # twine @@ -350,9 +354,9 @@ pkginfo==1.8.3 \ --hash=sha256:848865108ec99d4901b2f7e84058b6e7660aae8ae10164e015a6dcf5b242a594 \ --hash=sha256:a84da4318dd86f870a9447a8c98340aa06216bfc6f2b7bdc4b8766984ae1867c # via twine -platformdirs==2.5.2 \ - --hash=sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788 \ - --hash=sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19 +platformdirs==2.5.4 \ + --hash=sha256:1006647646d80f16130f052404c6b901e80ee4ed6bef6792e1f238a8969106f7 \ + --hash=sha256:af0276409f9a02373d540bf8480021a048711d572745aef4b7842dad245eba10 # via virtualenv protobuf==3.20.3 \ --hash=sha256:03038ac1cfbc41aa21f6afcbcd357281d7521b4157926f30ebecc8d4ea59dcb7 \ @@ -381,7 +385,6 @@ protobuf==3.20.3 \ # gcp-docuploader # gcp-releasetool # google-api-core - # googleapis-common-protos py==1.11.0 \ --hash=sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719 \ --hash=sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378 @@ -476,17 +479,17 @@ urllib3==1.26.12 \ # via # requests # twine -virtualenv==20.16.6 \ - --hash=sha256:186ca84254abcbde98180fd17092f9628c5fe742273c02724972a1d8a2035108 \ - --hash=sha256:530b850b523c6449406dfba859d6345e48ef19b8439606c5d74d7d3c9e14d76e +virtualenv==20.16.7 \ + --hash=sha256:8691e3ff9387f743e00f6bb20f70121f5e4f596cae754531f2b3b3a1b1ac696e \ + --hash=sha256:efd66b00386fdb7dbe4822d172303f40cd05e50e01740b19ea42425cbe653e29 # via nox webencodings==0.5.1 \ --hash=sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78 \ --hash=sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923 # via bleach -wheel==0.37.1 \ - --hash=sha256:4bdcd7d840138086126cd09254dc6195fb4fc6f01c050a1d7236f2630db1d22a \ - --hash=sha256:e9a504e793efbca1b8e0e9cb979a249cf4a0a7b5b8c9e8b65a5e39d49529c1c4 +wheel==0.38.4 \ + --hash=sha256:965f5259b566725405b05e7cf774052044b1ed30119b5d586b2703aafe8719ac \ + --hash=sha256:b60533f3f5d530e971d6737ca6d58681ee434818fab630c83a734bb10c083ce8 # via -r requirements.in zipp==3.10.0 \ --hash=sha256:4fcb6f278987a6605757302a6e40e896257570d11c51628968ccb2a47e80c6c1 \ @@ -494,7 +497,7 @@ zipp==3.10.0 \ # via importlib-metadata # The following packages are considered to be unsafe in a requirements file: -setuptools==65.5.0 \ - --hash=sha256:512e5536220e38146176efb833d4a62aa726b7bbff82cfbc8ba9eaa3996e0b17 \ - --hash=sha256:f62ea9da9ed6289bfe868cd6845968a2c854d1427f8548d52cae02a42b4f0356 +setuptools==65.5.1 \ + --hash=sha256:d0b9a8433464d5800cbe05094acf5c6d52a91bfac9b52bcfc4d41382be5d5d31 \ + --hash=sha256:e197a19aa8ec9722928f2206f8de752def0e4c9fc6953527360d1c36d94ddb2f # via -r requirements.in diff --git a/noxfile.py b/noxfile.py index 29d02000..d8440c02 100644 --- a/noxfile.py +++ b/noxfile.py @@ -273,7 +273,7 @@ def cover(session): session.run("coverage", "erase") -@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.session(python="3.9") def docs(session): """Build the docs for this library.""" @@ -299,7 +299,7 @@ def docs(session): ) -@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.session(python="3.9") def docfx(session): """Build the docfx yaml files for this library.""" From 3d26563eb19471ef024408a9d15ef05784beae2f Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 24 Nov 2022 21:52:14 +0000 Subject: [PATCH 221/254] chore(python): drop flake8-import-order in samples noxfile [autoapprove] (#405) Source-Link: https://togithub.com/googleapis/synthtool/commit/6ed3a831cb9ff69ef8a504c353e098ec0192ad93 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:3abfa0f1886adaf0b83f07cb117b24a639ea1cb9cffe56d43280b977033563eb --- .github/.OwlBot.lock.yaml | 2 +- samples/snippets/api/noxfile.py | 26 +++---------------- samples/snippets/classify_text/noxfile.py | 26 +++---------------- samples/snippets/cloud-client/v1/noxfile.py | 26 +++---------------- .../snippets/generated-samples/v1/noxfile.py | 26 +++---------------- samples/snippets/sentiment/noxfile.py | 26 +++---------------- 6 files changed, 16 insertions(+), 116 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 3f1ccc08..bb21147e 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:e6cbd61f1838d9ff6a31436dfc13717f372a7482a82fc1863ca954ec47bff8c8 + digest: sha256:3abfa0f1886adaf0b83f07cb117b24a639ea1cb9cffe56d43280b977033563eb diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py index c1715136..05770846 100644 --- a/samples/snippets/api/noxfile.py +++ b/samples/snippets/api/noxfile.py @@ -18,7 +18,7 @@ import os from pathlib import Path import sys -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, Optional import nox @@ -108,22 +108,6 @@ def get_pytest_env_vars() -> Dict[str, str]: # -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - # Linting with flake8. # # We ignore the following rules: @@ -138,7 +122,6 @@ def _determine_local_import_names(start_dir: str) -> List[str]: "--show-source", "--builtin=gettext", "--max-complexity=20", - "--import-order-style=google", "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", "--max-line-length=88", @@ -148,14 +131,11 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") + session.install("flake8") else: - session.install("flake8", "flake8-import-order", "flake8-annotations") + session.install("flake8", "flake8-annotations") - local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), ".", ] session.run("flake8", *args) diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py index c1715136..05770846 100644 --- a/samples/snippets/classify_text/noxfile.py +++ b/samples/snippets/classify_text/noxfile.py @@ -18,7 +18,7 @@ import os from pathlib import Path import sys -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, Optional import nox @@ -108,22 +108,6 @@ def get_pytest_env_vars() -> Dict[str, str]: # -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - # Linting with flake8. # # We ignore the following rules: @@ -138,7 +122,6 @@ def _determine_local_import_names(start_dir: str) -> List[str]: "--show-source", "--builtin=gettext", "--max-complexity=20", - "--import-order-style=google", "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", "--max-line-length=88", @@ -148,14 +131,11 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") + session.install("flake8") else: - session.install("flake8", "flake8-import-order", "flake8-annotations") + session.install("flake8", "flake8-annotations") - local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), ".", ] session.run("flake8", *args) diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py index c1715136..05770846 100644 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ b/samples/snippets/cloud-client/v1/noxfile.py @@ -18,7 +18,7 @@ import os from pathlib import Path import sys -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, Optional import nox @@ -108,22 +108,6 @@ def get_pytest_env_vars() -> Dict[str, str]: # -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - # Linting with flake8. # # We ignore the following rules: @@ -138,7 +122,6 @@ def _determine_local_import_names(start_dir: str) -> List[str]: "--show-source", "--builtin=gettext", "--max-complexity=20", - "--import-order-style=google", "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", "--max-line-length=88", @@ -148,14 +131,11 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") + session.install("flake8") else: - session.install("flake8", "flake8-import-order", "flake8-annotations") + session.install("flake8", "flake8-annotations") - local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), ".", ] session.run("flake8", *args) diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py index c1715136..05770846 100644 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ b/samples/snippets/generated-samples/v1/noxfile.py @@ -18,7 +18,7 @@ import os from pathlib import Path import sys -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, Optional import nox @@ -108,22 +108,6 @@ def get_pytest_env_vars() -> Dict[str, str]: # -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - # Linting with flake8. # # We ignore the following rules: @@ -138,7 +122,6 @@ def _determine_local_import_names(start_dir: str) -> List[str]: "--show-source", "--builtin=gettext", "--max-complexity=20", - "--import-order-style=google", "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", "--max-line-length=88", @@ -148,14 +131,11 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") + session.install("flake8") else: - session.install("flake8", "flake8-import-order", "flake8-annotations") + session.install("flake8", "flake8-annotations") - local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), ".", ] session.run("flake8", *args) diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py index c1715136..05770846 100644 --- a/samples/snippets/sentiment/noxfile.py +++ b/samples/snippets/sentiment/noxfile.py @@ -18,7 +18,7 @@ import os from pathlib import Path import sys -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, Optional import nox @@ -108,22 +108,6 @@ def get_pytest_env_vars() -> Dict[str, str]: # -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - # Linting with flake8. # # We ignore the following rules: @@ -138,7 +122,6 @@ def _determine_local_import_names(start_dir: str) -> List[str]: "--show-source", "--builtin=gettext", "--max-complexity=20", - "--import-order-style=google", "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", "--max-line-length=88", @@ -148,14 +131,11 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") + session.install("flake8") else: - session.install("flake8", "flake8-import-order", "flake8-annotations") + session.install("flake8", "flake8-annotations") - local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), ".", ] session.run("flake8", *args) From b0d17733c910fe176aa6880607847dd530105c69 Mon Sep 17 00:00:00 2001 From: Mend Renovate <bot@renovateapp.com> Date: Sun, 27 Nov 2022 00:35:53 +0100 Subject: [PATCH 222/254] chore(deps): update dependency google-auth to v2.14.1 (#401) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore(deps): update dependency google-auth to v2.14.1 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 8cef7de4..74faaa62 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ google-api-python-client==2.65.0 -google-auth==2.14.0 +google-auth==2.14.1 google-auth-httplib2==0.1.0 From bff4a65b6a3bb28bf205cdc2fcf5ad914665c453 Mon Sep 17 00:00:00 2001 From: wizeng23 <william.f.zeng@gmail.com> Date: Sat, 26 Nov 2022 15:42:55 -0800 Subject: [PATCH 223/254] docs: specify client library version requirement in samples/v1/language_classify_text.py (#388) * docs: specify client library version requirement * clarify comment Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/v1/language_classify_text.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/v1/language_classify_text.py b/samples/v1/language_classify_text.py index fe2b5671..d1efb35e 100644 --- a/samples/v1/language_classify_text.py +++ b/samples/v1/language_classify_text.py @@ -25,7 +25,7 @@ # usage: python3 samples/v1/language_classify_text.py [--text_content "That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows."] # [START language_classify_text] -from google.cloud import language_v1 +from google.cloud import language_v1 # Requires `google-cloud-language>=2.6.0` def sample_classify_text(text_content): """ From cb1b186684e2b552126dfca38603229c62b69a98 Mon Sep 17 00:00:00 2001 From: Mend Renovate <bot@renovateapp.com> Date: Sun, 27 Nov 2022 00:50:20 +0100 Subject: [PATCH 224/254] chore(deps): update all dependencies (#406) Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- samples/snippets/api/requirements.txt | 2 +- samples/snippets/classify_text/requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt index 74faaa62..69c6359f 100644 --- a/samples/snippets/api/requirements.txt +++ b/samples/snippets/api/requirements.txt @@ -1,3 +1,3 @@ -google-api-python-client==2.65.0 +google-api-python-client==2.66.0 google-auth==2.14.1 google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt index f53284c6..30a832ca 100644 --- a/samples/snippets/classify_text/requirements.txt +++ b/samples/snippets/classify_text/requirements.txt @@ -1,3 +1,3 @@ google-cloud-language==2.6.1 -numpy==1.23.4; python_version > '3.7' +numpy==1.23.5; python_version > '3.7' numpy===1.21.4; python_version == '3.7' From 3ff2900b0d4c00d408dc9743d80bb034677be978 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 26 Nov 2022 19:24:19 -0500 Subject: [PATCH 225/254] chore: Update gapic-generator-python to v1.6.1 (#392) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: update to gapic-generator-python 1.5.0 feat: add support for `google.cloud.<api>.__version__` PiperOrigin-RevId: 484665853 Source-Link: https://github.com/googleapis/googleapis/commit/8eb249a19db926c2fbc4ecf1dc09c0e521a88b22 Source-Link: https://github.com/googleapis/googleapis-gen/commit/c8aa327b5f478865fc3fd91e3c2768e54e26ad44 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzhhYTMyN2I1ZjQ3ODg2NWZjM2ZkOTFlM2MyNzY4ZTU0ZTI2YWQ0NCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * update version in gapic_version.py * add .release-please-manifest.json with correct version * add owlbot.py to exclude generated gapic_version.py * set manifest to true in .github/release-please.yml * add release-please-config.json * fix spacing * revert * typo * chore: Update to gapic-generator-python 1.6.0 feat(python): Add typing to proto.Message based class attributes feat(python): Snippetgen handling of repeated enum field PiperOrigin-RevId: 487326846 Source-Link: https://github.com/googleapis/googleapis/commit/da380c77bb87ba0f752baf07605dd1db30e1f7e1 Source-Link: https://github.com/googleapis/googleapis-gen/commit/61ef5762ee6731a0cbbfea22fd0eecee51ab1c8e Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjFlZjU3NjJlZTY3MzFhMGNiYmZlYTIyZmQwZWVjZWU1MWFiMWM4ZSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * feat: new APIs added to reflect updates to the filestore service - Add ENTERPRISE Tier - Add snapshot APIs: RevertInstance, ListSnapshots, CreateSnapshot, DeleteSnapshot, UpdateSnapshot - Add multi-share APIs: ListShares, GetShare, CreateShare, DeleteShare, UpdateShare - Add ConnectMode to NetworkConfig (for Private Service Access support) - New status codes (SUSPENDED/SUSPENDING, REVERTING/RESUMING) - Add SuspensionReason (for KMS related suspension) - Add new fields to Instance information: max_capacity_gb, capacity_step_size_gb, max_share_count, capacity_gb, multi_share_enabled PiperOrigin-RevId: 487492758 Source-Link: https://github.com/googleapis/googleapis/commit/5be5981f50322cf0c7388595e0f31ac5d0693469 Source-Link: https://github.com/googleapis/googleapis-gen/commit/ab0e217f560cc2c1afc11441c2eab6b6950efd2b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYWIwZTIxN2Y1NjBjYzJjMWFmYzExNDQxYzJlYWI2YjY5NTBlZmQyYiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * update path to snippet metadata json * chore: Update gapic-generator-python to v1.6.1 PiperOrigin-RevId: 488036204 Source-Link: https://github.com/googleapis/googleapis/commit/08f275f5c1c0d99056e1cb68376323414459ee19 Source-Link: https://github.com/googleapis/googleapis-gen/commit/555c0945e60649e38739ae64bc45719cdf72178f Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTU1YzA5NDVlNjA2NDllMzg3MzlhZTY0YmM0NTcxOWNkZjcyMTc4ZiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * configure release-please to use manifest * drop flake8-import-order Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/release-please.yml | 1 + docs/language_v1/types.rst | 1 - docs/language_v1beta2/types.rst | 1 - google/cloud/language/__init__.py | 4 + google/cloud/language_v1/__init__.py | 4 + .../services/language_service/async_client.py | 78 ++++---- .../services/language_service/client.py | 72 ++++--- .../language_service/transports/base.py | 2 +- .../language_service/transports/grpc.py | 20 +- .../transports/grpc_asyncio.py | 16 +- .../language_v1/types/language_service.py | 182 ++++++++--------- google/cloud/language_v1beta2/__init__.py | 4 + .../services/language_service/async_client.py | 78 ++++---- .../services/language_service/client.py | 72 ++++--- .../language_service/transports/base.py | 2 +- .../language_service/transports/grpc.py | 20 +- .../transports/grpc_asyncio.py | 16 +- .../types/language_service.py | 186 +++++++++--------- owlbot.py | 56 ++++++ release-please-config.json | 49 +++-- setup.py | 47 +++-- testing/constraints-3.10.txt | 6 + testing/constraints-3.11.txt | 6 + testing/constraints-3.7.txt | 2 +- testing/constraints-3.8.txt | 8 +- testing/constraints-3.9.txt | 8 +- 26 files changed, 541 insertions(+), 400 deletions(-) create mode 100644 owlbot.py diff --git a/.github/release-please.yml b/.github/release-please.yml index 29601ad4..fe749ff6 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,5 +1,6 @@ releaseType: python handleGHRelease: true +manifest: true # NOTE: this section is generated by synthtool.languages.python # See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py branches: diff --git a/docs/language_v1/types.rst b/docs/language_v1/types.rst index a8633727..5dd3769e 100644 --- a/docs/language_v1/types.rst +++ b/docs/language_v1/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Language v1 API .. automodule:: google.cloud.language_v1.types :members: - :undoc-members: :show-inheritance: diff --git a/docs/language_v1beta2/types.rst b/docs/language_v1beta2/types.rst index 6c5a9493..2e834e61 100644 --- a/docs/language_v1beta2/types.rst +++ b/docs/language_v1beta2/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Language v1beta2 API .. automodule:: google.cloud.language_v1beta2.types :members: - :undoc-members: :show-inheritance: diff --git a/google/cloud/language/__init__.py b/google/cloud/language/__init__.py index 74c4351e..3e7674b2 100644 --- a/google/cloud/language/__init__.py +++ b/google/cloud/language/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.language import gapic_version as package_version + +__version__ = package_version.__version__ + from google.cloud.language_v1.services.language_service.async_client import ( LanguageServiceAsyncClient, diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py index acafe86d..3c9bd856 100644 --- a/google/cloud/language_v1/__init__.py +++ b/google/cloud/language_v1/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.language import gapic_version as package_version + +__version__ = package_version.__version__ + from .services.language_service import LanguageServiceAsyncClient, LanguageServiceClient from .types.language_service import ( diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 6a7f7172..9793a2dd 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -16,7 +16,17 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 @@ -158,9 +168,9 @@ def transport(self) -> LanguageServiceTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, LanguageServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the language service client. @@ -204,12 +214,12 @@ def __init__( async def analyze_sentiment( self, - request: Union[language_service.AnalyzeSentimentRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -244,7 +254,7 @@ async def sample_analyze_sentiment(): print(response) Args: - request (Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]): + request (Optional[Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]]): The request object. The sentiment analysis request message. document (:class:`google.cloud.language_v1.types.Document`): @@ -321,12 +331,12 @@ async def sample_analyze_sentiment(): async def analyze_entities( self, - request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -364,7 +374,7 @@ async def sample_analyze_entities(): print(response) Args: - request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): + request (Optional[Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]]): The request object. The entity analysis request message. document (:class:`google.cloud.language_v1.types.Document`): Required. Input document. @@ -438,12 +448,14 @@ async def sample_analyze_entities(): async def analyze_entity_sentiment( self, - request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, + request: Optional[ + Union[language_service.AnalyzeEntitySentimentRequest, dict] + ] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -481,7 +493,7 @@ async def sample_analyze_entity_sentiment(): print(response) Args: - request (Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]): + request (Optional[Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]]): The request object. The entity-level sentiment analysis request message. document (:class:`google.cloud.language_v1.types.Document`): @@ -558,12 +570,12 @@ async def sample_analyze_entity_sentiment(): async def analyze_syntax( self, - request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -600,7 +612,7 @@ async def sample_analyze_syntax(): print(response) Args: - request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): + request (Optional[Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]]): The request object. The syntax analysis request message. document (:class:`google.cloud.language_v1.types.Document`): Required. Input document. @@ -674,11 +686,11 @@ async def sample_analyze_syntax(): async def classify_text( self, - request: Union[language_service.ClassifyTextRequest, dict] = None, + request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, *, - document: language_service.Document = None, + document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -713,7 +725,7 @@ async def sample_classify_text(): print(response) Args: - request (Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]): + request (Optional[Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]]): The request object. The document classification request message. document (:class:`google.cloud.language_v1.types.Document`): @@ -781,13 +793,13 @@ async def sample_classify_text(): async def annotate_text( self, - request: Union[language_service.AnnotateTextRequest, dict] = None, + request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, *, - document: language_service.Document = None, - features: language_service.AnnotateTextRequest.Features = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + features: Optional[language_service.AnnotateTextRequest.Features] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all the features @@ -824,7 +836,7 @@ async def sample_annotate_text(): print(response) Args: - request (Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]): + request (Optional[Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]]): The request object. The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 9b67ea6a..05873cce 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -16,7 +16,18 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -57,7 +68,7 @@ class LanguageServiceClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[LanguageServiceTransport]: """Returns an appropriate transport class. @@ -312,8 +323,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, LanguageServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, LanguageServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the language service client. @@ -327,7 +338,7 @@ def __init__( transport (Union[str, LanguageServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -357,6 +368,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -409,12 +421,12 @@ def __init__( def analyze_sentiment( self, - request: Union[language_service.AnalyzeSentimentRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -516,12 +528,12 @@ def sample_analyze_sentiment(): def analyze_entities( self, - request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -623,12 +635,14 @@ def sample_analyze_entities(): def analyze_entity_sentiment( self, - request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, + request: Optional[ + Union[language_service.AnalyzeEntitySentimentRequest, dict] + ] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -733,12 +747,12 @@ def sample_analyze_entity_sentiment(): def analyze_syntax( self, - request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -839,11 +853,11 @@ def sample_analyze_syntax(): def classify_text( self, - request: Union[language_service.ClassifyTextRequest, dict] = None, + request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, *, - document: language_service.Document = None, + document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -936,13 +950,13 @@ def sample_classify_text(): def annotate_text( self, - request: Union[language_service.AnnotateTextRequest, dict] = None, + request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, *, - document: language_service.Document = None, - features: language_service.AnnotateTextRequest.Features = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + features: Optional[language_service.AnnotateTextRequest.Features] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all the features diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index 1ae661d7..f3b088b0 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -51,7 +51,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index 9349716b..f46b19fd 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -47,14 +47,14 @@ def __init__( self, *, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -181,8 +181,8 @@ def __init__( def create_channel( cls, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index e674a409..dd19f8f1 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -49,7 +49,7 @@ class LanguageServiceGrpcAsyncIOTransport(LanguageServiceTransport): def create_channel( cls, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -92,15 +92,15 @@ def __init__( self, *, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 431fa9f1..5e6fb4cb 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore __protobuf__ = proto.module( @@ -104,22 +106,22 @@ class Type(proto.Enum): PLAIN_TEXT = 1 HTML = 2 - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=1, enum=Type, ) - content = proto.Field( + content: str = proto.Field( proto.STRING, number=2, oneof="source", ) - gcs_content_uri = proto.Field( + gcs_content_uri: str = proto.Field( proto.STRING, number=3, oneof="source", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=4, ) @@ -138,12 +140,12 @@ class Sentence(proto.Message): the sentence. """ - text = proto.Field( + text: "TextSpan" = proto.Field( proto.MESSAGE, number=1, message="TextSpan", ) - sentiment = proto.Field( + sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=2, message="Sentiment", @@ -160,7 +162,7 @@ class Entity(proto.Message): The representative name for the entity. type_ (google.cloud.language_v1.types.Entity.Type): The entity type. - metadata (Mapping[str, str]): + metadata (MutableMapping[str, str]): Metadata associated with the entity. For most entity types, the metadata is a Wikipedia URL @@ -175,7 +177,7 @@ class Entity(proto.Message): the importance or centrality of that entity to the entire document text. Scores closer to 0 are less salient, while scores closer to 1.0 are highly salient. - mentions (Sequence[google.cloud.language_v1.types.EntityMention]): + mentions (MutableSequence[google.cloud.language_v1.types.EntityMention]): The mentions of this entity in the input document. The API currently supports proper noun mentions. @@ -207,30 +209,30 @@ class Type(proto.Enum): NUMBER = 12 PRICE = 13 - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=2, enum=Type, ) - metadata = proto.MapField( + metadata: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=3, ) - salience = proto.Field( + salience: float = proto.Field( proto.FLOAT, number=4, ) - mentions = proto.RepeatedField( + mentions: MutableSequence["EntityMention"] = proto.RepeatedField( proto.MESSAGE, number=5, message="EntityMention", ) - sentiment = proto.Field( + sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=6, message="Sentiment", @@ -252,22 +254,22 @@ class Token(proto.Message): of the token. """ - text = proto.Field( + text: "TextSpan" = proto.Field( proto.MESSAGE, number=1, message="TextSpan", ) - part_of_speech = proto.Field( + part_of_speech: "PartOfSpeech" = proto.Field( proto.MESSAGE, number=2, message="PartOfSpeech", ) - dependency_edge = proto.Field( + dependency_edge: "DependencyEdge" = proto.Field( proto.MESSAGE, number=3, message="DependencyEdge", ) - lemma = proto.Field( + lemma: str = proto.Field( proto.STRING, number=4, ) @@ -287,11 +289,11 @@ class Sentiment(proto.Message): sentiment) and 1.0 (positive sentiment). """ - magnitude = proto.Field( + magnitude: float = proto.Field( proto.FLOAT, number=2, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=3, ) @@ -466,62 +468,62 @@ class Voice(proto.Enum): CAUSATIVE = 2 PASSIVE = 3 - tag = proto.Field( + tag: Tag = proto.Field( proto.ENUM, number=1, enum=Tag, ) - aspect = proto.Field( + aspect: Aspect = proto.Field( proto.ENUM, number=2, enum=Aspect, ) - case = proto.Field( + case: Case = proto.Field( proto.ENUM, number=3, enum=Case, ) - form = proto.Field( + form: Form = proto.Field( proto.ENUM, number=4, enum=Form, ) - gender = proto.Field( + gender: Gender = proto.Field( proto.ENUM, number=5, enum=Gender, ) - mood = proto.Field( + mood: Mood = proto.Field( proto.ENUM, number=6, enum=Mood, ) - number = proto.Field( + number: Number = proto.Field( proto.ENUM, number=7, enum=Number, ) - person = proto.Field( + person: Person = proto.Field( proto.ENUM, number=8, enum=Person, ) - proper = proto.Field( + proper: Proper = proto.Field( proto.ENUM, number=9, enum=Proper, ) - reciprocity = proto.Field( + reciprocity: Reciprocity = proto.Field( proto.ENUM, number=10, enum=Reciprocity, ) - tense = proto.Field( + tense: Tense = proto.Field( proto.ENUM, number=11, enum=Tense, ) - voice = proto.Field( + voice: Voice = proto.Field( proto.ENUM, number=12, enum=Voice, @@ -631,11 +633,11 @@ class Label(proto.Enum): MES = 81 NCOMP = 82 - head_token_index = proto.Field( + head_token_index: int = proto.Field( proto.INT32, number=1, ) - label = proto.Field( + label: Label = proto.Field( proto.ENUM, number=2, enum=Label, @@ -665,17 +667,17 @@ class Type(proto.Enum): PROPER = 1 COMMON = 2 - text = proto.Field( + text: "TextSpan" = proto.Field( proto.MESSAGE, number=1, message="TextSpan", ) - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=2, enum=Type, ) - sentiment = proto.Field( + sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=3, message="Sentiment", @@ -695,11 +697,11 @@ class TextSpan(proto.Message): specified in the API request. """ - content = proto.Field( + content: str = proto.Field( proto.STRING, number=1, ) - begin_offset = proto.Field( + begin_offset: int = proto.Field( proto.INT32, number=2, ) @@ -719,11 +721,11 @@ class ClassificationCategory(proto.Message): that this category represents the given text. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) @@ -773,19 +775,19 @@ class ContentCategoriesVersion(proto.Enum): V1 = 1 V2 = 2 - content_categories_version = proto.Field( + content_categories_version: "ClassificationModelOptions.V2Model.ContentCategoriesVersion" = proto.Field( proto.ENUM, number=1, enum="ClassificationModelOptions.V2Model.ContentCategoriesVersion", ) - v1_model = proto.Field( + v1_model: V1Model = proto.Field( proto.MESSAGE, number=1, oneof="model_type", message=V1Model, ) - v2_model = proto.Field( + v2_model: V2Model = proto.Field( proto.MESSAGE, number=2, oneof="model_type", @@ -804,12 +806,12 @@ class AnalyzeSentimentRequest(proto.Message): calculate sentence offsets. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -828,21 +830,21 @@ class AnalyzeSentimentResponse(proto.Message): automatically-detected language. See [Document.language][google.cloud.language.v1.Document.language] field for more details. - sentences (Sequence[google.cloud.language_v1.types.Sentence]): + sentences (MutableSequence[google.cloud.language_v1.types.Sentence]): The sentiment for all the sentences in the document. """ - document_sentiment = proto.Field( + document_sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=1, message="Sentiment", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=2, ) - sentences = proto.RepeatedField( + sentences: MutableSequence["Sentence"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Sentence", @@ -860,12 +862,12 @@ class AnalyzeEntitySentimentRequest(proto.Message): calculate offsets. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -876,7 +878,7 @@ class AnalyzeEntitySentimentResponse(proto.Message): r"""The entity-level sentiment analysis response message. Attributes: - entities (Sequence[google.cloud.language_v1.types.Entity]): + entities (MutableSequence[google.cloud.language_v1.types.Entity]): The recognized entities in the input document with associated sentiments. language (str): @@ -887,12 +889,12 @@ class AnalyzeEntitySentimentResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField( + entities: MutableSequence["Entity"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Entity", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=2, ) @@ -909,12 +911,12 @@ class AnalyzeEntitiesRequest(proto.Message): calculate offsets. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -925,7 +927,7 @@ class AnalyzeEntitiesResponse(proto.Message): r"""The entity analysis response message. Attributes: - entities (Sequence[google.cloud.language_v1.types.Entity]): + entities (MutableSequence[google.cloud.language_v1.types.Entity]): The recognized entities in the input document. language (str): @@ -936,12 +938,12 @@ class AnalyzeEntitiesResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField( + entities: MutableSequence["Entity"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Entity", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=2, ) @@ -958,12 +960,12 @@ class AnalyzeSyntaxRequest(proto.Message): calculate offsets. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -974,9 +976,9 @@ class AnalyzeSyntaxResponse(proto.Message): r"""The syntax analysis response message. Attributes: - sentences (Sequence[google.cloud.language_v1.types.Sentence]): + sentences (MutableSequence[google.cloud.language_v1.types.Sentence]): Sentences in the input document. - tokens (Sequence[google.cloud.language_v1.types.Token]): + tokens (MutableSequence[google.cloud.language_v1.types.Token]): Tokens, along with their syntactic information, in the input document. language (str): @@ -987,17 +989,17 @@ class AnalyzeSyntaxResponse(proto.Message): field for more details. """ - sentences = proto.RepeatedField( + sentences: MutableSequence["Sentence"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Sentence", ) - tokens = proto.RepeatedField( + tokens: MutableSequence["Token"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Token", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=3, ) @@ -1014,12 +1016,12 @@ class ClassifyTextRequest(proto.Message): Defaults to v1 options if not specified. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - classification_model_options = proto.Field( + classification_model_options: "ClassificationModelOptions" = proto.Field( proto.MESSAGE, number=3, message="ClassificationModelOptions", @@ -1030,11 +1032,11 @@ class ClassifyTextResponse(proto.Message): r"""The document classification response message. Attributes: - categories (Sequence[google.cloud.language_v1.types.ClassificationCategory]): + categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): Categories representing the input document. """ - categories = proto.RepeatedField( + categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ClassificationCategory", @@ -1079,43 +1081,43 @@ class Features(proto.Message): set to true. """ - extract_syntax = proto.Field( + extract_syntax: bool = proto.Field( proto.BOOL, number=1, ) - extract_entities = proto.Field( + extract_entities: bool = proto.Field( proto.BOOL, number=2, ) - extract_document_sentiment = proto.Field( + extract_document_sentiment: bool = proto.Field( proto.BOOL, number=3, ) - extract_entity_sentiment = proto.Field( + extract_entity_sentiment: bool = proto.Field( proto.BOOL, number=4, ) - classify_text = proto.Field( + classify_text: bool = proto.Field( proto.BOOL, number=6, ) - classification_model_options = proto.Field( + classification_model_options: "ClassificationModelOptions" = proto.Field( proto.MESSAGE, number=10, message="ClassificationModelOptions", ) - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - features = proto.Field( + features: Features = proto.Field( proto.MESSAGE, number=2, message=Features, ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=3, enum="EncodingType", @@ -1126,15 +1128,15 @@ class AnnotateTextResponse(proto.Message): r"""The text annotations response message. Attributes: - sentences (Sequence[google.cloud.language_v1.types.Sentence]): + sentences (MutableSequence[google.cloud.language_v1.types.Sentence]): Sentences in the input document. Populated if the user enables [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1.AnnotateTextRequest.Features.extract_syntax]. - tokens (Sequence[google.cloud.language_v1.types.Token]): + tokens (MutableSequence[google.cloud.language_v1.types.Token]): Tokens, along with their syntactic information, in the input document. Populated if the user enables [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1.AnnotateTextRequest.Features.extract_syntax]. - entities (Sequence[google.cloud.language_v1.types.Entity]): + entities (MutableSequence[google.cloud.language_v1.types.Entity]): Entities, along with their semantic information, in the input document. Populated if the user enables [AnnotateTextRequest.Features.extract_entities][google.cloud.language.v1.AnnotateTextRequest.Features.extract_entities]. @@ -1148,35 +1150,35 @@ class AnnotateTextResponse(proto.Message): automatically-detected language. See [Document.language][google.cloud.language.v1.Document.language] field for more details. - categories (Sequence[google.cloud.language_v1.types.ClassificationCategory]): + categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): Categories identified in the input document. """ - sentences = proto.RepeatedField( + sentences: MutableSequence["Sentence"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Sentence", ) - tokens = proto.RepeatedField( + tokens: MutableSequence["Token"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Token", ) - entities = proto.RepeatedField( + entities: MutableSequence["Entity"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Entity", ) - document_sentiment = proto.Field( + document_sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=4, message="Sentiment", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=5, ) - categories = proto.RepeatedField( + categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( proto.MESSAGE, number=6, message="ClassificationCategory", diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py index acafe86d..3c9bd856 100644 --- a/google/cloud/language_v1beta2/__init__.py +++ b/google/cloud/language_v1beta2/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.language import gapic_version as package_version + +__version__ = package_version.__version__ + from .services.language_service import LanguageServiceAsyncClient, LanguageServiceClient from .types.language_service import ( diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index db5180ac..e3f79792 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -16,7 +16,17 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 @@ -158,9 +168,9 @@ def transport(self) -> LanguageServiceTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, LanguageServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the language service client. @@ -204,12 +214,12 @@ def __init__( async def analyze_sentiment( self, - request: Union[language_service.AnalyzeSentimentRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -244,7 +254,7 @@ async def sample_analyze_sentiment(): print(response) Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]): + request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]]): The request object. The sentiment analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): @@ -322,12 +332,12 @@ async def sample_analyze_sentiment(): async def analyze_entities( self, - request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -365,7 +375,7 @@ async def sample_analyze_entities(): print(response) Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]): + request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]]): The request object. The entity analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): Required. Input document. @@ -439,12 +449,14 @@ async def sample_analyze_entities(): async def analyze_entity_sentiment( self, - request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, + request: Optional[ + Union[language_service.AnalyzeEntitySentimentRequest, dict] + ] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -482,7 +494,7 @@ async def sample_analyze_entity_sentiment(): print(response) Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]): + request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]]): The request object. The entity-level sentiment analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): @@ -559,12 +571,12 @@ async def sample_analyze_entity_sentiment(): async def analyze_syntax( self, - request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -601,7 +613,7 @@ async def sample_analyze_syntax(): print(response) Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]): + request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]]): The request object. The syntax analysis request message. document (:class:`google.cloud.language_v1beta2.types.Document`): Required. Input document. @@ -675,11 +687,11 @@ async def sample_analyze_syntax(): async def classify_text( self, - request: Union[language_service.ClassifyTextRequest, dict] = None, + request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, *, - document: language_service.Document = None, + document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -714,7 +726,7 @@ async def sample_classify_text(): print(response) Args: - request (Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]): + request (Optional[Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]]): The request object. The document classification request message. document (:class:`google.cloud.language_v1beta2.types.Document`): @@ -782,13 +794,13 @@ async def sample_classify_text(): async def annotate_text( self, - request: Union[language_service.AnnotateTextRequest, dict] = None, + request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, *, - document: language_service.Document = None, - features: language_service.AnnotateTextRequest.Features = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + features: Optional[language_service.AnnotateTextRequest.Features] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all syntax, @@ -825,7 +837,7 @@ async def sample_annotate_text(): print(response) Args: - request (Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]): + request (Optional[Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]]): The request object. The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 10e8b064..07405a6f 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -16,7 +16,18 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -57,7 +68,7 @@ class LanguageServiceClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[LanguageServiceTransport]: """Returns an appropriate transport class. @@ -312,8 +323,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, LanguageServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, LanguageServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the language service client. @@ -327,7 +338,7 @@ def __init__( transport (Union[str, LanguageServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -357,6 +368,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -409,12 +421,12 @@ def __init__( def analyze_sentiment( self, - request: Union[language_service.AnalyzeSentimentRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -517,12 +529,12 @@ def sample_analyze_sentiment(): def analyze_entities( self, - request: Union[language_service.AnalyzeEntitiesRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -624,12 +636,14 @@ def sample_analyze_entities(): def analyze_entity_sentiment( self, - request: Union[language_service.AnalyzeEntitySentimentRequest, dict] = None, + request: Optional[ + Union[language_service.AnalyzeEntitySentimentRequest, dict] + ] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -734,12 +748,12 @@ def sample_analyze_entity_sentiment(): def analyze_syntax( self, - request: Union[language_service.AnalyzeSyntaxRequest, dict] = None, + request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -840,11 +854,11 @@ def sample_analyze_syntax(): def classify_text( self, - request: Union[language_service.ClassifyTextRequest, dict] = None, + request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, *, - document: language_service.Document = None, + document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -937,13 +951,13 @@ def sample_classify_text(): def annotate_text( self, - request: Union[language_service.AnnotateTextRequest, dict] = None, + request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, *, - document: language_service.Document = None, - features: language_service.AnnotateTextRequest.Features = None, - encoding_type: language_service.EncodingType = None, + document: Optional[language_service.Document] = None, + features: Optional[language_service.AnnotateTextRequest.Features] = None, + encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all syntax, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index cea5272d..3877d81b 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -51,7 +51,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index 3d1de3e0..f89362eb 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -47,14 +47,14 @@ def __init__( self, *, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -181,8 +181,8 @@ def __init__( def create_channel( cls, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index 72f07a70..dc0f8f26 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -49,7 +49,7 @@ class LanguageServiceGrpcAsyncIOTransport(LanguageServiceTransport): def create_channel( cls, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -92,15 +92,15 @@ def __init__( self, *, host: str = "language.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 63f87cc8..7e98b632 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore __protobuf__ = proto.module( @@ -120,30 +122,30 @@ class BoilerplateHandling(proto.Enum): SKIP_BOILERPLATE = 1 KEEP_BOILERPLATE = 2 - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=1, enum=Type, ) - content = proto.Field( + content: str = proto.Field( proto.STRING, number=2, oneof="source", ) - gcs_content_uri = proto.Field( + gcs_content_uri: str = proto.Field( proto.STRING, number=3, oneof="source", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=4, ) - reference_web_uri = proto.Field( + reference_web_uri: str = proto.Field( proto.STRING, number=5, ) - boilerplate_handling = proto.Field( + boilerplate_handling: BoilerplateHandling = proto.Field( proto.ENUM, number=6, enum=BoilerplateHandling, @@ -163,12 +165,12 @@ class Sentence(proto.Message): the sentence. """ - text = proto.Field( + text: "TextSpan" = proto.Field( proto.MESSAGE, number=1, message="TextSpan", ) - sentiment = proto.Field( + sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=2, message="Sentiment", @@ -185,7 +187,7 @@ class Entity(proto.Message): The representative name for the entity. type_ (google.cloud.language_v1beta2.types.Entity.Type): The entity type. - metadata (Mapping[str, str]): + metadata (MutableMapping[str, str]): Metadata associated with the entity. For most entity types, the metadata is a Wikipedia URL @@ -200,7 +202,7 @@ class Entity(proto.Message): the importance or centrality of that entity to the entire document text. Scores closer to 0 are less salient, while scores closer to 1.0 are highly salient. - mentions (Sequence[google.cloud.language_v1beta2.types.EntityMention]): + mentions (MutableSequence[google.cloud.language_v1beta2.types.EntityMention]): The mentions of this entity in the input document. The API currently supports proper noun mentions. @@ -232,30 +234,30 @@ class Type(proto.Enum): NUMBER = 12 PRICE = 13 - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=2, enum=Type, ) - metadata = proto.MapField( + metadata: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=3, ) - salience = proto.Field( + salience: float = proto.Field( proto.FLOAT, number=4, ) - mentions = proto.RepeatedField( + mentions: MutableSequence["EntityMention"] = proto.RepeatedField( proto.MESSAGE, number=5, message="EntityMention", ) - sentiment = proto.Field( + sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=6, message="Sentiment", @@ -277,22 +279,22 @@ class Token(proto.Message): of the token. """ - text = proto.Field( + text: "TextSpan" = proto.Field( proto.MESSAGE, number=1, message="TextSpan", ) - part_of_speech = proto.Field( + part_of_speech: "PartOfSpeech" = proto.Field( proto.MESSAGE, number=2, message="PartOfSpeech", ) - dependency_edge = proto.Field( + dependency_edge: "DependencyEdge" = proto.Field( proto.MESSAGE, number=3, message="DependencyEdge", ) - lemma = proto.Field( + lemma: str = proto.Field( proto.STRING, number=4, ) @@ -313,11 +315,11 @@ class Sentiment(proto.Message): sentiment) and 1.0 (positive sentiment). """ - magnitude = proto.Field( + magnitude: float = proto.Field( proto.FLOAT, number=2, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=3, ) @@ -490,62 +492,62 @@ class Voice(proto.Enum): CAUSATIVE = 2 PASSIVE = 3 - tag = proto.Field( + tag: Tag = proto.Field( proto.ENUM, number=1, enum=Tag, ) - aspect = proto.Field( + aspect: Aspect = proto.Field( proto.ENUM, number=2, enum=Aspect, ) - case = proto.Field( + case: Case = proto.Field( proto.ENUM, number=3, enum=Case, ) - form = proto.Field( + form: Form = proto.Field( proto.ENUM, number=4, enum=Form, ) - gender = proto.Field( + gender: Gender = proto.Field( proto.ENUM, number=5, enum=Gender, ) - mood = proto.Field( + mood: Mood = proto.Field( proto.ENUM, number=6, enum=Mood, ) - number = proto.Field( + number: Number = proto.Field( proto.ENUM, number=7, enum=Number, ) - person = proto.Field( + person: Person = proto.Field( proto.ENUM, number=8, enum=Person, ) - proper = proto.Field( + proper: Proper = proto.Field( proto.ENUM, number=9, enum=Proper, ) - reciprocity = proto.Field( + reciprocity: Reciprocity = proto.Field( proto.ENUM, number=10, enum=Reciprocity, ) - tense = proto.Field( + tense: Tense = proto.Field( proto.ENUM, number=11, enum=Tense, ) - voice = proto.Field( + voice: Voice = proto.Field( proto.ENUM, number=12, enum=Voice, @@ -653,11 +655,11 @@ class Label(proto.Enum): MES = 81 NCOMP = 82 - head_token_index = proto.Field( + head_token_index: int = proto.Field( proto.INT32, number=1, ) - label = proto.Field( + label: Label = proto.Field( proto.ENUM, number=2, enum=Label, @@ -687,17 +689,17 @@ class Type(proto.Enum): PROPER = 1 COMMON = 2 - text = proto.Field( + text: "TextSpan" = proto.Field( proto.MESSAGE, number=1, message="TextSpan", ) - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=2, enum=Type, ) - sentiment = proto.Field( + sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=3, message="Sentiment", @@ -717,11 +719,11 @@ class TextSpan(proto.Message): specified in the API request. """ - content = proto.Field( + content: str = proto.Field( proto.STRING, number=1, ) - begin_offset = proto.Field( + begin_offset: int = proto.Field( proto.INT32, number=2, ) @@ -741,11 +743,11 @@ class ClassificationCategory(proto.Message): that this category represents the given text. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) @@ -795,19 +797,19 @@ class ContentCategoriesVersion(proto.Enum): V1 = 1 V2 = 2 - content_categories_version = proto.Field( + content_categories_version: "ClassificationModelOptions.V2Model.ContentCategoriesVersion" = proto.Field( proto.ENUM, number=1, enum="ClassificationModelOptions.V2Model.ContentCategoriesVersion", ) - v1_model = proto.Field( + v1_model: V1Model = proto.Field( proto.MESSAGE, number=1, oneof="model_type", message=V1Model, ) - v2_model = proto.Field( + v2_model: V2Model = proto.Field( proto.MESSAGE, number=2, oneof="model_type", @@ -827,12 +829,12 @@ class AnalyzeSentimentRequest(proto.Message): sentiment. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -851,21 +853,21 @@ class AnalyzeSentimentResponse(proto.Message): automatically-detected language. See [Document.language][google.cloud.language.v1beta2.Document.language] field for more details. - sentences (Sequence[google.cloud.language_v1beta2.types.Sentence]): + sentences (MutableSequence[google.cloud.language_v1beta2.types.Sentence]): The sentiment for all the sentences in the document. """ - document_sentiment = proto.Field( + document_sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=1, message="Sentiment", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=2, ) - sentences = proto.RepeatedField( + sentences: MutableSequence["Sentence"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Sentence", @@ -883,12 +885,12 @@ class AnalyzeEntitySentimentRequest(proto.Message): calculate offsets. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -899,7 +901,7 @@ class AnalyzeEntitySentimentResponse(proto.Message): r"""The entity-level sentiment analysis response message. Attributes: - entities (Sequence[google.cloud.language_v1beta2.types.Entity]): + entities (MutableSequence[google.cloud.language_v1beta2.types.Entity]): The recognized entities in the input document with associated sentiments. language (str): @@ -910,12 +912,12 @@ class AnalyzeEntitySentimentResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField( + entities: MutableSequence["Entity"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Entity", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=2, ) @@ -932,12 +934,12 @@ class AnalyzeEntitiesRequest(proto.Message): calculate offsets. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -948,7 +950,7 @@ class AnalyzeEntitiesResponse(proto.Message): r"""The entity analysis response message. Attributes: - entities (Sequence[google.cloud.language_v1beta2.types.Entity]): + entities (MutableSequence[google.cloud.language_v1beta2.types.Entity]): The recognized entities in the input document. language (str): @@ -959,12 +961,12 @@ class AnalyzeEntitiesResponse(proto.Message): field for more details. """ - entities = proto.RepeatedField( + entities: MutableSequence["Entity"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Entity", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=2, ) @@ -981,12 +983,12 @@ class AnalyzeSyntaxRequest(proto.Message): calculate offsets. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=2, enum="EncodingType", @@ -997,9 +999,9 @@ class AnalyzeSyntaxResponse(proto.Message): r"""The syntax analysis response message. Attributes: - sentences (Sequence[google.cloud.language_v1beta2.types.Sentence]): + sentences (MutableSequence[google.cloud.language_v1beta2.types.Sentence]): Sentences in the input document. - tokens (Sequence[google.cloud.language_v1beta2.types.Token]): + tokens (MutableSequence[google.cloud.language_v1beta2.types.Token]): Tokens, along with their syntactic information, in the input document. language (str): @@ -1010,17 +1012,17 @@ class AnalyzeSyntaxResponse(proto.Message): field for more details. """ - sentences = proto.RepeatedField( + sentences: MutableSequence["Sentence"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Sentence", ) - tokens = proto.RepeatedField( + tokens: MutableSequence["Token"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Token", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=3, ) @@ -1037,12 +1039,12 @@ class ClassifyTextRequest(proto.Message): Defaults to v1 options if not specified. """ - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - classification_model_options = proto.Field( + classification_model_options: "ClassificationModelOptions" = proto.Field( proto.MESSAGE, number=3, message="ClassificationModelOptions", @@ -1053,11 +1055,11 @@ class ClassifyTextResponse(proto.Message): r"""The document classification response message. Attributes: - categories (Sequence[google.cloud.language_v1beta2.types.ClassificationCategory]): + categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): Categories representing the input document. """ - categories = proto.RepeatedField( + categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ClassificationCategory", @@ -1105,43 +1107,43 @@ class Features(proto.Message): set to true. """ - extract_syntax = proto.Field( + extract_syntax: bool = proto.Field( proto.BOOL, number=1, ) - extract_entities = proto.Field( + extract_entities: bool = proto.Field( proto.BOOL, number=2, ) - extract_document_sentiment = proto.Field( + extract_document_sentiment: bool = proto.Field( proto.BOOL, number=3, ) - extract_entity_sentiment = proto.Field( + extract_entity_sentiment: bool = proto.Field( proto.BOOL, number=4, ) - classify_text = proto.Field( + classify_text: bool = proto.Field( proto.BOOL, number=6, ) - classification_model_options = proto.Field( + classification_model_options: "ClassificationModelOptions" = proto.Field( proto.MESSAGE, number=10, message="ClassificationModelOptions", ) - document = proto.Field( + document: "Document" = proto.Field( proto.MESSAGE, number=1, message="Document", ) - features = proto.Field( + features: Features = proto.Field( proto.MESSAGE, number=2, message=Features, ) - encoding_type = proto.Field( + encoding_type: "EncodingType" = proto.Field( proto.ENUM, number=3, enum="EncodingType", @@ -1152,15 +1154,15 @@ class AnnotateTextResponse(proto.Message): r"""The text annotations response message. Attributes: - sentences (Sequence[google.cloud.language_v1beta2.types.Sentence]): + sentences (MutableSequence[google.cloud.language_v1beta2.types.Sentence]): Sentences in the input document. Populated if the user enables [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_syntax]. - tokens (Sequence[google.cloud.language_v1beta2.types.Token]): + tokens (MutableSequence[google.cloud.language_v1beta2.types.Token]): Tokens, along with their syntactic information, in the input document. Populated if the user enables [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_syntax]. - entities (Sequence[google.cloud.language_v1beta2.types.Entity]): + entities (MutableSequence[google.cloud.language_v1beta2.types.Entity]): Entities, along with their semantic information, in the input document. Populated if the user enables [AnnotateTextRequest.Features.extract_entities][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_entities]. @@ -1174,35 +1176,35 @@ class AnnotateTextResponse(proto.Message): automatically-detected language. See [Document.language][google.cloud.language.v1beta2.Document.language] field for more details. - categories (Sequence[google.cloud.language_v1beta2.types.ClassificationCategory]): + categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): Categories identified in the input document. """ - sentences = proto.RepeatedField( + sentences: MutableSequence["Sentence"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Sentence", ) - tokens = proto.RepeatedField( + tokens: MutableSequence["Token"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Token", ) - entities = proto.RepeatedField( + entities: MutableSequence["Entity"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Entity", ) - document_sentiment = proto.Field( + document_sentiment: "Sentiment" = proto.Field( proto.MESSAGE, number=4, message="Sentiment", ) - language = proto.Field( + language: str = proto.Field( proto.STRING, number=5, ) - categories = proto.RepeatedField( + categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( proto.MESSAGE, number=6, message="ClassificationCategory", diff --git a/owlbot.py b/owlbot.py new file mode 100644 index 00000000..ce738f01 --- /dev/null +++ b/owlbot.py @@ -0,0 +1,56 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from pathlib import Path +import shutil + +import synthtool as s +import synthtool.gcp as gcp +from synthtool.languages import python + +# ---------------------------------------------------------------------------- +# Copy the generated client from the owl-bot staging directory +# ---------------------------------------------------------------------------- + +clean_up_generated_samples = True + +# Load the default version defined in .repo-metadata.json. +default_version = json.load(open(".repo-metadata.json", "rt")).get( + "default_version" +) + +for library in s.get_staging_dirs(default_version): + if clean_up_generated_samples: + shutil.rmtree("samples/generated_samples", ignore_errors=True) + clean_up_generated_samples = False + s.move([library], excludes=["**/gapic_version.py"]) +s.remove_staging_dirs() + +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- + +templated_files = gcp.CommonTemplates().py_library( + cov_level=100, + microgenerator=True, + versions=gcp.common.detect_versions(path="./google", default_first=True), +) +s.move(templated_files, excludes=[".coveragerc", ".github/release-please.yml"]) + +python.py_samples(skip_readmes=True) + +# run format session for all directories which have a noxfile +for noxfile in Path(".").glob("**/noxfile.py"): + s.shell.run(["nox", "-s", "format"], cwd=noxfile.parent, hide_output=False) diff --git a/release-please-config.json b/release-please-config.json index 8a8c9d0e..cd455f82 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,29 +1,28 @@ { - "$schema": -"https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", - "packages": { - ".": { - "release-type": "python", - "extra-files": [ - "google/cloud/language/gapic_version.py", - { - "type": "json", - "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1.json", - "jsonpath": "$.clientLibrary.version" - }, - { - "type": "json", - "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json", - "jsonpath": "$.clientLibrary.version" - } - ] - } - }, - "release-type": "python", - "plugins": [ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "python", + "extra-files": [ + "google/cloud/language/gapic_version.py", + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1.json", + "jsonpath": "$.clientLibrary.version" + }, { - "type": "sentence-case" + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json", + "jsonpath": "$.clientLibrary.version" } - ], - "initial-version": "0.1.0" + ] + } + }, + "release-type": "python", + "plugins": [ + { + "type": "sentence-case" + } + ], + "initial-version": "0.1.0" } diff --git a/setup.py b/setup.py index ae220ed8..d24aa357 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ -# Copyright 2018 Google LLC +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,29 +12,35 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - +# import io import os -import setuptools +import setuptools # type: ignore -# Package metadata. +package_root = os.path.abspath(os.path.dirname(__file__)) name = "google-cloud-language" -description = "Google Cloud Natural Language API client library" -version = "2.6.1" -# Should be one of: -# 'Development Status :: 3 - Alpha' -# 'Development Status :: 4 - Beta' -# 'Development Status :: 5 - Production/Stable' -release_status = "Development Status :: 5 - Production/Stable" + + +description = "Google Cloud Language API client library" + +version = {} +with open(os.path.join(package_root, "google/cloud/language/gapic_version.py")) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + dependencies = [ - "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "google-api-core[grpc] >= 1.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.22.0, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] - -# Setup boilerplate below this line. +url = "https://github.com/googleapis/python-language" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -41,20 +48,16 @@ with io.open(readme_filename, encoding="utf-8") as readme_file: readme = readme_file.read() -# Only include packages under the 'google' namespace. Do not include tests, -# benchmarks, etc. packages = [ package for package in setuptools.PEP420PackageFinder.find() if package.startswith("google") ] -# Determine which namespaces are needed. namespaces = ["google"] if "google.cloud" in packages: namespaces.append("google.cloud") - setuptools.setup( name=name, version=version, @@ -63,7 +66,7 @@ author="Google LLC", author_email="googleapis-packages@google.com", license="Apache 2.0", - url="https://github.com/googleapis/python-language", + url=url, classifiers=[ release_status, "Intended Audience :: Developers", @@ -79,13 +82,9 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, + python_requires=">=3.7", namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=3.7", - scripts=[ - "scripts/fixup_language_v1_keywords.py", - "scripts/fixup_language_v1beta2_keywords.py", - ], include_package_data=True, zip_safe=False, ) diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt index e69de29b..ed7f9aed 100644 --- a/testing/constraints-3.10.txt +++ b/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt index e69de29b..ed7f9aed 100644 --- a/testing/constraints-3.11.txt +++ b/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 4005dc5b..6f3158cc 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -4,6 +4,6 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.32.0 +google-api-core==1.33.2 proto-plus==1.22.0 protobuf==3.19.5 diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index da93009b..ed7f9aed 100644 --- a/testing/constraints-3.8.txt +++ b/testing/constraints-3.8.txt @@ -1,2 +1,6 @@ -# This constraints file is left inentionally empty -# so the latest version of dependencies is installed \ No newline at end of file +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index da93009b..ed7f9aed 100644 --- a/testing/constraints-3.9.txt +++ b/testing/constraints-3.9.txt @@ -1,2 +1,6 @@ -# This constraints file is left inentionally empty -# so the latest version of dependencies is installed \ No newline at end of file +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf From 017c68a8a68d2de8b2fa985aac6db682a14bf5f8 Mon Sep 17 00:00:00 2001 From: Maciej Strzelczyk <strzelczyk@google.com> Date: Wed, 7 Dec 2022 17:06:38 +0100 Subject: [PATCH 226/254] cleanup(samples): Removing migrated code samples (#408) --- samples/AUTHORING_GUIDE.md | 1 - samples/CONTRIBUTING.md | 1 - samples/README.txt | 3 + samples/snippets/README.md | 15 - samples/snippets/api/README.rst | 98 ------ samples/snippets/api/README.rst.in | 22 -- samples/snippets/api/analyze.py | 92 ------ samples/snippets/api/analyze_test.py | 278 ----------------- samples/snippets/api/noxfile.py | 292 ------------------ samples/snippets/api/requirements-test.txt | 1 - samples/snippets/api/requirements.txt | 3 - samples/snippets/classify_text/README.rst | 130 -------- samples/snippets/classify_text/README.rst.in | 28 -- .../classify_text/classify_text_tutorial.py | 256 --------------- .../classify_text_tutorial_test.py | 89 ------ samples/snippets/classify_text/noxfile.py | 292 ------------------ .../classify_text/requirements-test.txt | 1 - .../snippets/classify_text/requirements.txt | 3 - .../classify_text/resources/query_text1.txt | 1 - .../classify_text/resources/query_text2.txt | 1 - .../classify_text/resources/query_text3.txt | 1 - .../classify_text/resources/texts/android.txt | 1 - .../resources/texts/cat_in_the_hat.txt | 1 - .../resources/texts/cloud_computing.txt | 1 - .../classify_text/resources/texts/eclipse.txt | 1 - .../resources/texts/eclipse_of_the_sun.txt | 1 - .../classify_text/resources/texts/email.txt | 1 - .../classify_text/resources/texts/gcp.txt | 1 - .../classify_text/resources/texts/gmail.txt | 1 - .../classify_text/resources/texts/google.txt | 1 - .../resources/texts/harry_potter.txt | 1 - .../classify_text/resources/texts/matilda.txt | 1 - .../resources/texts/mobile_phone.txt | 1 - .../classify_text/resources/texts/mr_fox.txt | 1 - .../resources/texts/wireless.txt | 1 - samples/snippets/cloud-client/.DS_Store | Bin 6148 -> 0 bytes samples/snippets/cloud-client/v1/README.rst | 99 ------ .../snippets/cloud-client/v1/README.rst.in | 30 -- samples/snippets/cloud-client/v1/noxfile.py | 292 ------------------ .../snippets/cloud-client/v1/quickstart.py | 47 --- .../cloud-client/v1/quickstart_test.py | 22 -- .../cloud-client/v1/requirements-test.txt | 1 - .../snippets/cloud-client/v1/requirements.txt | 1 - .../cloud-client/v1/resources/text.txt | 1 - .../snippets/cloud-client/v1/set_endpoint.py | 42 --- .../cloud-client/v1/set_endpoint_test.py | 22 -- .../v1/language_sentiment_text.py | 58 ---- .../v1/language_sentiment_text_test.py | 28 -- .../snippets/generated-samples/v1/noxfile.py | 292 ------------------ .../v1/requirements-test.txt | 1 - .../generated-samples/v1/requirements.txt | 1 - samples/snippets/sentiment/README.md | 53 ---- samples/snippets/sentiment/noxfile.py | 292 ------------------ .../snippets/sentiment/requirements-test.txt | 1 - samples/snippets/sentiment/requirements.txt | 1 - .../snippets/sentiment/resources/mixed.txt | 20 -- samples/snippets/sentiment/resources/neg.txt | 4 - .../snippets/sentiment/resources/neutral.txt | 3 - samples/snippets/sentiment/resources/pos.txt | 11 - .../snippets/sentiment/sentiment_analysis.py | 79 ----- .../sentiment/sentiment_analysis_test.py | 50 --- samples/v1/language_classify_gcs.py | 83 ----- samples/v1/language_classify_text.py | 90 ------ samples/v1/language_entities_gcs.py | 103 ------ samples/v1/language_entities_text.py | 103 ------ samples/v1/language_entity_sentiment_gcs.py | 107 ------- samples/v1/language_entity_sentiment_text.py | 104 ------- samples/v1/language_sentiment_gcs.py | 93 ------ samples/v1/language_sentiment_text.py | 88 ------ samples/v1/language_syntax_gcs.py | 115 ------- samples/v1/language_syntax_text.py | 110 ------- samples/v1/test/analyzing_entities.test.yaml | 101 ------ .../test/analyzing_entity_sentiment.test.yaml | 63 ---- samples/v1/test/analyzing_sentiment.test.yaml | 74 ----- samples/v1/test/analyzing_syntax.test.yaml | 72 ----- samples/v1/test/classifying_content.test.yaml | 51 --- samples/v1/test/samples.manifest.yaml | 38 --- 77 files changed, 3 insertions(+), 4465 deletions(-) delete mode 100644 samples/AUTHORING_GUIDE.md delete mode 100644 samples/CONTRIBUTING.md create mode 100644 samples/README.txt delete mode 100644 samples/snippets/README.md delete mode 100644 samples/snippets/api/README.rst delete mode 100644 samples/snippets/api/README.rst.in delete mode 100644 samples/snippets/api/analyze.py delete mode 100644 samples/snippets/api/analyze_test.py delete mode 100644 samples/snippets/api/noxfile.py delete mode 100644 samples/snippets/api/requirements-test.txt delete mode 100644 samples/snippets/api/requirements.txt delete mode 100644 samples/snippets/classify_text/README.rst delete mode 100644 samples/snippets/classify_text/README.rst.in delete mode 100644 samples/snippets/classify_text/classify_text_tutorial.py delete mode 100644 samples/snippets/classify_text/classify_text_tutorial_test.py delete mode 100644 samples/snippets/classify_text/noxfile.py delete mode 100644 samples/snippets/classify_text/requirements-test.txt delete mode 100644 samples/snippets/classify_text/requirements.txt delete mode 100644 samples/snippets/classify_text/resources/query_text1.txt delete mode 100644 samples/snippets/classify_text/resources/query_text2.txt delete mode 100644 samples/snippets/classify_text/resources/query_text3.txt delete mode 100644 samples/snippets/classify_text/resources/texts/android.txt delete mode 100644 samples/snippets/classify_text/resources/texts/cat_in_the_hat.txt delete mode 100644 samples/snippets/classify_text/resources/texts/cloud_computing.txt delete mode 100644 samples/snippets/classify_text/resources/texts/eclipse.txt delete mode 100644 samples/snippets/classify_text/resources/texts/eclipse_of_the_sun.txt delete mode 100644 samples/snippets/classify_text/resources/texts/email.txt delete mode 100644 samples/snippets/classify_text/resources/texts/gcp.txt delete mode 100644 samples/snippets/classify_text/resources/texts/gmail.txt delete mode 100644 samples/snippets/classify_text/resources/texts/google.txt delete mode 100644 samples/snippets/classify_text/resources/texts/harry_potter.txt delete mode 100644 samples/snippets/classify_text/resources/texts/matilda.txt delete mode 100644 samples/snippets/classify_text/resources/texts/mobile_phone.txt delete mode 100644 samples/snippets/classify_text/resources/texts/mr_fox.txt delete mode 100644 samples/snippets/classify_text/resources/texts/wireless.txt delete mode 100644 samples/snippets/cloud-client/.DS_Store delete mode 100644 samples/snippets/cloud-client/v1/README.rst delete mode 100644 samples/snippets/cloud-client/v1/README.rst.in delete mode 100644 samples/snippets/cloud-client/v1/noxfile.py delete mode 100644 samples/snippets/cloud-client/v1/quickstart.py delete mode 100644 samples/snippets/cloud-client/v1/quickstart_test.py delete mode 100644 samples/snippets/cloud-client/v1/requirements-test.txt delete mode 100644 samples/snippets/cloud-client/v1/requirements.txt delete mode 100644 samples/snippets/cloud-client/v1/resources/text.txt delete mode 100644 samples/snippets/cloud-client/v1/set_endpoint.py delete mode 100644 samples/snippets/cloud-client/v1/set_endpoint_test.py delete mode 100644 samples/snippets/generated-samples/v1/language_sentiment_text.py delete mode 100644 samples/snippets/generated-samples/v1/language_sentiment_text_test.py delete mode 100644 samples/snippets/generated-samples/v1/noxfile.py delete mode 100644 samples/snippets/generated-samples/v1/requirements-test.txt delete mode 100644 samples/snippets/generated-samples/v1/requirements.txt delete mode 100644 samples/snippets/sentiment/README.md delete mode 100644 samples/snippets/sentiment/noxfile.py delete mode 100644 samples/snippets/sentiment/requirements-test.txt delete mode 100644 samples/snippets/sentiment/requirements.txt delete mode 100644 samples/snippets/sentiment/resources/mixed.txt delete mode 100644 samples/snippets/sentiment/resources/neg.txt delete mode 100644 samples/snippets/sentiment/resources/neutral.txt delete mode 100644 samples/snippets/sentiment/resources/pos.txt delete mode 100644 samples/snippets/sentiment/sentiment_analysis.py delete mode 100644 samples/snippets/sentiment/sentiment_analysis_test.py delete mode 100644 samples/v1/language_classify_gcs.py delete mode 100644 samples/v1/language_classify_text.py delete mode 100644 samples/v1/language_entities_gcs.py delete mode 100644 samples/v1/language_entities_text.py delete mode 100644 samples/v1/language_entity_sentiment_gcs.py delete mode 100644 samples/v1/language_entity_sentiment_text.py delete mode 100644 samples/v1/language_sentiment_gcs.py delete mode 100644 samples/v1/language_sentiment_text.py delete mode 100644 samples/v1/language_syntax_gcs.py delete mode 100644 samples/v1/language_syntax_text.py delete mode 100644 samples/v1/test/analyzing_entities.test.yaml delete mode 100644 samples/v1/test/analyzing_entity_sentiment.test.yaml delete mode 100644 samples/v1/test/analyzing_sentiment.test.yaml delete mode 100644 samples/v1/test/analyzing_syntax.test.yaml delete mode 100644 samples/v1/test/classifying_content.test.yaml delete mode 100644 samples/v1/test/samples.manifest.yaml diff --git a/samples/AUTHORING_GUIDE.md b/samples/AUTHORING_GUIDE.md deleted file mode 100644 index 55c97b32..00000000 --- a/samples/AUTHORING_GUIDE.md +++ /dev/null @@ -1 +0,0 @@ -See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/samples/CONTRIBUTING.md b/samples/CONTRIBUTING.md deleted file mode 100644 index 34c882b6..00000000 --- a/samples/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/samples/README.txt b/samples/README.txt new file mode 100644 index 00000000..c87a54f3 --- /dev/null +++ b/samples/README.txt @@ -0,0 +1,3 @@ +# Handwritten code samples migrated + +The handwritten samples were moved to: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/language diff --git a/samples/snippets/README.md b/samples/snippets/README.md deleted file mode 100644 index 5689d7c2..00000000 --- a/samples/snippets/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Google Cloud Natural Language API examples - -[![Open in Cloud Shell][shell_img]][shell_link] - -[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png -[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/README.md - -This directory contains Python examples that use the -[Google Cloud Natural Language API](https://cloud.google.com/natural-language/). - -- [api](api) has a simple command line tool that shows off the API's features. - -- [sentiment](sentiment) contains the [Sentiment Analysis - Tutorial](https://cloud.google.com/natural-language/docs/sentiment-tutorial) -code as used within the documentation. diff --git a/samples/snippets/api/README.rst b/samples/snippets/api/README.rst deleted file mode 100644 index 0d9d9451..00000000 --- a/samples/snippets/api/README.rst +++ /dev/null @@ -1,98 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Natural Language API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/api/README.rst - - -This directory contains samples for Google Cloud Natural Language API. The `Google Cloud Natural Language API`_ provides natural language understanding technologies to developers, including sentiment analysis, entity recognition, and syntax analysis. This API is part of the larger Cloud Machine Learning API. - - - - -.. _Google Cloud Natural Language API: https://cloud.google.com/natural-language/docs/ - - - - - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Samples -------------------------------------------------------------------------------- - -Analyze syntax -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/api/analyze.py,language/api/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python analyze.py - - usage: analyze.py [-h] {entities,sentiment,syntax} text - - Analyzes text using the Google Cloud Natural Language API. - - positional arguments: - {entities,sentiment,syntax} - text - - optional arguments: - -h, --help show this help message and exit - - - - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/api/README.rst.in b/samples/snippets/api/README.rst.in deleted file mode 100644 index f3195edf..00000000 --- a/samples/snippets/api/README.rst.in +++ /dev/null @@ -1,22 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Natural Language API - short_name: Cloud Natural Language API - url: https://cloud.google.com/natural-language/docs/ - description: > - The `Google Cloud Natural Language API`_ provides natural language - understanding technologies to developers, including sentiment analysis, - entity recognition, and syntax analysis. This API is part of the larger - Cloud Machine Learning API. - -setup: -- auth -- install_deps - -samples: -- name: Analyze syntax - file: analyze.py - show_help: true - -folder: language/api \ No newline at end of file diff --git a/samples/snippets/api/analyze.py b/samples/snippets/api/analyze.py deleted file mode 100644 index be865226..00000000 --- a/samples/snippets/api/analyze.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2016 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. - -"""Analyzes text using the Google Cloud Natural Language API.""" - -import argparse -import json -import sys - -import googleapiclient.discovery - - -def get_native_encoding_type(): - """Returns the encoding type that matches Python's native strings.""" - if sys.maxunicode == 65535: - return "UTF16" - else: - return "UTF32" - - -def analyze_entities(text, encoding="UTF32"): - body = { - "document": {"type": "PLAIN_TEXT", "content": text}, - "encoding_type": encoding, - } - - service = googleapiclient.discovery.build("language", "v1") - - request = service.documents().analyzeEntities(body=body) - response = request.execute() - - return response - - -def analyze_sentiment(text, encoding="UTF32"): - body = { - "document": {"type": "PLAIN_TEXT", "content": text}, - "encoding_type": encoding, - } - - service = googleapiclient.discovery.build("language", "v1") - - request = service.documents().analyzeSentiment(body=body) - response = request.execute() - - return response - - -def analyze_syntax(text, encoding="UTF32"): - body = { - "document": {"type": "PLAIN_TEXT", "content": text}, - "encoding_type": encoding, - } - - service = googleapiclient.discovery.build("language", "v1") - - request = service.documents().analyzeSyntax(body=body) - response = request.execute() - - return response - - -if __name__ == "__main__": - parser = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - parser.add_argument("command", choices=["entities", "sentiment", "syntax"]) - parser.add_argument("text") - - args = parser.parse_args() - - if args.command == "entities": - result = analyze_entities(args.text, get_native_encoding_type()) - elif args.command == "sentiment": - result = analyze_sentiment(args.text, get_native_encoding_type()) - elif args.command == "syntax": - result = analyze_syntax(args.text, get_native_encoding_type()) - - print(json.dumps(result, indent=2)) diff --git a/samples/snippets/api/analyze_test.py b/samples/snippets/api/analyze_test.py deleted file mode 100644 index da5f0ab0..00000000 --- a/samples/snippets/api/analyze_test.py +++ /dev/null @@ -1,278 +0,0 @@ -# Copyright 2016, 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. - -import textwrap - -import analyze - - -def test_analyze_entities(): - result = analyze.analyze_entities( - "Tom Sawyer is a book written by a guy known as Mark Twain." - ) - - assert result["language"] == "en" - entities = result["entities"] - assert len(entities) - subject = entities[0] - assert subject["type"] == "PERSON" - assert subject["name"].startswith("Tom") - - -def test_analyze_sentiment(capsys): - result = analyze.analyze_sentiment("your face is really ugly and i hate it.") - - sentiment = result["documentSentiment"] - assert sentiment["score"] < 0 - assert sentiment["magnitude"] < 1 - - result = analyze.analyze_sentiment( - "cheerio, mate - I greatly admire the pallor of your visage, and your angle of repose leaves little room for improvement." - ) - - sentiment = result["documentSentiment"] - assert sentiment["score"] > 0 - assert sentiment["magnitude"] < 1 - - -def test_analyze_syntax(capsys): - result = analyze.analyze_syntax( - textwrap.dedent( - """\ - Keep away from people who try to belittle your ambitions. Small people - always do that, but the really great make you feel that you, too, can - become great. - - Mark Twain""" - ) - ) - - assert len(result["tokens"]) - first_token = result["tokens"][0] - assert first_token["text"]["content"] == "Keep" - assert first_token["partOfSpeech"]["tag"] == "VERB" - assert len(result["sentences"]) > 1 - assert result["language"] == "en" - - -def test_analyze_syntax_utf8(): - """Demonstrate the interpretation of the offsets when encoding=utf8. - - UTF8 is a variable-length encoding, where each character is at least 8 - bits. The offsets we get should be the index of the first byte of the - character. - """ - test_string = "a \u00e3 \u0201 \U0001f636 b" - byte_array = test_string.encode("utf8") - result = analyze.analyze_syntax(test_string, encoding="UTF8") - tokens = result["tokens"] - - assert tokens[0]["text"]["content"] == "a" - offset = tokens[0]["text"].get("beginOffset", 0) - assert ( - byte_array[offset : offset + 1].decode("utf8") == tokens[0]["text"]["content"] - ) - - assert tokens[1]["text"]["content"] == "\u00e3" - offset = tokens[1]["text"].get("beginOffset", 0) - assert ( - byte_array[offset : offset + 2].decode("utf8") == tokens[1]["text"]["content"] - ) - - assert tokens[2]["text"]["content"] == "\u0201" - offset = tokens[2]["text"].get("beginOffset", 0) - assert ( - byte_array[offset : offset + 2].decode("utf8") == tokens[2]["text"]["content"] - ) - - assert tokens[3]["text"]["content"] == "\U0001f636" - offset = tokens[3]["text"].get("beginOffset", 0) - assert ( - byte_array[offset : offset + 4].decode("utf8") == tokens[3]["text"]["content"] - ) - - # This demonstrates that the offset takes into account the variable-length - # characters before the target token. - assert tokens[4]["text"]["content"] == "b" - offset = tokens[4]["text"].get("beginOffset", 0) - # 'b' is only one byte long - assert ( - byte_array[offset : offset + 1].decode("utf8") == tokens[4]["text"]["content"] - ) - - -def test_analyze_syntax_utf16(): - """Demonstrate the interpretation of the offsets when encoding=utf16. - - UTF16 is a variable-length encoding, where each character is at least 16 - bits. The returned offsets will be the index of the first 2-byte character - of the token. - """ - test_string = "a \u00e3 \u0201 \U0001f636 b" - byte_array = test_string.encode("utf16") - # Remove the byte order marker, which the offsets don't account for - byte_array = byte_array[2:] - result = analyze.analyze_syntax(test_string, encoding="UTF16") - tokens = result["tokens"] - - assert tokens[0]["text"]["content"] == "a" - # The offset is an offset into an array where each entry is 16 bits. Since - # we have an 8-bit array, the offsets should be doubled to index into our - # array. - offset = 2 * tokens[0]["text"].get("beginOffset", 0) - assert ( - byte_array[offset : offset + 2].decode("utf16") == tokens[0]["text"]["content"] - ) - - assert tokens[1]["text"]["content"] == "\u00e3" - offset = 2 * tokens[1]["text"].get("beginOffset", 0) - # A UTF16 character with a low codepoint is 16 bits (2 bytes) long, so - # slice out 2 bytes starting from the offset. Then interpret the bytes as - # utf16 for comparison. - assert ( - byte_array[offset : offset + 2].decode("utf16") == tokens[1]["text"]["content"] - ) - - assert tokens[2]["text"]["content"] == "\u0201" - offset = 2 * tokens[2]["text"].get("beginOffset", 0) - # A UTF16 character with a low codepoint is 16 bits (2 bytes) long, so - # slice out 2 bytes starting from the offset. Then interpret the bytes as - # utf16 for comparison. - assert ( - byte_array[offset : offset + 2].decode("utf16") == tokens[2]["text"]["content"] - ) - - assert tokens[3]["text"]["content"] == "\U0001f636" - offset = 2 * tokens[3]["text"].get("beginOffset", 0) - # A UTF16 character with a high codepoint is 32 bits (4 bytes) long, so - # slice out 4 bytes starting from the offset. Then interpret those bytes as - # utf16 for comparison. - assert ( - byte_array[offset : offset + 4].decode("utf16") == tokens[3]["text"]["content"] - ) - - # This demonstrates that the offset takes into account the variable-length - # characters before the target token. - assert tokens[4]["text"]["content"] == "b" - offset = 2 * tokens[4]["text"].get("beginOffset", 0) - # Even though 'b' is only one byte long, utf16 still encodes it using 16 - # bits - assert ( - byte_array[offset : offset + 2].decode("utf16") == tokens[4]["text"]["content"] - ) - - -def test_annotate_text_utf32(): - """Demonstrate the interpretation of the offsets when encoding=utf32. - - UTF32 is a fixed-length encoding, where each character is exactly 32 bits. - The returned offsets will be the index of the first 4-byte character - of the token. - - Python unicode objects index by the interpreted unicode character. This - means a given unicode character only ever takes up one slot in a unicode - string. This is equivalent to indexing into a UTF32 string, where all - characters are a fixed length and thus will only ever take up one slot. - - Thus, if you're indexing into a python unicode object, you can set - encoding to UTF32 to index directly into the unicode object (as opposed to - the byte arrays, as these examples do). - - Nonetheless, this test still demonstrates indexing into the byte array, for - consistency. Note that you could just index into the origin test_string - unicode object with the raw offset returned by the api (ie without - multiplying it by 4, as it is below). - """ - test_string = "a \u00e3 \u0201 \U0001f636 b" - byte_array = test_string.encode("utf32") - # Remove the byte order marker, which the offsets don't account for - byte_array = byte_array[4:] - result = analyze.analyze_syntax(test_string, encoding="UTF32") - tokens = result["tokens"] - - assert tokens[0]["text"]["content"] == "a" - # The offset is an offset into an array where each entry is 32 bits. Since - # we have an 8-bit array, the offsets should be quadrupled to index into - # our array. - offset = 4 * tokens[0]["text"].get("beginOffset", 0) - assert ( - byte_array[offset : offset + 4].decode("utf32") == tokens[0]["text"]["content"] - ) - - assert tokens[1]["text"]["content"] == "\u00e3" - offset = 4 * tokens[1]["text"].get("beginOffset", 0) - # A UTF32 character with a low codepoint is 32 bits (4 bytes) long, so - # slice out 4 bytes starting from the offset. Then interpret the bytes as - # utf32 for comparison. - assert ( - byte_array[offset : offset + 4].decode("utf32") == tokens[1]["text"]["content"] - ) - - assert tokens[2]["text"]["content"] == "\u0201" - offset = 4 * tokens[2]["text"].get("beginOffset", 0) - # A UTF32 character with a low codepoint is 32 bits (4 bytes) long, so - # slice out 4 bytes starting from the offset. Then interpret the bytes as - # utf32 for comparison. - assert ( - byte_array[offset : offset + 4].decode("utf32") == tokens[2]["text"]["content"] - ) - - assert tokens[3]["text"]["content"] == "\U0001f636" - offset = 4 * tokens[3]["text"].get("beginOffset", 0) - # A UTF32 character with a high codepoint is 32 bits (4 bytes) long, so - # slice out 4 bytes starting from the offset. Then interpret those bytes as - # utf32 for comparison. - assert ( - byte_array[offset : offset + 4].decode("utf32") == tokens[3]["text"]["content"] - ) - - # This demonstrates that the offset takes into account the variable-length - # characters before the target token. - assert tokens[4]["text"]["content"] == "b" - offset = 4 * tokens[4]["text"].get("beginOffset", 0) - # Even though 'b' is only one byte long, utf32 still encodes it using 32 - # bits - assert ( - byte_array[offset : offset + 4].decode("utf32") == tokens[4]["text"]["content"] - ) - - -def test_annotate_text_utf32_directly_index_into_unicode(): - """Demonstrate using offsets directly, using encoding=utf32. - - See the explanation for test_annotate_text_utf32. Essentially, indexing - into a utf32 array is equivalent to indexing into a python unicode object. - """ - test_string = "a \u00e3 \u0201 \U0001f636 b" - result = analyze.analyze_syntax(test_string, encoding="UTF32") - tokens = result["tokens"] - - assert tokens[0]["text"]["content"] == "a" - offset = tokens[0]["text"].get("beginOffset", 0) - assert test_string[offset] == tokens[0]["text"]["content"] - - assert tokens[1]["text"]["content"] == "\u00e3" - offset = tokens[1]["text"].get("beginOffset", 0) - assert test_string[offset] == tokens[1]["text"]["content"] - - assert tokens[2]["text"]["content"] == "\u0201" - offset = tokens[2]["text"].get("beginOffset", 0) - assert test_string[offset] == tokens[2]["text"]["content"] - - # Temporarily disabled - # assert tokens[3]['text']['content'] == u'\U0001f636' - # offset = tokens[3]['text'].get('beginOffset', 0) - # assert test_string[offset] == tokens[3]['text']['content'] - - # assert tokens[4]['text']['content'] == u'b' - # offset = tokens[4]['text'].get('beginOffset', 0) - # assert test_string[offset] == tokens[4]['text']['content'] diff --git a/samples/snippets/api/noxfile.py b/samples/snippets/api/noxfile.py deleted file mode 100644 index 05770846..00000000 --- a/samples/snippets/api/noxfile.py +++ /dev/null @@ -1,292 +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. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, Optional - -import nox - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # 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": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8") - else: - session.install("flake8", "flake8-annotations") - - args = FLAKE8_COMMON_ARGS + [ - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( - "**/test_*.py", recursive=True - ) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - 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.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("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") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) - elif "pytest-xdist" in packages: - concurrent_args.extend(["-n", "auto"]) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/api/requirements-test.txt b/samples/snippets/api/requirements-test.txt deleted file mode 100644 index 49780e03..00000000 --- a/samples/snippets/api/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.2.0 diff --git a/samples/snippets/api/requirements.txt b/samples/snippets/api/requirements.txt deleted file mode 100644 index 69c6359f..00000000 --- a/samples/snippets/api/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -google-api-python-client==2.66.0 -google-auth==2.14.1 -google-auth-httplib2==0.1.0 diff --git a/samples/snippets/classify_text/README.rst b/samples/snippets/classify_text/README.rst deleted file mode 100644 index 757debb0..00000000 --- a/samples/snippets/classify_text/README.rst +++ /dev/null @@ -1,130 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Natural Language API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/classify_text/README.rst - - -This directory contains samples for Google Cloud Natural Language API. The `Google Cloud Natural Language API`_ provides natural language understanding technologies to developers. - -This tutorial demostrates how to use the `classify_text` method to classify content category of text files, and use the result to compare texts by their similarity to each other. See the `tutorial page`_ for details about this sample. - -.. _tutorial page: https://cloud.google.com/natural-language/docs/classify-text-tutorial - - - - -.. _Google Cloud Natural Language API: https://cloud.google.com/natural-language/docs/ - - - - - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Samples -------------------------------------------------------------------------------- - -Classify Text Tutorial -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/classify_text/classify_text_tutorial.py,language/classify_text/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python classify_text_tutorial.py - - usage: classify_text_tutorial.py [-h] - {classify,index,query,query-category} ... - - Using the classify_text method to find content categories of text files, - Then use the content category labels to compare text similarity. - - For more information, see the tutorial page at - https://cloud.google.com/natural-language/docs/classify-text-tutorial. - - positional arguments: - {classify,index,query,query-category} - classify Classify the input text into categories. - index Classify each text file in a directory and write the - results to the index_file. - query Find the indexed files that are the most similar to - the query text. - query-category Find the indexed files that are the most similar to - the query label. The list of all available labels: - https://cloud.google.com/natural- - language/docs/categories - - optional arguments: - -h, --help show this help message and exit - - - - - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/classify_text/README.rst.in b/samples/snippets/classify_text/README.rst.in deleted file mode 100644 index 14ee6dc9..00000000 --- a/samples/snippets/classify_text/README.rst.in +++ /dev/null @@ -1,28 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Natural Language API - short_name: Cloud Natural Language API - url: https://cloud.google.com/natural-language/docs/ - description: > - The `Google Cloud Natural Language API`_ provides natural language - understanding technologies to developers. - - - This tutorial demostrates how to use the `classify_text` method to classify content category of text files, and use the result to compare texts by their similarity to each other. See the `tutorial page`_ for details about this sample. - - - .. _tutorial page: https://cloud.google.com/natural-language/docs/classify-text-tutorial - -setup: -- auth -- install_deps - -samples: -- name: Classify Text Tutorial - file: classify_text_tutorial.py - show_help: true - -cloud_client_library: true - -folder: language/classify_text \ No newline at end of file diff --git a/samples/snippets/classify_text/classify_text_tutorial.py b/samples/snippets/classify_text/classify_text_tutorial.py deleted file mode 100644 index de35451d..00000000 --- a/samples/snippets/classify_text/classify_text_tutorial.py +++ /dev/null @@ -1,256 +0,0 @@ -#!/usr/bin/env python - -# 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. - -"""Using the classify_text method to find content categories of text files, -Then use the content category labels to compare text similarity. - -For more information, see the tutorial page at -https://cloud.google.com/natural-language/docs/classify-text-tutorial. -""" - -# [START language_classify_text_tutorial_imports] -import argparse -import io -import json -import os - -from google.cloud import language_v1 -import numpy -import six - -# [END language_classify_text_tutorial_imports] - - -# [START language_classify_text_tutorial_classify] -def classify(text, verbose=True): - """Classify the input text into categories.""" - - language_client = language_v1.LanguageServiceClient() - - document = language_v1.Document( - content=text, type_=language_v1.Document.Type.PLAIN_TEXT - ) - response = language_client.classify_text(request={"document": document}) - categories = response.categories - - result = {} - - for category in categories: - # Turn the categories into a dictionary of the form: - # {category.name: category.confidence}, so that they can - # be treated as a sparse vector. - result[category.name] = category.confidence - - if verbose: - print(text) - for category in categories: - print("=" * 20) - print("{:<16}: {}".format("category", category.name)) - print("{:<16}: {}".format("confidence", category.confidence)) - - return result - - -# [END language_classify_text_tutorial_classify] - - -# [START language_classify_text_tutorial_index] -def index(path, index_file): - """Classify each text file in a directory and write - the results to the index_file. - """ - - result = {} - for filename in os.listdir(path): - file_path = os.path.join(path, filename) - - if not os.path.isfile(file_path): - continue - - try: - with io.open(file_path, "r") as f: - text = f.read() - categories = classify(text, verbose=False) - - result[filename] = categories - except Exception: - print("Failed to process {}".format(file_path)) - - with io.open(index_file, "w", encoding="utf-8") as f: - f.write(json.dumps(result, ensure_ascii=False)) - - print("Texts indexed in file: {}".format(index_file)) - return result - - -# [END language_classify_text_tutorial_index] - - -def split_labels(categories): - """The category labels are of the form "/a/b/c" up to three levels, - for example "/Computers & Electronics/Software", and these labels - are used as keys in the categories dictionary, whose values are - confidence scores. - - The split_labels function splits the keys into individual levels - while duplicating the confidence score, which allows a natural - boost in how we calculate similarity when more levels are in common. - - Example: - If we have - - x = {"/a/b/c": 0.5} - y = {"/a/b": 0.5} - z = {"/a": 0.5} - - Then x and y are considered more similar than y and z. - """ - _categories = {} - for name, confidence in six.iteritems(categories): - labels = [label for label in name.split("/") if label] - for label in labels: - _categories[label] = confidence - - return _categories - - -def similarity(categories1, categories2): - """Cosine similarity of the categories treated as sparse vectors.""" - categories1 = split_labels(categories1) - categories2 = split_labels(categories2) - - norm1 = numpy.linalg.norm(list(categories1.values())) - norm2 = numpy.linalg.norm(list(categories2.values())) - - # Return the smallest possible similarity if either categories is empty. - if norm1 == 0 or norm2 == 0: - return 0.0 - - # Compute the cosine similarity. - dot = 0.0 - for label, confidence in six.iteritems(categories1): - dot += confidence * categories2.get(label, 0.0) - - return dot / (norm1 * norm2) - - -# [START language_classify_text_tutorial_query] -def query(index_file, text, n_top=3): - """Find the indexed files that are the most similar to - the query text. - """ - - with io.open(index_file, "r") as f: - index = json.load(f) - - # Get the categories of the query text. - query_categories = classify(text, verbose=False) - - similarities = [] - for filename, categories in six.iteritems(index): - similarities.append((filename, similarity(query_categories, categories))) - - similarities = sorted(similarities, key=lambda p: p[1], reverse=True) - - print("=" * 20) - print("Query: {}\n".format(text)) - for category, confidence in six.iteritems(query_categories): - print("\tCategory: {}, confidence: {}".format(category, confidence)) - print("\nMost similar {} indexed texts:".format(n_top)) - for filename, sim in similarities[:n_top]: - print("\tFilename: {}".format(filename)) - print("\tSimilarity: {}".format(sim)) - print("\n") - - return similarities - - -# [END language_classify_text_tutorial_query] - - -# [START language_classify_text_tutorial_query_category] -def query_category(index_file, category_string, n_top=3): - """Find the indexed files that are the most similar to - the query label. - - The list of all available labels: - https://cloud.google.com/natural-language/docs/categories - """ - - with io.open(index_file, "r") as f: - index = json.load(f) - - # Make the category_string into a dictionary so that it is - # of the same format as what we get by calling classify. - query_categories = {category_string: 1.0} - - similarities = [] - for filename, categories in six.iteritems(index): - similarities.append((filename, similarity(query_categories, categories))) - - similarities = sorted(similarities, key=lambda p: p[1], reverse=True) - - print("=" * 20) - print("Query: {}\n".format(category_string)) - print("\nMost similar {} indexed texts:".format(n_top)) - for filename, sim in similarities[:n_top]: - print("\tFilename: {}".format(filename)) - print("\tSimilarity: {}".format(sim)) - print("\n") - - return similarities - - -# [END language_classify_text_tutorial_query_category] - - -if __name__ == "__main__": - parser = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - subparsers = parser.add_subparsers(dest="command") - classify_parser = subparsers.add_parser("classify", help=classify.__doc__) - classify_parser.add_argument( - "text", - help="The text to be classified. " "The text needs to have at least 20 tokens.", - ) - index_parser = subparsers.add_parser("index", help=index.__doc__) - index_parser.add_argument( - "path", help="The directory that contains " "text files to be indexed." - ) - index_parser.add_argument( - "--index_file", help="Filename for the output JSON.", default="index.json" - ) - query_parser = subparsers.add_parser("query", help=query.__doc__) - query_parser.add_argument("index_file", help="Path to the index JSON file.") - query_parser.add_argument("text", help="Query text.") - query_category_parser = subparsers.add_parser( - "query-category", help=query_category.__doc__ - ) - query_category_parser.add_argument( - "index_file", help="Path to the index JSON file." - ) - query_category_parser.add_argument("category", help="Query category.") - - args = parser.parse_args() - - if args.command == "classify": - classify(args.text) - if args.command == "index": - index(args.path, args.index_file) - if args.command == "query": - query(args.index_file, args.text) - if args.command == "query-category": - query_category(args.index_file, args.category) diff --git a/samples/snippets/classify_text/classify_text_tutorial_test.py b/samples/snippets/classify_text/classify_text_tutorial_test.py deleted file mode 100644 index 5859a771..00000000 --- a/samples/snippets/classify_text/classify_text_tutorial_test.py +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright 2016, 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. - -import os - -import pytest - -import classify_text_tutorial - -OUTPUT = "index.json" -RESOURCES = os.path.join(os.path.dirname(__file__), "resources") -QUERY_TEXT = """Google Home enables users to speak voice commands to interact -with services through the Home\'s intelligent personal assistant called -Google Assistant. A large number of services, both in-house and third-party, -are integrated, allowing users to listen to music, look at videos or photos, -or receive news updates entirely by voice.""" -QUERY_CATEGORY = "/Computers & Electronics/Software" - - -@pytest.fixture(scope="session") -def index_file(tmpdir_factory): - temp_file = tmpdir_factory.mktemp("tmp").join(OUTPUT) - temp_out = temp_file.strpath - classify_text_tutorial.index(os.path.join(RESOURCES, "texts"), temp_out) - return temp_file - - -def test_classify(capsys): - with open(os.path.join(RESOURCES, "query_text1.txt"), "r") as f: - text = f.read() - classify_text_tutorial.classify(text) - out, err = capsys.readouterr() - assert "category" in out - - -def test_index(capsys, tmpdir): - temp_dir = tmpdir.mkdir("tmp") - temp_out = temp_dir.join(OUTPUT).strpath - - classify_text_tutorial.index(os.path.join(RESOURCES, "texts"), temp_out) - out, err = capsys.readouterr() - - assert OUTPUT in out - assert len(temp_dir.listdir()) == 1 - - -def test_query_text(capsys, index_file): - temp_out = index_file.strpath - - classify_text_tutorial.query(temp_out, QUERY_TEXT) - out, err = capsys.readouterr() - - assert "Filename: cloud_computing.txt" in out - - -def test_query_category(capsys, index_file): - temp_out = index_file.strpath - - classify_text_tutorial.query_category(temp_out, QUERY_CATEGORY) - out, err = capsys.readouterr() - - assert "Filename: cloud_computing.txt" in out - - -def test_split_labels(): - categories = {"/a/b/c": 1.0} - split_categories = {"a": 1.0, "b": 1.0, "c": 1.0} - assert classify_text_tutorial.split_labels(categories) == split_categories - - -def test_similarity(): - empty_categories = {} - categories1 = {"/a/b/c": 1.0, "/d/e": 1.0} - categories2 = {"/a/b": 1.0} - - assert classify_text_tutorial.similarity(empty_categories, categories1) == 0.0 - assert classify_text_tutorial.similarity(categories1, categories1) > 0.99 - assert classify_text_tutorial.similarity(categories1, categories2) > 0 - assert classify_text_tutorial.similarity(categories1, categories2) < 1 diff --git a/samples/snippets/classify_text/noxfile.py b/samples/snippets/classify_text/noxfile.py deleted file mode 100644 index 05770846..00000000 --- a/samples/snippets/classify_text/noxfile.py +++ /dev/null @@ -1,292 +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. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, Optional - -import nox - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # 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": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8") - else: - session.install("flake8", "flake8-annotations") - - args = FLAKE8_COMMON_ARGS + [ - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( - "**/test_*.py", recursive=True - ) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - 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.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("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") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) - elif "pytest-xdist" in packages: - concurrent_args.extend(["-n", "auto"]) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/classify_text/requirements-test.txt b/samples/snippets/classify_text/requirements-test.txt deleted file mode 100644 index 49780e03..00000000 --- a/samples/snippets/classify_text/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.2.0 diff --git a/samples/snippets/classify_text/requirements.txt b/samples/snippets/classify_text/requirements.txt deleted file mode 100644 index 30a832ca..00000000 --- a/samples/snippets/classify_text/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -google-cloud-language==2.6.1 -numpy==1.23.5; python_version > '3.7' -numpy===1.21.4; python_version == '3.7' diff --git a/samples/snippets/classify_text/resources/query_text1.txt b/samples/snippets/classify_text/resources/query_text1.txt deleted file mode 100644 index 30472730..00000000 --- a/samples/snippets/classify_text/resources/query_text1.txt +++ /dev/null @@ -1 +0,0 @@ -Google Home enables users to speak voice commands to interact with services through the Home's intelligent personal assistant called Google Assistant. A large number of services, both in-house and third-party, are integrated, allowing users to listen to music, look at videos or photos, or receive news updates entirely by voice. diff --git a/samples/snippets/classify_text/resources/query_text2.txt b/samples/snippets/classify_text/resources/query_text2.txt deleted file mode 100644 index eef573c6..00000000 --- a/samples/snippets/classify_text/resources/query_text2.txt +++ /dev/null @@ -1 +0,0 @@ -The Hitchhiker's Guide to the Galaxy is the first of five books in the Hitchhiker's Guide to the Galaxy comedy science fiction "trilogy" by Douglas Adams (with the sixth written by Eoin Colfer). \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/query_text3.txt b/samples/snippets/classify_text/resources/query_text3.txt deleted file mode 100644 index 1337d3c6..00000000 --- a/samples/snippets/classify_text/resources/query_text3.txt +++ /dev/null @@ -1 +0,0 @@ -Goodnight Moon is an American children's picture book written by Margaret Wise Brown and illustrated by Clement Hurd. It was published on September 3, 1947, and is a highly acclaimed example of a bedtime story. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/android.txt b/samples/snippets/classify_text/resources/texts/android.txt deleted file mode 100644 index 29dc1449..00000000 --- a/samples/snippets/classify_text/resources/texts/android.txt +++ /dev/null @@ -1 +0,0 @@ -Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets. diff --git a/samples/snippets/classify_text/resources/texts/cat_in_the_hat.txt b/samples/snippets/classify_text/resources/texts/cat_in_the_hat.txt deleted file mode 100644 index bb5a853c..00000000 --- a/samples/snippets/classify_text/resources/texts/cat_in_the_hat.txt +++ /dev/null @@ -1 +0,0 @@ -The Cat in the Hat is a children's book written and illustrated by Theodor Geisel under the pen name Dr. Seuss and first published in 1957. The story centers on a tall anthropomorphic cat, who wears a red and white-striped hat and a red bow tie. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/cloud_computing.txt b/samples/snippets/classify_text/resources/texts/cloud_computing.txt deleted file mode 100644 index 88172adf..00000000 --- a/samples/snippets/classify_text/resources/texts/cloud_computing.txt +++ /dev/null @@ -1 +0,0 @@ -Cloud computing is a computing-infrastructure and software model for enabling ubiquitous access to shared pools of configurable resources (such as computer networks, servers, storage, applications and services), which can be rapidly provisioned with minimal management effort, often over the Internet. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/eclipse.txt b/samples/snippets/classify_text/resources/texts/eclipse.txt deleted file mode 100644 index 5d16217e..00000000 --- a/samples/snippets/classify_text/resources/texts/eclipse.txt +++ /dev/null @@ -1 +0,0 @@ -A solar eclipse (as seen from the planet Earth) is a type of eclipse that occurs when the Moon passes between the Sun and Earth, and when the Moon fully or partially blocks (occults) the Sun. diff --git a/samples/snippets/classify_text/resources/texts/eclipse_of_the_sun.txt b/samples/snippets/classify_text/resources/texts/eclipse_of_the_sun.txt deleted file mode 100644 index 7236fc9d..00000000 --- a/samples/snippets/classify_text/resources/texts/eclipse_of_the_sun.txt +++ /dev/null @@ -1 +0,0 @@ -Eclipse of the Sun is the debut novel by English author Phil Whitaker. It won the 1997 John Llewellyn Rhys Prize a Betty Trask Award in 1998, and was shortlisted for the 1997 Whitbread First Novel Award. diff --git a/samples/snippets/classify_text/resources/texts/email.txt b/samples/snippets/classify_text/resources/texts/email.txt deleted file mode 100644 index 3d430527..00000000 --- a/samples/snippets/classify_text/resources/texts/email.txt +++ /dev/null @@ -1 +0,0 @@ -Electronic mail (email or e-mail) is a method of exchanging messages between people using electronics. Email first entered substantial use in the 1960s and by the mid-1970s had taken the form now recognized as email. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/gcp.txt b/samples/snippets/classify_text/resources/texts/gcp.txt deleted file mode 100644 index 1ed09b2c..00000000 --- a/samples/snippets/classify_text/resources/texts/gcp.txt +++ /dev/null @@ -1 +0,0 @@ -Google Cloud Platform, offered by Google, is a suite of cloud computing services that runs on the same infrastructure that Google uses internally for its end-user products, such as Google Search and YouTube. Alongside a set of management tools, it provides a series of modular cloud services including computing, data storage, data analytics and machine learning. diff --git a/samples/snippets/classify_text/resources/texts/gmail.txt b/samples/snippets/classify_text/resources/texts/gmail.txt deleted file mode 100644 index 89c9704b..00000000 --- a/samples/snippets/classify_text/resources/texts/gmail.txt +++ /dev/null @@ -1 +0,0 @@ -Gmail is a free, advertising-supported email service developed by Google. Users can access Gmail on the web and through mobile apps for Android and iOS, as well as through third-party programs that synchronize email content through POP or IMAP protocols. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/google.txt b/samples/snippets/classify_text/resources/texts/google.txt deleted file mode 100644 index 06828635..00000000 --- a/samples/snippets/classify_text/resources/texts/google.txt +++ /dev/null @@ -1 +0,0 @@ -Google is an American multinational technology company that specializes in Internet-related services and products. These include online advertising technologies, search, cloud computing, software, and hardware. diff --git a/samples/snippets/classify_text/resources/texts/harry_potter.txt b/samples/snippets/classify_text/resources/texts/harry_potter.txt deleted file mode 100644 index 339c10af..00000000 --- a/samples/snippets/classify_text/resources/texts/harry_potter.txt +++ /dev/null @@ -1 +0,0 @@ -Harry Potter is a series of fantasy novels written by British author J. K. Rowling. The novels chronicle the life of a young wizard, Harry Potter, and his friends Hermione Granger and Ron Weasley, all of whom are students at Hogwarts School of Witchcraft and Wizardry. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/matilda.txt b/samples/snippets/classify_text/resources/texts/matilda.txt deleted file mode 100644 index e1539d7e..00000000 --- a/samples/snippets/classify_text/resources/texts/matilda.txt +++ /dev/null @@ -1 +0,0 @@ -Matilda is a book by British writer Roald Dahl. Matilda won the Children's Book Award in 1999. It was published in 1988 by Jonathan Cape in London, with 232 pages and illustrations by Quentin Blake. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/mobile_phone.txt b/samples/snippets/classify_text/resources/texts/mobile_phone.txt deleted file mode 100644 index 725e22ef..00000000 --- a/samples/snippets/classify_text/resources/texts/mobile_phone.txt +++ /dev/null @@ -1 +0,0 @@ -A mobile phone is a portable device that can make and receive calls over a radio frequency link while the user is moving within a telephone service area. The radio frequency link establishes a connection to the switching systems of a mobile phone operator, which provides access to the public switched telephone network (PSTN). \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/mr_fox.txt b/samples/snippets/classify_text/resources/texts/mr_fox.txt deleted file mode 100644 index 354feced..00000000 --- a/samples/snippets/classify_text/resources/texts/mr_fox.txt +++ /dev/null @@ -1 +0,0 @@ -Fantastic Mr Fox is a children's novel written by British author Roald Dahl. It was published in 1970, by George Allen & Unwin in the UK and Alfred A. Knopf in the U.S., with illustrations by Donald Chaffin. \ No newline at end of file diff --git a/samples/snippets/classify_text/resources/texts/wireless.txt b/samples/snippets/classify_text/resources/texts/wireless.txt deleted file mode 100644 index d742331c..00000000 --- a/samples/snippets/classify_text/resources/texts/wireless.txt +++ /dev/null @@ -1 +0,0 @@ -Wireless communication, or sometimes simply wireless, is the transfer of information or power between two or more points that are not connected by an electrical conductor. The most common wireless technologies use radio waves. \ No newline at end of file diff --git a/samples/snippets/cloud-client/.DS_Store b/samples/snippets/cloud-client/.DS_Store deleted file mode 100644 index f344c851a0ee4f90f50741edcbb6236ebbbc354d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK!A`<J5S;~-5@Y0GqTcr6jRT0%lSxzY;LQZ12Q|<JB2BO*P#{_{{SN&jf56{y zW_KYddhuWknMr2fbarMp^V;lo06@5-b_Jja02V4?rhvmYLi40ck};kvqM$YWUgV?w z=J$KSQZzgMBLnpAGBAdUKN<EH-`_AUm)}Jun_FAYTZMvE*tBjN-DuK?y?8Wqy}`A5 z3fdjt*cVaMo7<j$8FVJi;`T`t#$FJ11`FXgS3%g0CT=te+e5X^xfgdaS8dcR?j=dZ zu2oC&$gWOHGO_J)Ngh^f)2U_c>{pJ@TK5l+$<y@tMN=y9>r=92a0ahvsOrXzLD-AJ zJA9_tJXH)nbRY%~4!+FJvKg5HW`G%3RR+wdX>F`(fm|0ezzqDF0XiQfDxqUA)u@gR z98?Q{m_xS`w5gY%9BI%om}<ls6rocQb*eBehS2HgmnP0Jm}=DNAWZWi%+A7eC_?Ry z>q`|5!qLbhGr$adW`KG>lp@{#r$6`qDu@SWfEid#21KsjsJmF3xm%a2q`Ow4wopkZ oF4Z_sK|@`|7)w|2E~*mrOEM50gQ-UJpzx1?qJaly;7=L&02eA$o&W#< diff --git a/samples/snippets/cloud-client/v1/README.rst b/samples/snippets/cloud-client/v1/README.rst deleted file mode 100644 index e0d71946..00000000 --- a/samples/snippets/cloud-client/v1/README.rst +++ /dev/null @@ -1,99 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Natural Language API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/cloud-client/v1/README.rst - - -This directory contains samples for Google Cloud Natural Language API. The `Google Cloud Natural Language API`_ provides natural language understanding technologies to developers, including sentiment analysis, entity recognition, and syntax analysis. This API is part of the larger Cloud Machine Learning API. - -- See the `migration guide`_ for information about migrating to Python client library v0.26.1. - -.. _migration guide: https://cloud.google.com/natural-language/docs/python-client-migration - - - - -.. _Google Cloud Natural Language API: https://cloud.google.com/natural-language/docs/ - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the sample. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Sample -------------------------------------------------------------------------------- - -Quickstart -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/cloud-client/v1/quickstart.py,language/cloud-client/v1/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python quickstart.py - - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/cloud-client/v1/README.rst.in b/samples/snippets/cloud-client/v1/README.rst.in deleted file mode 100644 index 9bf38dbf..00000000 --- a/samples/snippets/cloud-client/v1/README.rst.in +++ /dev/null @@ -1,30 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Natural Language API - short_name: Cloud Natural Language API - url: https://cloud.google.com/natural-language/docs/ - description: > - The `Google Cloud Natural Language API`_ provides natural language - understanding technologies to developers, including sentiment analysis, - entity recognition, and syntax analysis. This API is part of the larger - Cloud Machine Learning API. - - - - See the `migration guide`_ for information about migrating to Python client library v0.26.1. - - - .. _migration guide: https://cloud.google.com/natural-language/docs/python-client-migration - -setup: -- auth -- install_deps - -samples: -- name: Quickstart - file: quickstart.py - show_help: true - -cloud_client_library: true - -folder: language/cloud-client/v1 \ No newline at end of file diff --git a/samples/snippets/cloud-client/v1/noxfile.py b/samples/snippets/cloud-client/v1/noxfile.py deleted file mode 100644 index 05770846..00000000 --- a/samples/snippets/cloud-client/v1/noxfile.py +++ /dev/null @@ -1,292 +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. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, Optional - -import nox - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # 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": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8") - else: - session.install("flake8", "flake8-annotations") - - args = FLAKE8_COMMON_ARGS + [ - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( - "**/test_*.py", recursive=True - ) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - 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.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("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") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) - elif "pytest-xdist" in packages: - concurrent_args.extend(["-n", "auto"]) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/cloud-client/v1/quickstart.py b/samples/snippets/cloud-client/v1/quickstart.py deleted file mode 100644 index bbc914d1..00000000 --- a/samples/snippets/cloud-client/v1/quickstart.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2016 Google Inc. All Rights Reserved. -# -# 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. - - -def run_quickstart(): - # [START language_quickstart] - # Imports the Google Cloud client library - # [START language_python_migration_imports] - from google.cloud import language_v1 - - # [END language_python_migration_imports] - # Instantiates a client - # [START language_python_migration_client] - client = language_v1.LanguageServiceClient() - # [END language_python_migration_client] - - # The text to analyze - text = "Hello, world!" - document = language_v1.Document( - content=text, type_=language_v1.Document.Type.PLAIN_TEXT - ) - - # Detects the sentiment of the text - sentiment = client.analyze_sentiment( - request={"document": document} - ).document_sentiment - - print("Text: {}".format(text)) - print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude)) - # [END language_quickstart] - - -if __name__ == "__main__": - run_quickstart() diff --git a/samples/snippets/cloud-client/v1/quickstart_test.py b/samples/snippets/cloud-client/v1/quickstart_test.py deleted file mode 100644 index 59b44da8..00000000 --- a/samples/snippets/cloud-client/v1/quickstart_test.py +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import quickstart - - -def test_quickstart(capsys): - quickstart.run_quickstart() - out, _ = capsys.readouterr() - assert "Sentiment" in out diff --git a/samples/snippets/cloud-client/v1/requirements-test.txt b/samples/snippets/cloud-client/v1/requirements-test.txt deleted file mode 100644 index 49780e03..00000000 --- a/samples/snippets/cloud-client/v1/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.2.0 diff --git a/samples/snippets/cloud-client/v1/requirements.txt b/samples/snippets/cloud-client/v1/requirements.txt deleted file mode 100644 index c3458e3d..00000000 --- a/samples/snippets/cloud-client/v1/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -google-cloud-language==2.6.1 diff --git a/samples/snippets/cloud-client/v1/resources/text.txt b/samples/snippets/cloud-client/v1/resources/text.txt deleted file mode 100644 index 97a1cea0..00000000 --- a/samples/snippets/cloud-client/v1/resources/text.txt +++ /dev/null @@ -1 +0,0 @@ -President Obama is speaking at the White House. \ No newline at end of file diff --git a/samples/snippets/cloud-client/v1/set_endpoint.py b/samples/snippets/cloud-client/v1/set_endpoint.py deleted file mode 100644 index c49537a5..00000000 --- a/samples/snippets/cloud-client/v1/set_endpoint.py +++ /dev/null @@ -1,42 +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. - - -def set_endpoint(): - """Change your endpoint""" - # [START language_set_endpoint] - # Imports the Google Cloud client library - from google.cloud import language_v1 - - client_options = {"api_endpoint": "eu-language.googleapis.com:443"} - - # Instantiates a client - client = language_v1.LanguageServiceClient(client_options=client_options) - # [END language_set_endpoint] - - # The text to analyze - document = language_v1.Document( - content="Hello, world!", type_=language_v1.Document.Type.PLAIN_TEXT - ) - - # Detects the sentiment of the text - sentiment = client.analyze_sentiment( - request={"document": document} - ).document_sentiment - - print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude)) - - -if __name__ == "__main__": - set_endpoint() diff --git a/samples/snippets/cloud-client/v1/set_endpoint_test.py b/samples/snippets/cloud-client/v1/set_endpoint_test.py deleted file mode 100644 index 817748b1..00000000 --- a/samples/snippets/cloud-client/v1/set_endpoint_test.py +++ /dev/null @@ -1,22 +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. - -import set_endpoint - - -def test_set_endpoint(capsys): - set_endpoint.set_endpoint() - - out, _ = capsys.readouterr() - assert "Sentiment" in out diff --git a/samples/snippets/generated-samples/v1/language_sentiment_text.py b/samples/snippets/generated-samples/v1/language_sentiment_text.py deleted file mode 100644 index 13447d17..00000000 --- a/samples/snippets/generated-samples/v1/language_sentiment_text.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2018 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "analyze_sentiment") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -import sys - -# isort: split -# [START language_sentiment_text] - -from google.cloud import language_v1 -import six - - -def sample_analyze_sentiment(content): - - client = language_v1.LanguageServiceClient() - - # content = 'Your text to analyze, e.g. Hello, world!' - - if isinstance(content, six.binary_type): - content = content.decode("utf-8") - - type_ = language_v1.Document.Type.PLAIN_TEXT - document = {"type_": type_, "content": content} - - response = client.analyze_sentiment(request={"document": document}) - sentiment = response.document_sentiment - print("Score: {}".format(sentiment.score)) - print("Magnitude: {}".format(sentiment.magnitude)) - - -# [END language_sentiment_text] - - -def main(): - # FIXME: Convert argv from strings to the correct types. - sample_analyze_sentiment(*sys.argv[1:]) - - -if __name__ == "__main__": - main() diff --git a/samples/snippets/generated-samples/v1/language_sentiment_text_test.py b/samples/snippets/generated-samples/v1/language_sentiment_text_test.py deleted file mode 100644 index fd89f626..00000000 --- a/samples/snippets/generated-samples/v1/language_sentiment_text_test.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -# 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. - -import language_sentiment_text - - -def test_analyze_sentiment_text_positive(capsys): - language_sentiment_text.sample_analyze_sentiment("Happy Happy Joy Joy") - out, _ = capsys.readouterr() - assert "Score: 0." in out - - -def test_analyze_sentiment_text_negative(capsys): - language_sentiment_text.sample_analyze_sentiment("Angry Angry Sad Sad") - out, _ = capsys.readouterr() - assert "Score: -0." in out diff --git a/samples/snippets/generated-samples/v1/noxfile.py b/samples/snippets/generated-samples/v1/noxfile.py deleted file mode 100644 index 05770846..00000000 --- a/samples/snippets/generated-samples/v1/noxfile.py +++ /dev/null @@ -1,292 +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. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, Optional - -import nox - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # 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": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8") - else: - session.install("flake8", "flake8-annotations") - - args = FLAKE8_COMMON_ARGS + [ - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( - "**/test_*.py", recursive=True - ) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - 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.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("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") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) - elif "pytest-xdist" in packages: - concurrent_args.extend(["-n", "auto"]) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/generated-samples/v1/requirements-test.txt b/samples/snippets/generated-samples/v1/requirements-test.txt deleted file mode 100644 index 49780e03..00000000 --- a/samples/snippets/generated-samples/v1/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.2.0 diff --git a/samples/snippets/generated-samples/v1/requirements.txt b/samples/snippets/generated-samples/v1/requirements.txt deleted file mode 100644 index c3458e3d..00000000 --- a/samples/snippets/generated-samples/v1/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -google-cloud-language==2.6.1 diff --git a/samples/snippets/sentiment/README.md b/samples/snippets/sentiment/README.md deleted file mode 100644 index 313817ef..00000000 --- a/samples/snippets/sentiment/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Introduction - -[![Open in Cloud Shell][shell_img]][shell_link] - -[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png -[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=language/sentiment/README.md - -This sample contains the code referenced in the -[Sentiment Analysis Tutorial](http://cloud.google.com/natural-language/docs/sentiment-tutorial) -within the Google Cloud Natural Language API Documentation. A full walkthrough of this sample -is located within the documentation. - -This sample is a simple illustration of how to construct a sentiment analysis -request and process a response using the API. - -## Prerequisites - -Set up your -[Cloud Natural Language API project](https://cloud.google.com/natural-language/docs/getting-started#set_up_a_project) -, which includes: - -* Enabling the Natural Language API -* Setting up a service account -* Ensuring you've properly set up your `GOOGLE_APPLICATION_CREDENTIALS` for proper - authentication to the service. - -## Download the Code - -``` -$ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git -$ cd python-docs-samples/language/sentiment -``` - -## Run the Code - -Open a sample folder, create a virtualenv, install dependencies, and run the sample: - -``` -$ virtualenv env -$ source env/bin/activate -(env)$ pip install -r requirements.txt -``` - -### Usage - -This sample provides four sample movie reviews which you can -provide to the sample on the command line. (You can also -pass your own text files.) - -``` -(env)$ python sentiment_analysis.py textfile.txt -Sentiment: score of -0.1 with magnitude of 6.7 -``` diff --git a/samples/snippets/sentiment/noxfile.py b/samples/snippets/sentiment/noxfile.py deleted file mode 100644 index 05770846..00000000 --- a/samples/snippets/sentiment/noxfile.py +++ /dev/null @@ -1,292 +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. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, Optional - -import nox - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # 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": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8") - else: - session.install("flake8", "flake8-annotations") - - args = FLAKE8_COMMON_ARGS + [ - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( - "**/test_*.py", recursive=True - ) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - 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.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("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") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) - elif "pytest-xdist" in packages: - concurrent_args.extend(["-n", "auto"]) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/sentiment/requirements-test.txt b/samples/snippets/sentiment/requirements-test.txt deleted file mode 100644 index 49780e03..00000000 --- a/samples/snippets/sentiment/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.2.0 diff --git a/samples/snippets/sentiment/requirements.txt b/samples/snippets/sentiment/requirements.txt deleted file mode 100644 index c3458e3d..00000000 --- a/samples/snippets/sentiment/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -google-cloud-language==2.6.1 diff --git a/samples/snippets/sentiment/resources/mixed.txt b/samples/snippets/sentiment/resources/mixed.txt deleted file mode 100644 index d4a42aa2..00000000 --- a/samples/snippets/sentiment/resources/mixed.txt +++ /dev/null @@ -1,20 +0,0 @@ -I really wanted to love 'Bladerunner' but ultimately I couldn't get -myself to appreciate it fully. However, you may like it if you're into -science fiction, especially if you're interested in the philosophical -exploration of what it means to be human or machine. Some of the gizmos -like the flying cars and the Vouight-Kampff machine (which seemed very -steampunk), were quite cool. - -I did find the plot pretty slow and but the dialogue and action sequences -were good. Unlike most science fiction films, this one was mostly quiet, and -not all that much happened, except during the last 15 minutes. I didn't -understand why a unicorn was in the movie. The visual effects were fantastic, -however, and the musical score and overall mood was quite interesting. -A futurist Los Angeles that was both highly polished and also falling apart -reminded me of 'Outland.' Certainly, the style of the film made up for -many of its pedantic plot holes. - -If you want your sci-fi to be lasers and spaceships, 'Bladerunner' may -disappoint you. But if you want it to make you think, this movie may -be worth the money. - diff --git a/samples/snippets/sentiment/resources/neg.txt b/samples/snippets/sentiment/resources/neg.txt deleted file mode 100644 index 5dcbec0f..00000000 --- a/samples/snippets/sentiment/resources/neg.txt +++ /dev/null @@ -1,4 +0,0 @@ -What was Hollywood thinking with this movie! I hated, -hated, hated it. BORING! I went afterwards and demanded my money back. -They refused. - diff --git a/samples/snippets/sentiment/resources/neutral.txt b/samples/snippets/sentiment/resources/neutral.txt deleted file mode 100644 index 89839ef2..00000000 --- a/samples/snippets/sentiment/resources/neutral.txt +++ /dev/null @@ -1,3 +0,0 @@ -I neither liked nor disliked this movie. Parts were interesting, but -overall I was left wanting more. The acting was pretty good. - diff --git a/samples/snippets/sentiment/resources/pos.txt b/samples/snippets/sentiment/resources/pos.txt deleted file mode 100644 index 5f211496..00000000 --- a/samples/snippets/sentiment/resources/pos.txt +++ /dev/null @@ -1,11 +0,0 @@ -`Bladerunner` is often touted as one of the best science fiction films ever -made. Indeed, it satisfies many of the requisites for good sci-fi: a future -world with flying cars and humanoid robots attempting to rebel against their -creators. But more than anything, `Bladerunner` is a fantastic exploration -of the nature of what it means to be human. If we create robots which can -think, will they become human? And if they do, what makes us unique? Indeed, -how can we be sure we're not human in any case? `Bladerunner` explored -these issues before such movies as `The Matrix,' and did so intelligently. -The visual effects and score by Vangelis set the mood. See this movie -in a dark theatre to appreciate it fully. Highly recommended! - diff --git a/samples/snippets/sentiment/sentiment_analysis.py b/samples/snippets/sentiment/sentiment_analysis.py deleted file mode 100644 index e82c3a68..00000000 --- a/samples/snippets/sentiment/sentiment_analysis.py +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright 2016, 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. - -# [START language_sentiment_tutorial] -"""Demonstrates how to make a simple call to the Natural Language API.""" - -# [START language_sentiment_tutorial_imports] -import argparse - -from google.cloud import language_v1 - -# [END language_sentiment_tutorial_imports] - - -# [START language_sentiment_tutorial_print_result] -def print_result(annotations): - score = annotations.document_sentiment.score - magnitude = annotations.document_sentiment.magnitude - - for index, sentence in enumerate(annotations.sentences): - sentence_sentiment = sentence.sentiment.score - print( - "Sentence {} has a sentiment score of {}".format(index, sentence_sentiment) - ) - - print( - "Overall Sentiment: score of {} with magnitude of {}".format(score, magnitude) - ) - return 0 - - -# [END language_sentiment_tutorial_print_result] - - -# [START language_sentiment_tutorial_analyze_sentiment] -def analyze(movie_review_filename): - """Run a sentiment analysis request on text within a passed filename.""" - client = language_v1.LanguageServiceClient() - - with open(movie_review_filename, "r") as review_file: - # Instantiates a plain text document. - content = review_file.read() - - document = language_v1.Document( - content=content, type_=language_v1.Document.Type.PLAIN_TEXT - ) - annotations = client.analyze_sentiment(request={"document": document}) - - # Print the results - print_result(annotations) - - -# [END language_sentiment_tutorial_analyze_sentiment] - - -# [START language_sentiment_tutorial_run_application] -if __name__ == "__main__": - parser = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - parser.add_argument( - "movie_review_filename", - help="The filename of the movie review you'd like to analyze.", - ) - args = parser.parse_args() - - analyze(args.movie_review_filename) -# [END language_sentiment_tutorial_run_application] -# [END language_sentiment_tutorial] diff --git a/samples/snippets/sentiment/sentiment_analysis_test.py b/samples/snippets/sentiment/sentiment_analysis_test.py deleted file mode 100644 index 845e842f..00000000 --- a/samples/snippets/sentiment/sentiment_analysis_test.py +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright 2016, 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. - -import os -import re - -from sentiment_analysis import analyze - -RESOURCES = os.path.join(os.path.dirname(__file__), "resources") - - -def test_pos(capsys): - analyze(os.path.join(RESOURCES, "pos.txt")) - out, err = capsys.readouterr() - score = float(re.search("score of (.+?) with", out).group(1)) - magnitude = float(re.search("magnitude of (.+?)", out).group(1)) - assert score * magnitude > 0 - - -def test_neg(capsys): - analyze(os.path.join(RESOURCES, "neg.txt")) - out, err = capsys.readouterr() - score = float(re.search("score of (.+?) with", out).group(1)) - magnitude = float(re.search("magnitude of (.+?)", out).group(1)) - assert score * magnitude < 0 - - -def test_mixed(capsys): - analyze(os.path.join(RESOURCES, "mixed.txt")) - out, err = capsys.readouterr() - score = float(re.search("score of (.+?) with", out).group(1)) - assert score <= 0.3 - assert score >= -0.3 - - -def test_neutral(capsys): - analyze(os.path.join(RESOURCES, "neutral.txt")) - out, err = capsys.readouterr() - magnitude = float(re.search("magnitude of (.+?)", out).group(1)) - assert magnitude <= 2.0 diff --git a/samples/v1/language_classify_gcs.py b/samples/v1/language_classify_gcs.py deleted file mode 100644 index b357a8ae..00000000 --- a/samples/v1/language_classify_gcs.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_classify_gcs") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Classify Content (GCS) -# description: Classifying Content in text file stored in Cloud Storage -# usage: python3 samples/v1/language_classify_gcs.py [--gcs_content_uri "gs://cloud-samples-data/language/classify-entertainment.txt"] - -# [START language_classify_gcs] -from google.cloud import language_v1 - -def sample_classify_text(gcs_content_uri): - """ - Classifying Content in text file stored in Cloud Storage - - Args: - gcs_content_uri Google Cloud Storage URI where the file content is located. - e.g. gs://[Your Bucket]/[Path to File] - The text file must include at least 20 words. - """ - - client = language_v1.LanguageServiceClient() - - # gcs_content_uri = 'gs://cloud-samples-data/language/classify-entertainment.txt' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"gcs_content_uri": gcs_content_uri, "type_": type_, "language": language} - - response = client.classify_text(request = {'document': document}) - # Loop through classified categories returned from the API - for category in response.categories: - # Get the name of the category representing the document. - # See the predefined taxonomy of categories: - # https://cloud.google.com/natural-language/docs/categories - print(u"Category name: {}".format(category.name)) - # Get the confidence. Number representing how certain the classifier - # is that this category represents the provided text. - print(u"Confidence: {}".format(category.confidence)) - - -# [END language_classify_gcs] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument( - "--gcs_content_uri", - type=str, - default="gs://cloud-samples-data/language/classify-entertainment.txt", - ) - args = parser.parse_args() - - sample_classify_text(args.gcs_content_uri) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_classify_text.py b/samples/v1/language_classify_text.py deleted file mode 100644 index d1efb35e..00000000 --- a/samples/v1/language_classify_text.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_classify_text") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Classify Content -# description: Classifying Content in a String -# usage: python3 samples/v1/language_classify_text.py [--text_content "That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows."] - -# [START language_classify_text] -from google.cloud import language_v1 # Requires `google-cloud-language>=2.6.0` - -def sample_classify_text(text_content): - """ - Classifying Content in a String - - Args: - text_content The text content to analyze. - """ - - client = language_v1.LanguageServiceClient() - - # text_content = "That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows." - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"content": text_content, "type_": type_, "language": language} - - content_categories_version = ( - language_v1.ClassificationModelOptions.V2Model.ContentCategoriesVersion.V2) - response = client.classify_text(request = { - "document": document, - "classification_model_options": { - "v2_model": { - "content_categories_version": content_categories_version - } - } - }) - # Loop through classified categories returned from the API - for category in response.categories: - # Get the name of the category representing the document. - # See the predefined taxonomy of categories: - # https://cloud.google.com/natural-language/docs/categories - print(u"Category name: {}".format(category.name)) - # Get the confidence. Number representing how certain the classifier - # is that this category represents the provided text. - print(u"Confidence: {}".format(category.confidence)) - - -# [END language_classify_text] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument( - "--text_content", - type=str, - default="That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows.", - ) - args = parser.parse_args() - - sample_classify_text(args.text_content) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_entities_gcs.py b/samples/v1/language_entities_gcs.py deleted file mode 100644 index 6bdb8577..00000000 --- a/samples/v1/language_entities_gcs.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_entities_gcs") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Entities (GCS) -# description: Analyzing Entities in text file stored in Cloud Storage -# usage: python3 samples/v1/language_entities_gcs.py [--gcs_content_uri "gs://cloud-samples-data/language/entity.txt"] - -# [START language_entities_gcs] -from google.cloud import language_v1 - -def sample_analyze_entities(gcs_content_uri): - """ - Analyzing Entities in text file stored in Cloud Storage - - Args: - gcs_content_uri Google Cloud Storage URI where the file content is located. - e.g. gs://[Your Bucket]/[Path to File] - """ - - client = language_v1.LanguageServiceClient() - - # gcs_content_uri = 'gs://cloud-samples-data/language/entity.txt' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"gcs_content_uri": gcs_content_uri, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_entities(request = {'document': document, 'encoding_type': encoding_type}) - # Loop through entitites returned from the API - for entity in response.entities: - print(u"Representative name for the entity: {}".format(entity.name)) - # Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al - print(u"Entity type: {}".format(language_v1.Entity.Type(entity.type_).name)) - # Get the salience score associated with the entity in the [0, 1.0] range - print(u"Salience score: {}".format(entity.salience)) - # Loop over the metadata associated with entity. For many known entities, - # the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid). - # Some entity types may have additional metadata, e.g. ADDRESS entities - # may have metadata for the address street_name, postal_code, et al. - for metadata_name, metadata_value in entity.metadata.items(): - print(u"{}: {}".format(metadata_name, metadata_value)) - - # Loop over the mentions of this entity in the input document. - # The API currently supports proper noun mentions. - for mention in entity.mentions: - print(u"Mention text: {}".format(mention.text.content)) - # Get the mention type, e.g. PROPER for proper noun - print( - u"Mention type: {}".format(language_v1.EntityMention.Type(mention.type_).name) - ) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_entities_gcs] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument( - "--gcs_content_uri", - type=str, - default="gs://cloud-samples-data/language/entity.txt", - ) - args = parser.parse_args() - - sample_analyze_entities(args.gcs_content_uri) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_entities_text.py b/samples/v1/language_entities_text.py deleted file mode 100644 index 2cce0015..00000000 --- a/samples/v1/language_entities_text.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_entities_text") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Entities -# description: Analyzing Entities in a String -# usage: python3 samples/v1/language_entities_text.py [--text_content "California is a state."] - -# [START language_entities_text] -from google.cloud import language_v1 - -def sample_analyze_entities(text_content): - """ - Analyzing Entities in a String - - Args: - text_content The text content to analyze - """ - - client = language_v1.LanguageServiceClient() - - # text_content = 'California is a state.' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"content": text_content, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_entities(request = {'document': document, 'encoding_type': encoding_type}) - - # Loop through entitites returned from the API - for entity in response.entities: - print(u"Representative name for the entity: {}".format(entity.name)) - - # Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al - print(u"Entity type: {}".format(language_v1.Entity.Type(entity.type_).name)) - - # Get the salience score associated with the entity in the [0, 1.0] range - print(u"Salience score: {}".format(entity.salience)) - - # Loop over the metadata associated with entity. For many known entities, - # the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid). - # Some entity types may have additional metadata, e.g. ADDRESS entities - # may have metadata for the address street_name, postal_code, et al. - for metadata_name, metadata_value in entity.metadata.items(): - print(u"{}: {}".format(metadata_name, metadata_value)) - - # Loop over the mentions of this entity in the input document. - # The API currently supports proper noun mentions. - for mention in entity.mentions: - print(u"Mention text: {}".format(mention.text.content)) - - # Get the mention type, e.g. PROPER for proper noun - print( - u"Mention type: {}".format(language_v1.EntityMention.Type(mention.type_).name) - ) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_entities_text] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("--text_content", type=str, default="California is a state.") - args = parser.parse_args() - - sample_analyze_entities(args.text_content) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_entity_sentiment_gcs.py b/samples/v1/language_entity_sentiment_gcs.py deleted file mode 100644 index dba3dc1b..00000000 --- a/samples/v1/language_entity_sentiment_gcs.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_entity_sentiment_gcs") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Entity Sentiment (GCS) -# description: Analyzing Entity Sentiment in text file stored in Cloud Storage -# usage: python3 samples/v1/language_entity_sentiment_gcs.py [--gcs_content_uri "gs://cloud-samples-data/language/entity-sentiment.txt"] - -# [START language_entity_sentiment_gcs] -from google.cloud import language_v1 - -def sample_analyze_entity_sentiment(gcs_content_uri): - """ - Analyzing Entity Sentiment in text file stored in Cloud Storage - - Args: - gcs_content_uri Google Cloud Storage URI where the file content is located. - e.g. gs://[Your Bucket]/[Path to File] - """ - - client = language_v1.LanguageServiceClient() - - # gcs_content_uri = 'gs://cloud-samples-data/language/entity-sentiment.txt' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"gcs_content_uri": gcs_content_uri, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_entity_sentiment(request = {'document': document, 'encoding_type': encoding_type}) - # Loop through entitites returned from the API - for entity in response.entities: - print(u"Representative name for the entity: {}".format(entity.name)) - # Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al - print(u"Entity type: {}".format(language_v1.Entity.Type(entity.type_).name)) - # Get the salience score associated with the entity in the [0, 1.0] range - print(u"Salience score: {}".format(entity.salience)) - # Get the aggregate sentiment expressed for this entity in the provided document. - sentiment = entity.sentiment - print(u"Entity sentiment score: {}".format(sentiment.score)) - print(u"Entity sentiment magnitude: {}".format(sentiment.magnitude)) - # Loop over the metadata associated with entity. For many known entities, - # the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid). - # Some entity types may have additional metadata, e.g. ADDRESS entities - # may have metadata for the address street_name, postal_code, et al. - for metadata_name, metadata_value in entity.metadata.items(): - print(u"{} = {}".format(metadata_name, metadata_value)) - - # Loop over the mentions of this entity in the input document. - # The API currently supports proper noun mentions. - for mention in entity.mentions: - print(u"Mention text: {}".format(mention.text.content)) - # Get the mention type, e.g. PROPER for proper noun - print( - u"Mention type: {}".format(language_v1.EntityMention.Type(mention.type_).name) - ) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_entity_sentiment_gcs] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument( - "--gcs_content_uri", - type=str, - default="gs://cloud-samples-data/language/entity-sentiment.txt", - ) - args = parser.parse_args() - - sample_analyze_entity_sentiment(args.gcs_content_uri) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_entity_sentiment_text.py b/samples/v1/language_entity_sentiment_text.py deleted file mode 100644 index 4e1341d5..00000000 --- a/samples/v1/language_entity_sentiment_text.py +++ /dev/null @@ -1,104 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_entity_sentiment_text") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Entity Sentiment -# description: Analyzing Entity Sentiment in a String -# usage: python3 samples/v1/language_entity_sentiment_text.py [--text_content "Grapes are good. Bananas are bad."] - -# [START language_entity_sentiment_text] -from google.cloud import language_v1 - -def sample_analyze_entity_sentiment(text_content): - """ - Analyzing Entity Sentiment in a String - - Args: - text_content The text content to analyze - """ - - client = language_v1.LanguageServiceClient() - - # text_content = 'Grapes are good. Bananas are bad.' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.types.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"content": text_content, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_entity_sentiment(request = {'document': document, 'encoding_type': encoding_type}) - # Loop through entitites returned from the API - for entity in response.entities: - print(u"Representative name for the entity: {}".format(entity.name)) - # Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al - print(u"Entity type: {}".format(language_v1.Entity.Type(entity.type_).name)) - # Get the salience score associated with the entity in the [0, 1.0] range - print(u"Salience score: {}".format(entity.salience)) - # Get the aggregate sentiment expressed for this entity in the provided document. - sentiment = entity.sentiment - print(u"Entity sentiment score: {}".format(sentiment.score)) - print(u"Entity sentiment magnitude: {}".format(sentiment.magnitude)) - # Loop over the metadata associated with entity. For many known entities, - # the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid). - # Some entity types may have additional metadata, e.g. ADDRESS entities - # may have metadata for the address street_name, postal_code, et al. - for metadata_name, metadata_value in entity.metadata.items(): - print(u"{} = {}".format(metadata_name, metadata_value)) - - # Loop over the mentions of this entity in the input document. - # The API currently supports proper noun mentions. - for mention in entity.mentions: - print(u"Mention text: {}".format(mention.text.content)) - # Get the mention type, e.g. PROPER for proper noun - print( - u"Mention type: {}".format(language_v1.EntityMention.Type(mention.type_).name) - ) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_entity_sentiment_text] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument( - "--text_content", type=str, default="Grapes are good. Bananas are bad." - ) - args = parser.parse_args() - - sample_analyze_entity_sentiment(args.text_content) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_sentiment_gcs.py b/samples/v1/language_sentiment_gcs.py deleted file mode 100644 index f225db1c..00000000 --- a/samples/v1/language_sentiment_gcs.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_sentiment_gcs") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Sentiment (GCS) -# description: Analyzing Sentiment in text file stored in Cloud Storage -# usage: python3 samples/v1/language_sentiment_gcs.py [--gcs_content_uri "gs://cloud-samples-data/language/sentiment-positive.txt"] - -# [START language_sentiment_gcs] -from google.cloud import language_v1 - -def sample_analyze_sentiment(gcs_content_uri): - """ - Analyzing Sentiment in text file stored in Cloud Storage - - Args: - gcs_content_uri Google Cloud Storage URI where the file content is located. - e.g. gs://[Your Bucket]/[Path to File] - """ - - client = language_v1.LanguageServiceClient() - - # gcs_content_uri = 'gs://cloud-samples-data/language/sentiment-positive.txt' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"gcs_content_uri": gcs_content_uri, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_sentiment(request = {'document': document, 'encoding_type': encoding_type}) - # Get overall sentiment of the input document - print(u"Document sentiment score: {}".format(response.document_sentiment.score)) - print( - u"Document sentiment magnitude: {}".format( - response.document_sentiment.magnitude - ) - ) - # Get sentiment for all sentences in the document - for sentence in response.sentences: - print(u"Sentence text: {}".format(sentence.text.content)) - print(u"Sentence sentiment score: {}".format(sentence.sentiment.score)) - print(u"Sentence sentiment magnitude: {}".format(sentence.sentiment.magnitude)) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_sentiment_gcs] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument( - "--gcs_content_uri", - type=str, - default="gs://cloud-samples-data/language/sentiment-positive.txt", - ) - args = parser.parse_args() - - sample_analyze_sentiment(args.gcs_content_uri) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_sentiment_text.py b/samples/v1/language_sentiment_text.py deleted file mode 100644 index d94420a3..00000000 --- a/samples/v1/language_sentiment_text.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_sentiment_text") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Sentiment -# description: Analyzing Sentiment in a String -# usage: python3 samples/v1/language_sentiment_text.py [--text_content "I am so happy and joyful."] - -# [START language_sentiment_text] -from google.cloud import language_v1 - -def sample_analyze_sentiment(text_content): - """ - Analyzing Sentiment in a String - - Args: - text_content The text content to analyze - """ - - client = language_v1.LanguageServiceClient() - - # text_content = 'I am so happy and joyful.' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"content": text_content, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_sentiment(request = {'document': document, 'encoding_type': encoding_type}) - # Get overall sentiment of the input document - print(u"Document sentiment score: {}".format(response.document_sentiment.score)) - print( - u"Document sentiment magnitude: {}".format( - response.document_sentiment.magnitude - ) - ) - # Get sentiment for all sentences in the document - for sentence in response.sentences: - print(u"Sentence text: {}".format(sentence.text.content)) - print(u"Sentence sentiment score: {}".format(sentence.sentiment.score)) - print(u"Sentence sentiment magnitude: {}".format(sentence.sentiment.magnitude)) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_sentiment_text] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("--text_content", type=str, default="I am so happy and joyful.") - args = parser.parse_args() - - sample_analyze_sentiment(args.text_content) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_syntax_gcs.py b/samples/v1/language_syntax_gcs.py deleted file mode 100644 index 32c64ede..00000000 --- a/samples/v1/language_syntax_gcs.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_syntax_gcs") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Syntax (GCS) -# description: Analyzing Syntax in text file stored in Cloud Storage -# usage: python3 samples/v1/language_syntax_gcs.py [--gcs_content_uri "gs://cloud-samples-data/language/syntax-sentence.txt"] - -# [START language_syntax_gcs] -from google.cloud import language_v1 - -def sample_analyze_syntax(gcs_content_uri): - """ - Analyzing Syntax in text file stored in Cloud Storage - - Args: - gcs_content_uri Google Cloud Storage URI where the file content is located. - e.g. gs://[Your Bucket]/[Path to File] - """ - - client = language_v1.LanguageServiceClient() - - # gcs_content_uri = 'gs://cloud-samples-data/language/syntax-sentence.txt' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"gcs_content_uri": gcs_content_uri, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_syntax(request = {'document': document, 'encoding_type': encoding_type}) - # Loop through tokens returned from the API - for token in response.tokens: - # Get the text content of this token. Usually a word or punctuation. - text = token.text - print(u"Token text: {}".format(text.content)) - print( - u"Location of this token in overall document: {}".format(text.begin_offset) - ) - # Get the part of speech information for this token. - # Part of speech is defined in: - # http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf - part_of_speech = token.part_of_speech - # Get the tag, e.g. NOUN, ADJ for Adjective, et al. - print( - u"Part of Speech tag: {}".format( - language_v1.PartOfSpeech.Tag(part_of_speech.tag).name - ) - ) - # Get the voice, e.g. ACTIVE or PASSIVE - print(u"Voice: {}".format(language_v1.PartOfSpeech.Voice(part_of_speech.voice).name)) - # Get the tense, e.g. PAST, FUTURE, PRESENT, et al. - print(u"Tense: {}".format(language_v1.PartOfSpeech.Tense(part_of_speech.tense).name)) - # See API reference for additional Part of Speech information available - # Get the lemma of the token. Wikipedia lemma description - # https://en.wikipedia.org/wiki/Lemma_(morphology) - print(u"Lemma: {}".format(token.lemma)) - # Get the dependency tree parse information for this token. - # For more information on dependency labels: - # http://www.aclweb.org/anthology/P13-2017 - dependency_edge = token.dependency_edge - print(u"Head token index: {}".format(dependency_edge.head_token_index)) - print( - u"Label: {}".format(language_v1.DependencyEdge.Label(dependency_edge.label).name) - ) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_syntax_gcs] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument( - "--gcs_content_uri", - type=str, - default="gs://cloud-samples-data/language/syntax-sentence.txt", - ) - args = parser.parse_args() - - sample_analyze_syntax(args.gcs_content_uri) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/language_syntax_text.py b/samples/v1/language_syntax_text.py deleted file mode 100644 index 132c5779..00000000 --- a/samples/v1/language_syntax_text.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# DO NOT EDIT! This is a generated sample ("Request", "language_syntax_text") - -# To install the latest published package dependency, execute the following: -# pip install google-cloud-language - -# sample-metadata -# title: Analyzing Syntax -# description: Analyzing Syntax in a String -# usage: python3 samples/v1/language_syntax_text.py [--text_content "This is a short sentence."] - -# [START language_syntax_text] -from google.cloud import language_v1 - -def sample_analyze_syntax(text_content): - """ - Analyzing Syntax in a String - - Args: - text_content The text content to analyze - """ - - client = language_v1.LanguageServiceClient() - - # text_content = 'This is a short sentence.' - - # Available types: PLAIN_TEXT, HTML - type_ = language_v1.Document.Type.PLAIN_TEXT - - # Optional. If not specified, the language is automatically detected. - # For list of supported languages: - # https://cloud.google.com/natural-language/docs/languages - language = "en" - document = {"content": text_content, "type_": type_, "language": language} - - # Available values: NONE, UTF8, UTF16, UTF32 - encoding_type = language_v1.EncodingType.UTF8 - - response = client.analyze_syntax(request = {'document': document, 'encoding_type': encoding_type}) - # Loop through tokens returned from the API - for token in response.tokens: - # Get the text content of this token. Usually a word or punctuation. - text = token.text - print(u"Token text: {}".format(text.content)) - print( - u"Location of this token in overall document: {}".format(text.begin_offset) - ) - # Get the part of speech information for this token. - # Part of speech is defined in: - # http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf - part_of_speech = token.part_of_speech - # Get the tag, e.g. NOUN, ADJ for Adjective, et al. - print( - u"Part of Speech tag: {}".format( - language_v1.PartOfSpeech.Tag(part_of_speech.tag).name - ) - ) - # Get the voice, e.g. ACTIVE or PASSIVE - print(u"Voice: {}".format(language_v1.PartOfSpeech.Voice(part_of_speech.voice).name)) - # Get the tense, e.g. PAST, FUTURE, PRESENT, et al. - print(u"Tense: {}".format(language_v1.PartOfSpeech.Tense(part_of_speech.tense).name)) - # See API reference for additional Part of Speech information available - # Get the lemma of the token. Wikipedia lemma description - # https://en.wikipedia.org/wiki/Lemma_(morphology) - print(u"Lemma: {}".format(token.lemma)) - # Get the dependency tree parse information for this token. - # For more information on dependency labels: - # http://www.aclweb.org/anthology/P13-2017 - dependency_edge = token.dependency_edge - print(u"Head token index: {}".format(dependency_edge.head_token_index)) - print( - u"Label: {}".format(language_v1.DependencyEdge.Label(dependency_edge.label).name) - ) - - # Get the language of the text, which will be the same as - # the language specified in the request or, if not specified, - # the automatically-detected language. - print(u"Language of the text: {}".format(response.language)) - - -# [END language_syntax_text] - - -def main(): - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("--text_content", type=str, default="This is a short sentence.") - args = parser.parse_args() - - sample_analyze_syntax(args.text_content) - - -if __name__ == "__main__": - main() diff --git a/samples/v1/test/analyzing_entities.test.yaml b/samples/v1/test/analyzing_entities.test.yaml deleted file mode 100644 index 5fafd01e..00000000 --- a/samples/v1/test/analyzing_entities.test.yaml +++ /dev/null @@ -1,101 +0,0 @@ -type: test/samples -schema_version: 1 -test: - suites: - - name: "Analyzing Entities [code sample tests]" - cases: - - - name: language_entities_text - Analyzing the Entities of a text string (default value) - spec: - # Default value: "California is a state." - - call: {sample: language_entities_text} - - assert_contains: - - {literal: "Representative name for the entity: California"} - - {literal: "Entity type: LOCATION"} - - {literal: "Salience score:"} - - {literal: "wikipedia_url: https://en.wikipedia.org/wiki/California"} - - {literal: "mid: /m/01n7q"} - - {literal: "Mention text: California"} - - {literal: "Mention type: PROPER"} - - {literal: "Mention text: state"} - - {literal: "Mention type: COMMON"} - - {literal: "Language of the text: en"} - - - name: language_entities_text - Analyzing the Entities of a text string (*custom value*) - spec: - # Custom value: "Alice is a person. She lives in California." - - call: - sample: language_entities_text - params: - text_content: {literal: "Alice is a person. She lives in California."} - - assert_contains: - - {literal: "Representative name for the entity: Alice"} - - {literal: "Entity type: PERSON"} - - {literal: "Mention text: Alice"} - - {literal: "Mention type: PROPER"} - - {literal: "Mention text: person"} - - {literal: "Mention type: COMMON"} - - {literal: "Representative name for the entity: California"} - - {literal: "Entity type: LOCATION"} - - {literal: "wikipedia_url: https://en.wikipedia.org/wiki/California"} - - {literal: "mid: /m/01n7q"} - - {literal: "Language of the text: en"} - - - name: language_entities_text - Analyzing the Entities of a text string (*metadata attributes*) - spec: - # Try out some of the metadata attributes which should be available for dates, addresses, etc. - # In case fake (555) area code numbers don't work, using United States Naval Observatory number. - # Custom value: "I called 202-762-1401 on January 31, 2019 from 1600 Amphitheatre Parkway, Mountain View, CA." - - call: - sample: language_entities_text - params: - text_content: - literal: "I called 202-762-1401 on January 31, 2019 from 1600 Amphitheatre Parkway, Mountain View, CA." - # The results may change, but it's fair to say that at least one of the following types were detected: - - assert_contains_any: - - literal: "Entity type: DATE" - - literal: "Entity type: ADDRESS" - - literal: "Entity type: PHONE_NUMBER" - # Check that at least some of the supporting metadata for an entity was present in the response - - assert_contains_any: - - literal: "month: 1" - - literal: "day: 31" - - literal: "year: 2019" - - literal: "street_number: 1600" - - literal: "street_name: Amphitheatre Parkway" - - literal: "area_code: 202" - - literal: "number: 7621401" - - - name: language_entities_gcs - Analyzing the Entities of text file in GCS (default value) - spec: - # Default value: gs://cloud-samples-data/language/entity.txt - # => "California is a state." - - call: {sample: language_entities_gcs} - - assert_contains: - - {literal: "Representative name for the entity: California"} - - {literal: "Entity type: LOCATION"} - - {literal: "Salience score:"} - - {literal: "wikipedia_url: https://en.wikipedia.org/wiki/California"} - - {literal: "mid: /m/01n7q"} - - {literal: "Mention text: California"} - - {literal: "Mention type: PROPER"} - - {literal: "Mention text: state"} - - {literal: "Mention type: COMMON"} - - {literal: "Language of the text: en"} - - - name: language_entities_gcs - Analyzing the Entities of text file in GCS (*custom value*) - spec: - # Use different file: gs://cloud-samples-data/language/entity-sentiment.txt - # => "Grapes are good. Bananas are bad." - - call: - sample: language_entities_gcs - params: - gcs_content_uri: - literal: "gs://cloud-samples-data/language/entity-sentiment.txt" - - assert_contains: - - {literal: "Representative name for the entity: Grapes"} - - {literal: "Mention text: Grapes"} - - {literal: "Mention type: COMMON"} - - {literal: "Representative name for the entity: Bananas"} - - {literal: "Mention text: Bananas"} - - {literal: "Language of the text: en"} diff --git a/samples/v1/test/analyzing_entity_sentiment.test.yaml b/samples/v1/test/analyzing_entity_sentiment.test.yaml deleted file mode 100644 index beb8fb4a..00000000 --- a/samples/v1/test/analyzing_entity_sentiment.test.yaml +++ /dev/null @@ -1,63 +0,0 @@ -type: test/samples -schema_version: 1 -test: - suites: - - name: "Analyzing Entity Sentiment [code sample tests]" - cases: - - - name: language_entity_sentiment_text - Analyzing Entity Sentiment of a text string (default value) - spec: - # Default value: "Grapes are good. Bananas are bad." - - call: {sample: language_entity_sentiment_text} - - assert_contains: - - {literal: "Representative name for the entity: Grapes"} - - {literal: "Entity sentiment score: 0."} - - {literal: "Representative name for the entity: Bananas"} - - {literal: "Entity sentiment score: -0."} - - {literal: "Entity sentiment magnitude: 0."} - - {literal: "Language of the text: en"} - - - name: language_entity_sentiment_text - Analyzing Entity Sentiment of a text string (*custom value*) - spec: - # Custom value: "Grapes are actually not very good. But Bananas are great." - - call: - sample: language_entity_sentiment_text - params: - text_content: {literal: "Grapes are actually not very good. But Bananas are great."} - - assert_contains: - - {literal: "Representative name for the entity: Grapes"} - - {literal: "Entity sentiment score: -0."} - - {literal: "Representative name for the entity: Bananas"} - - {literal: "Entity sentiment score: 0."} - - {literal: "Entity sentiment magnitude: 0."} - - {literal: "Language of the text: en"} - - - name: language_entity_sentiment_gcs - Analyzing Entity Sentiment of text file in GCS (default value) - spec: - # Default value: gs://cloud-samples-data/language/entity-sentiment.txt - # => "Grapes are good. Bananas are bad." - - call: {sample: language_entity_sentiment_gcs} - - assert_contains: - - {literal: "Representative name for the entity: Grapes"} - - {literal: "Entity sentiment score: -0."} - - {literal: "Representative name for the entity: Bananas"} - - {literal: "Entity sentiment score: 0."} - - {literal: "Entity sentiment magnitude: 0."} - - {literal: "Language of the text: en"} - - - name: language_entity_sentiment_gcs - Analyzing Entity Sentiment of text file in GCS (*custom value*) - spec: - # Use different file: gs://cloud-samples-data/language/entity-sentiment-reverse.txt - # => "Grapes are actually not very good. But Bananas are great." - - call: - sample: language_entity_sentiment_gcs - params: - gcs_content_uri: - literal: "gs://cloud-samples-data/language/entity-sentiment-reverse.txt" - - assert_contains: - - {literal: "Representative name for the entity: Grapes"} - - {literal: "Entity sentiment score: -0."} - - {literal: "Representative name for the entity: Bananas"} - - {literal: "Entity sentiment score: 0."} - - {literal: "Entity sentiment magnitude: 0."} - - {literal: "Language of the text: en"} diff --git a/samples/v1/test/analyzing_sentiment.test.yaml b/samples/v1/test/analyzing_sentiment.test.yaml deleted file mode 100644 index 55b5fdcb..00000000 --- a/samples/v1/test/analyzing_sentiment.test.yaml +++ /dev/null @@ -1,74 +0,0 @@ -type: test/samples -schema_version: 1 -test: - suites: - - name: "Analyzing Sentiment [code sample tests]" - cases: - - - name: language_sentiment_text - Analyzing the sentiment of a text string (default value) - spec: - # Default value: "I am so happy and joyful." - - call: {sample: language_sentiment_text} - - assert_contains: - - {literal: "Document sentiment score: 0."} - - {literal: "Document sentiment magnitude: 0."} - - {literal: "Sentence text: I am so happy and joyful."} - - {literal: "Sentence sentiment score: 0."} - - {literal: "Sentence sentiment magnitude: 0."} - - {literal: "Language of the text: en"} - # There should be no negative sentiment scores for this value. - - assert_not_contains: - - {literal: "Document sentiment score: -0."} - - {literal: "Sentence sentiment score: -0."} - - - name: language_sentiment_text - Analyzing the sentiment of a text string (*custom value*) - spec: - # Custom value: "I am very happy. I am angry and sad." - - call: - sample: language_sentiment_text - params: - text_content: {literal: "I am very happy. I am angry and sad."} - - assert_contains: - - {literal: "Sentence text: I am very happy"} - - {literal: "Sentence sentiment score: 0."} - - {literal: "Sentence text: I am angry and sad"} - - {literal: "Sentence sentiment score: -0."} - - {literal: "Language of the text: en"} - - - name: language_sentiment_gcs - Analyzing the sentiment of text file in GCS (default value) - spec: - # Default value: gs://cloud-samples-data/language/sentiment-positive.txt - # => "I am so happy and joyful." - - call: {sample: language_sentiment_gcs} - - assert_contains: - - {literal: "Document sentiment score: 0."} - - {literal: "Document sentiment magnitude: 0."} - - {literal: "Sentence text: I am so happy and joyful."} - - {literal: "Sentence sentiment score: 0."} - - {literal: "Sentence sentiment magnitude: 0."} - - {literal: "Language of the text: en"} - # There should be no negative sentiment scores for this value. - - assert_not_contains: - - {literal: "Document sentiment score: -0."} - - {literal: "Sentence sentiment score: -0."} - - - name: language_sentiment_gcs - Analyzing the sentiment of text file in GCS (*custom value*) - spec: - # Use different file: gs://cloud-samples-data/language/sentiment-negative.txt - # => "I am so sad and upset." - - call: - sample: language_sentiment_gcs - params: - gcs_content_uri: - literal: "gs://cloud-samples-data/language/sentiment-negative.txt" - - assert_contains: - - {literal: "Document sentiment score: -0."} - - {literal: "Document sentiment magnitude: 0."} - - {literal: "Sentence text: I am so sad and upset."} - - {literal: "Sentence sentiment score: -0."} - - {literal: "Sentence sentiment magnitude: 0."} - - {literal: "Language of the text: en"} - # There should be no positive sentiment scores for this value. - - assert_not_contains: - - {literal: "Document sentiment score: 0."} - - {literal: "Sentence sentiment score: 0."} diff --git a/samples/v1/test/analyzing_syntax.test.yaml b/samples/v1/test/analyzing_syntax.test.yaml deleted file mode 100644 index e89d465c..00000000 --- a/samples/v1/test/analyzing_syntax.test.yaml +++ /dev/null @@ -1,72 +0,0 @@ -type: test/samples -schema_version: 1 -test: - suites: - - name: "Analyzing Syntax [code sample tests]" - cases: - - - name: language_syntax_text - Analyzing the syntax of a text string (default value) - spec: - # Default value: "This is a short sentence." - - call: {sample: language_syntax_text} - - assert_contains: - - {literal: "Token text: is"} - - {literal: "Part of Speech tag: VERB"} - - {literal: "Tense: PRESENT"} - - {literal: "Lemma: be"} - - {literal: "Token text: short"} - - {literal: "Part of Speech tag: ADJ"} - - {literal: "Lemma: short"} - - {literal: "Language of the text: en"} - - - name: language_syntax_text - Analyzing the syntax of a text string (*custom value*) - spec: - # Custom value: "Alice runs. Bob ran." - - call: - sample: language_syntax_text - params: - text_content: {literal: "Alice runs. Bob ran."} - - assert_contains: - - {literal: "Token text: Alice"} - - {literal: "Location of this token in overall document: 0"} - - {literal: "Part of Speech tag: NOUN"} - - {literal: "Label: NSUBJ"} - - {literal: "Token text: runs"} - - {literal: "Part of Speech tag: VERB"} - - {literal: "Tense: PRESENT"} - - {literal: "Lemma: run"} - - {literal: "Token text: ran"} - - {literal: "Tense: PAST"} - - {literal: "Language of the text: en"} - - - name: language_syntax_gcs - Analyzing the syntax of text file in GCS (default value) - spec: - # Default value: gs://cloud-samples-data/language/syntax-sentence.txt - # => "This is a short sentence." - - call: {sample: language_syntax_gcs} - - assert_contains: - - {literal: "Token text: is"} - - {literal: "Part of Speech tag: VERB"} - - {literal: "Tense: PRESENT"} - - {literal: "Lemma: be"} - - {literal: "Token text: short"} - - {literal: "Part of Speech tag: ADJ"} - - {literal: "Lemma: short"} - - {literal: "Language of the text: en"} - - - name: language_syntax_gcs - Analyzing the syntax of text file in GCS (*custom value*) - spec: - # Use different file: gs://cloud-samples-data/language/hello.txt - # => "Hello, world!" - - call: - sample: language_syntax_gcs - params: - gcs_content_uri: - literal: "gs://cloud-samples-data/language/hello.txt" - - assert_contains: - - {literal: "Token text: Hello"} - - {literal: "Token text: World"} - - {literal: "Part of Speech tag: NOUN"} - - {literal: "Token text: !"} - - {literal: "Part of Speech tag: PUNCT"} - - {literal: "Language of the text: en"} diff --git a/samples/v1/test/classifying_content.test.yaml b/samples/v1/test/classifying_content.test.yaml deleted file mode 100644 index 4b5f121d..00000000 --- a/samples/v1/test/classifying_content.test.yaml +++ /dev/null @@ -1,51 +0,0 @@ -type: test/samples -schema_version: 1 -test: - suites: - - name: "Classifying Content [code sample tests]" - cases: - - - name: language_classify_text - Classifying Content of a text string (default value) - spec: - # Default value: "That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows." - - call: {sample: language_classify_text} - - assert_contains_any: - - {literal: "TV"} - - {literal: "Movies"} - - {literal: "Entertainment"} - - - name: language_classify_text - Classifying Content of a text string (*custom value*) - spec: - # Custom value: "Dungeons and dragons and loot, oh my!" - - call: - sample: language_classify_text - params: - text_content: {literal: "Dungeons and dragons and loot, oh my!"} - - assert_contains_any: - - {literal: "Games"} - - {literal: "Roleplaying"} - - {literal: "Computer"} - - - name: language_classify_gcs - Classifying Content of text file in GCS (default value) - spec: - # Default value: gs://cloud-samples-data/language/classify-entertainment.txt - # => "This is about film and movies and television and acting and movie theatres and theatre and drama and entertainment and the arts." - - call: {sample: language_classify_gcs} - - assert_contains_any: - - {literal: "TV"} - - {literal: "Movies"} - - {literal: "Entertainment"} - - - name: language_classify_gcs - Classifying Content of text file in GCS (*custom value*) - spec: - # Use different file: gs://cloud-samples-data/language/android.txt - # => "Android is a mobile operating system developed by Google, based on the Linux kernel and..." - - call: - sample: language_classify_gcs - params: - gcs_content_uri: - literal: "gs://cloud-samples-data/language/android.txt" - - assert_contains_any: - - {literal: "Mobile"} - - {literal: "Phone"} - - {literal: "Internet"} diff --git a/samples/v1/test/samples.manifest.yaml b/samples/v1/test/samples.manifest.yaml deleted file mode 100644 index aa270425..00000000 --- a/samples/v1/test/samples.manifest.yaml +++ /dev/null @@ -1,38 +0,0 @@ -type: manifest/samples -schema_version: 3 -base: &common - env: 'python' - bin: 'python3' - chdir: '{@manifest_dir}/../..' - basepath: '.' -samples: -- <<: *common - path: '{basepath}/v1/language_classify_gcs.py' - sample: 'language_classify_gcs' -- <<: *common - path: '{basepath}/v1/language_classify_text.py' - sample: 'language_classify_text' -- <<: *common - path: '{basepath}/v1/language_entities_gcs.py' - sample: 'language_entities_gcs' -- <<: *common - path: '{basepath}/v1/language_entities_text.py' - sample: 'language_entities_text' -- <<: *common - path: '{basepath}/v1/language_entity_sentiment_gcs.py' - sample: 'language_entity_sentiment_gcs' -- <<: *common - path: '{basepath}/v1/language_entity_sentiment_text.py' - sample: 'language_entity_sentiment_text' -- <<: *common - path: '{basepath}/v1/language_sentiment_gcs.py' - sample: 'language_sentiment_gcs' -- <<: *common - path: '{basepath}/v1/language_sentiment_text.py' - sample: 'language_sentiment_text' -- <<: *common - path: '{basepath}/v1/language_syntax_gcs.py' - sample: 'language_syntax_gcs' -- <<: *common - path: '{basepath}/v1/language_syntax_text.py' - sample: 'language_syntax_text' From fa4547f61179b9e8a4065bdd0a2bd7760b033985 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 8 Dec 2022 07:30:40 -0800 Subject: [PATCH 227/254] fix(deps): Require google-api-core >=1.34.0, >=2.11.0 (#409) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(deps): Require google-api-core >=1.34.0, >=2.11.0 fix: Drop usage of pkg_resources fix: Fix timeout default values docs(samples): Snippetgen should call await on the operation coroutine before calling result PiperOrigin-RevId: 493260409 Source-Link: https://github.com/googleapis/googleapis/commit/fea43879f83a8d0dacc9353b3f75f8f46d37162f Source-Link: https://github.com/googleapis/googleapis-gen/commit/387b7344c7529ee44be84e613b19a820508c612b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMzg3YjczNDRjNzUyOWVlNDRiZTg0ZTYxM2IxOWE4MjA1MDhjNjEyYiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * add gapic_version.py Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .coveragerc | 5 ---- google/cloud/language_v1/gapic_version.py | 16 ++++++++++++ .../services/language_service/async_client.py | 26 ++++++++----------- .../services/language_service/client.py | 26 ++++++++----------- .../language_service/transports/base.py | 13 +++------- .../cloud/language_v1beta2/gapic_version.py | 16 ++++++++++++ .../services/language_service/async_client.py | 26 ++++++++----------- .../services/language_service/client.py | 26 ++++++++----------- .../language_service/transports/base.py | 13 +++------- release-please-config.json | 2 ++ setup.py | 2 +- testing/constraints-3.7.txt | 2 +- 12 files changed, 88 insertions(+), 85 deletions(-) create mode 100644 google/cloud/language_v1/gapic_version.py create mode 100644 google/cloud/language_v1beta2/gapic_version.py diff --git a/.coveragerc b/.coveragerc index a2e29fbf..4a9db2a6 100644 --- a/.coveragerc +++ b/.coveragerc @@ -10,8 +10,3 @@ exclude_lines = pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py new file mode 100644 index 00000000..e253e532 --- /dev/null +++ b/google/cloud/language_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +__version__ = "2.6.1" # {x-release-please-version} diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 9793a2dd..8a60c525 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -34,7 +34,8 @@ from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -import pkg_resources + +from google.cloud.language_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -219,7 +220,7 @@ async def analyze_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -336,7 +337,7 @@ async def analyze_entities( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -455,7 +456,7 @@ async def analyze_entity_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -575,7 +576,7 @@ async def analyze_syntax( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -690,7 +691,7 @@ async def classify_text( *, document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -799,7 +800,7 @@ async def annotate_text( features: Optional[language_service.AnnotateTextRequest.Features] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all the features @@ -926,14 +927,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-language", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("LanguageServiceAsyncClient",) diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 05873cce..31add17c 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -38,7 +38,8 @@ from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.oauth2 import service_account # type: ignore -import pkg_resources + +from google.cloud.language_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -426,7 +427,7 @@ def analyze_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -533,7 +534,7 @@ def analyze_entities( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -642,7 +643,7 @@ def analyze_entity_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -752,7 +753,7 @@ def analyze_syntax( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -857,7 +858,7 @@ def classify_text( *, document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -956,7 +957,7 @@ def annotate_text( features: Optional[language_service.AnnotateTextRequest.Features] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all the features @@ -1080,14 +1081,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-language", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("LanguageServiceClient",) diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index f3b088b0..d8bfc5d9 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -23,18 +23,13 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -import pkg_resources +from google.cloud.language_v1 import gapic_version as package_version from google.cloud.language_v1.types import language_service -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-language", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class LanguageServiceTransport(abc.ABC): diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py new file mode 100644 index 00000000..e253e532 --- /dev/null +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +__version__ = "2.6.1" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index e3f79792..44ab65dd 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -34,7 +34,8 @@ from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -import pkg_resources + +from google.cloud.language_v1beta2 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -219,7 +220,7 @@ async def analyze_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -337,7 +338,7 @@ async def analyze_entities( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -456,7 +457,7 @@ async def analyze_entity_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -576,7 +577,7 @@ async def analyze_syntax( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -691,7 +692,7 @@ async def classify_text( *, document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -800,7 +801,7 @@ async def annotate_text( features: Optional[language_service.AnnotateTextRequest.Features] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all syntax, @@ -927,14 +928,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-language", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("LanguageServiceAsyncClient",) diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 07405a6f..6ba083ec 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -38,7 +38,8 @@ from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.oauth2 import service_account # type: ignore -import pkg_resources + +from google.cloud.language_v1beta2 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -426,7 +427,7 @@ def analyze_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSentimentResponse: r"""Analyzes the sentiment of the provided text. @@ -534,7 +535,7 @@ def analyze_entities( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitiesResponse: r"""Finds named entities (currently proper names and @@ -643,7 +644,7 @@ def analyze_entity_sentiment( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeEntitySentimentResponse: r"""Finds entities, similar to @@ -753,7 +754,7 @@ def analyze_syntax( document: Optional[language_service.Document] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnalyzeSyntaxResponse: r"""Analyzes the syntax of the text and provides sentence @@ -858,7 +859,7 @@ def classify_text( *, document: Optional[language_service.Document] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.ClassifyTextResponse: r"""Classifies a document into categories. @@ -957,7 +958,7 @@ def annotate_text( features: Optional[language_service.AnnotateTextRequest.Features] = None, encoding_type: Optional[language_service.EncodingType] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> language_service.AnnotateTextResponse: r"""A convenience method that provides all syntax, @@ -1081,14 +1082,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-language", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("LanguageServiceClient",) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 3877d81b..5204e4c9 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -23,18 +23,13 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -import pkg_resources +from google.cloud.language_v1beta2 import gapic_version as package_version from google.cloud.language_v1beta2.types import language_service -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-language", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class LanguageServiceTransport(abc.ABC): diff --git a/release-please-config.json b/release-please-config.json index cd455f82..e623c390 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -5,6 +5,8 @@ "release-type": "python", "extra-files": [ "google/cloud/language/gapic_version.py", + "google/cloud/language_v1beta2/gapic_version.py", + "google/cloud/language_v1/gapic_version.py", { "type": "json", "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1.json", diff --git a/setup.py b/setup.py index d24aa357..e8969d28 100644 --- a/setup.py +++ b/setup.py @@ -36,7 +36,7 @@ release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", "proto-plus >= 1.22.0, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 6f3158cc..6c44adfe 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -4,6 +4,6 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.33.2 +google-api-core==1.34.0 proto-plus==1.22.0 protobuf==3.19.5 From 60bde446f327b3585537f1468796db2e3944f6c8 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 13 Dec 2022 12:46:44 -0500 Subject: [PATCH 228/254] build(deps): bump certifi from 2022.9.24 to 2022.12.7 [autoapprove] (#411) * build(deps): bump certifi from 2022.9.24 to 2022.12.7 in /synthtool/gcp/templates/python_library/.kokoro Source-Link: https://github.com/googleapis/synthtool/commit/b4fe62efb5114b6738ad4b13d6f654f2bf4b7cc0 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:3bf87e47c2173d7eed42714589dc4da2c07c3268610f1e47f8e1a30decbfc7f1 * trigger ci Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 3 ++- .kokoro/requirements.txt | 6 +++--- .pre-commit-config.yaml | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index bb21147e..df2cfe5d 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:3abfa0f1886adaf0b83f07cb117b24a639ea1cb9cffe56d43280b977033563eb + digest: sha256:3bf87e47c2173d7eed42714589dc4da2c07c3268610f1e47f8e1a30decbfc7f1 + diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 9c1b9be3..05dc4672 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -20,9 +20,9 @@ cachetools==5.2.0 \ --hash=sha256:6a94c6402995a99c3970cc7e4884bb60b4a8639938157eeed436098bf9831757 \ --hash=sha256:f9f17d2aec496a9aa6b76f53e3b614c965223c061982d434d160f930c698a9db # via google-auth -certifi==2022.9.24 \ - --hash=sha256:0d9c601124e5a6ba9712dbc60d9c53c21e34f5f641fe83002317394311bdce14 \ - --hash=sha256:90c1a32f1d68f940488354e36370f6cca89f0f106db09518524c88d6ed83f382 +certifi==2022.12.7 \ + --hash=sha256:35824b4c3a97115964b408844d64aa14db1cc518f6562e8d7261699d1350a9e3 \ + --hash=sha256:4ad3232f5e926d6718ec31cfc1fcadfde020920e278684144551c91769c7bc18 # via requests cffi==1.15.1 \ --hash=sha256:00a9ed42e88df81ffae7a8ab6d9356b371399b91dbdf0c3cb1e84c03a13aceb5 \ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 46d23716..5405cc8f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -25,7 +25,7 @@ repos: rev: 22.3.0 hooks: - id: black -- repo: https://gitlab.com/pycqa/flake8 +- repo: https://github.com/pycqa/flake8 rev: 3.9.2 hooks: - id: flake8 From 686eac1d9a85fc532037b33e10581f0654c534fd Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 15 Dec 2022 12:02:17 -0500 Subject: [PATCH 229/254] chore(main): release 2.7.0 (#394) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 28 +++++++++++++++++++ google/cloud/language/gapic_version.py | 2 +- google/cloud/language_v1/gapic_version.py | 2 +- .../cloud/language_v1beta2/gapic_version.py | 2 +- ...pet_metadata_google.cloud.language.v1.json | 2 +- ...etadata_google.cloud.language.v1beta2.json | 2 +- 7 files changed, 34 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cb7c2b22..7afadd5e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.6.1" + ".": "2.7.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 030ec01e..03e1da9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,34 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.7.0](https://github.com/googleapis/python-language/compare/v2.6.1...v2.7.0) (2022-12-14) + + +### Features + +* Add support for `google.cloud.language.__version__` ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) +* Add typing to proto.Message based class attributes ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) + + +### Bug Fixes + +* Add dict typing for client_options ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) +* **deps:** Require google-api-core >=1.34.0, >=2.11.0 ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) +* Drop usage of pkg_resources ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) +* Fix timeout default values ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) + + +### Miscellaneous Chores + +* Release-please updates snippet metadata ([cb52907](https://github.com/googleapis/python-language/commit/cb5290723a1f13d6ea3929cdf2fce103ee464910)) + + +### Documentation + +* **samples:** Snippetgen handling of repeated enum field ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) +* **samples:** Snippetgen should call await on the operation coroutine before calling result ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) +* Specify client library version requirement in samples/v1/language_classify_text.py ([#388](https://github.com/googleapis/python-language/issues/388)) ([bff4a65](https://github.com/googleapis/python-language/commit/bff4a65b6a3bb28bf205cdc2fcf5ad914665c453)) + ## [2.6.1](https://github.com/googleapis/python-language/compare/v2.6.0...v2.6.1) (2022-10-10) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index e253e532..8d17333c 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.6.1" # {x-release-please-version} +__version__ = "2.7.0" # {x-release-please-version} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py index e253e532..8d17333c 100644 --- a/google/cloud/language_v1/gapic_version.py +++ b/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.6.1" # {x-release-please-version} +__version__ = "2.7.0" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py index e253e532..8d17333c 100644 --- a/google/cloud/language_v1beta2/gapic_version.py +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.6.1" # {x-release-please-version} +__version__ = "2.7.0" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 936a8b70..bc675ca4 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.7.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index a4368f2d..16e3f95f 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.7.0" }, "snippets": [ { From 9310f8485a4b09aa43c034feca9f25a0616b4485 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 6 Jan 2023 11:48:16 +0000 Subject: [PATCH 230/254] chore(python): add support for python 3.11 [autoapprove] (#412) Source-Link: https://togithub.com/googleapis/synthtool/commit/7197a001ffb6d8ce7b0b9b11c280f0c536c1033a Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 --- .github/.OwlBot.lock.yaml | 5 +-- .github/workflows/unittest.yml | 2 +- .kokoro/samples/python3.11/common.cfg | 40 ++++++++++++++++++++ .kokoro/samples/python3.11/continuous.cfg | 6 +++ .kokoro/samples/python3.11/periodic-head.cfg | 11 ++++++ .kokoro/samples/python3.11/periodic.cfg | 6 +++ .kokoro/samples/python3.11/presubmit.cfg | 6 +++ CONTRIBUTING.rst | 6 ++- noxfile.py | 2 +- 9 files changed, 77 insertions(+), 7 deletions(-) create mode 100644 .kokoro/samples/python3.11/common.cfg create mode 100644 .kokoro/samples/python3.11/continuous.cfg create mode 100644 .kokoro/samples/python3.11/periodic-head.cfg create mode 100644 .kokoro/samples/python3.11/periodic.cfg create mode 100644 .kokoro/samples/python3.11/presubmit.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index df2cfe5d..889f77df 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,4 @@ -# Copyright 2022 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:3bf87e47c2173d7eed42714589dc4da2c07c3268610f1e47f8e1a30decbfc7f1 - + digest: sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 23000c05..8057a769 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python: ['3.7', '3.8', '3.9', '3.10'] + python: ['3.7', '3.8', '3.9', '3.10', '3.11'] steps: - name: Checkout uses: actions/checkout@v3 diff --git a/.kokoro/samples/python3.11/common.cfg b/.kokoro/samples/python3.11/common.cfg new file mode 100644 index 00000000..568a26d0 --- /dev/null +++ b/.kokoro/samples/python3.11/common.cfg @@ -0,0 +1,40 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Specify which tests to run +env_vars: { + key: "RUN_TESTS_SESSION" + value: "py-3.11" +} + +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-311" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-language/.kokoro/test-samples.sh" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" +} + +# Download secrets for samples +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.11/continuous.cfg b/.kokoro/samples/python3.11/continuous.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.11/continuous.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.11/periodic-head.cfg b/.kokoro/samples/python3.11/periodic-head.cfg new file mode 100644 index 00000000..676f8aa8 --- /dev/null +++ b/.kokoro/samples/python3.11/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-language/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.11/periodic.cfg b/.kokoro/samples/python3.11/periodic.cfg new file mode 100644 index 00000000..71cd1e59 --- /dev/null +++ b/.kokoro/samples/python3.11/periodic.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "False" +} diff --git a/.kokoro/samples/python3.11/presubmit.cfg b/.kokoro/samples/python3.11/presubmit.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.11/presubmit.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index b200f77f..15e49507 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9 and 3.10 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10 and 3.11 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox <https://nox.readthedocs.io/en/latest/>`__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.10 -- -k <name of test> + $ nox -s unit-3.11 -- -k <name of test> .. note:: @@ -225,11 +225,13 @@ We support: - `Python 3.8`_ - `Python 3.9`_ - `Python 3.10`_ +- `Python 3.11`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ .. _Python 3.9: https://docs.python.org/3.9/ .. _Python 3.10: https://docs.python.org/3.10/ +.. _Python 3.11: https://docs.python.org/3.11/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/noxfile.py b/noxfile.py index d8440c02..e716318b 100644 --- a/noxfile.py +++ b/noxfile.py @@ -32,7 +32,7 @@ DEFAULT_PYTHON_VERSION = "3.8" -UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] +UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", From c156e1e67a3430d55664e3abad27951d4af07daf Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 22:48:27 -0500 Subject: [PATCH 231/254] feat: Add support for python 3.11 (#413) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Add support for python 3.11 chore: Update gapic-generator-python to v1.8.0 PiperOrigin-RevId: 500768693 Source-Link: https://github.com/googleapis/googleapis/commit/190b612e3d0ff8f025875a669e5d68a1446d43c1 Source-Link: https://github.com/googleapis/googleapis-gen/commit/7bf29a414b9ecac3170f0b65bdc2a95705c0ef1a Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiN2JmMjlhNDE0YjllY2FjMzE3MGYwYjY1YmRjMmE5NTcwNWMwZWYxYSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../language_v1/services/language_service/async_client.py | 2 +- .../cloud/language_v1/services/language_service/client.py | 2 +- .../services/language_service/async_client.py | 2 +- .../language_v1beta2/services/language_service/client.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- setup.py | 2 ++ testing/constraints-3.12.txt | 6 ++++++ 8 files changed, 14 insertions(+), 6 deletions(-) create mode 100644 testing/constraints-3.12.txt diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 8a60c525..605df5b5 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -133,7 +133,7 @@ def get_mtls_endpoint_and_cert_source( The API endpoint is determined in the following order: (1) if `client_options.api_endpoint` if provided, use the provided one. (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API + default mTLS endpoint; if the environment variable is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 31add17c..a5cc38d1 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -269,7 +269,7 @@ def get_mtls_endpoint_and_cert_source( The API endpoint is determined in the following order: (1) if `client_options.api_endpoint` if provided, use the provided one. (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API + default mTLS endpoint; if the environment variable is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 44ab65dd..d242f8df 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -133,7 +133,7 @@ def get_mtls_endpoint_and_cert_source( The API endpoint is determined in the following order: (1) if `client_options.api_endpoint` if provided, use the provided one. (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API + default mTLS endpoint; if the environment variable is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 6ba083ec..3b46e9bd 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -269,7 +269,7 @@ def get_mtls_endpoint_and_cert_source( The API endpoint is determined in the following order: (1) if `client_options.api_endpoint` if provided, use the provided one. (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API + default mTLS endpoint; if the environment variable is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index bc675ca4..936a8b70 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.7.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index 16e3f95f..a4368f2d 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.7.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/setup.py b/setup.py index e8969d28..5a29f742 100644 --- a/setup.py +++ b/setup.py @@ -38,6 +38,7 @@ dependencies = [ "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] url = "https://github.com/googleapis/python-language" @@ -77,6 +78,7 @@ "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", "Operating System :: OS Independent", "Topic :: Internet", ], diff --git a/testing/constraints-3.12.txt b/testing/constraints-3.12.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf From 4821d70a453aa24bdc0e6595e98c663777e41ada Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Tue, 10 Jan 2023 14:02:21 -0500 Subject: [PATCH 232/254] chore(main): release 2.8.0 (#414) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ google/cloud/language/gapic_version.py | 2 +- google/cloud/language_v1/gapic_version.py | 2 +- google/cloud/language_v1beta2/gapic_version.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- 7 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7afadd5e..8388fe10 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.7.0" + ".": "2.8.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 03e1da9e..711c0394 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.8.0](https://github.com/googleapis/python-language/compare/v2.7.0...v2.8.0) (2023-01-10) + + +### Features + +* Add support for python 3.11 ([#413](https://github.com/googleapis/python-language/issues/413)) ([c156e1e](https://github.com/googleapis/python-language/commit/c156e1e67a3430d55664e3abad27951d4af07daf)) + ## [2.7.0](https://github.com/googleapis/python-language/compare/v2.6.1...v2.7.0) (2022-12-14) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index 8d17333c..e248a9ca 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.7.0" # {x-release-please-version} +__version__ = "2.8.0" # {x-release-please-version} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py index 8d17333c..e248a9ca 100644 --- a/google/cloud/language_v1/gapic_version.py +++ b/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.7.0" # {x-release-please-version} +__version__ = "2.8.0" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py index 8d17333c..e248a9ca 100644 --- a/google/cloud/language_v1beta2/gapic_version.py +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.7.0" # {x-release-please-version} +__version__ = "2.8.0" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 936a8b70..ca7dff9f 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.8.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index a4368f2d..a3527b53 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.8.0" }, "snippets": [ { From a26c418a54cb26825c9c539282ed37cb9d9eac0c Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 20 Jan 2023 13:52:04 -0500 Subject: [PATCH 233/254] docs: Add documentation for enums (#415) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: Add documentation for enums fix: Add context manager return types chore: Update gapic-generator-python to v1.8.1 PiperOrigin-RevId: 503210727 Source-Link: https://github.com/googleapis/googleapis/commit/a391fd1dac18dfdfa00c18c8404f2c3a6ff8e98e Source-Link: https://github.com/googleapis/googleapis-gen/commit/0080f830dec37c3384157082bce279e37079ea58 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMDA4MGY4MzBkZWMzN2MzMzg0MTU3MDgyYmNlMjc5ZTM3MDc5ZWE1OCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../services/language_service/client.py | 2 +- .../language_v1/types/language_service.py | 509 ++++++++++++++++- .../services/language_service/client.py | 2 +- .../types/language_service.py | 522 +++++++++++++++++- ...pet_metadata_google.cloud.language.v1.json | 2 +- ...etadata_google.cloud.language.v1beta2.json | 2 +- 6 files changed, 1016 insertions(+), 23 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index a5cc38d1..276e9489 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -1067,7 +1067,7 @@ def sample_annotate_text(): # Done; return the response. return response - def __enter__(self): + def __enter__(self) -> "LanguageServiceClient": return self def __exit__(self, type, value, traceback): diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 5e6fb4cb..6eb54e90 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -54,6 +54,27 @@ class EncodingType(proto.Enum): provides the beginning offsets for various outputs, such as tokens and mentions, and languages that natively use different text encodings may access offsets differently. + + Values: + NONE (0): + If ``EncodingType`` is not specified, encoding-dependent + information (such as ``begin_offset``) will be set at + ``-1``. + UTF8 (1): + Encoding-dependent information (such as ``begin_offset``) is + calculated based on the UTF-8 encoding of the input. C++ and + Go are examples of languages that use this encoding + natively. + UTF16 (2): + Encoding-dependent information (such as ``begin_offset``) is + calculated based on the UTF-16 encoding of the input. Java + and JavaScript are examples of languages that use this + encoding natively. + UTF32 (3): + Encoding-dependent information (such as ``begin_offset``) is + calculated based on the UTF-32 encoding of the input. Python + is an example of a language that uses this encoding + natively. """ NONE = 0 UTF8 = 1 @@ -101,7 +122,16 @@ class Document(proto.Message): """ class Type(proto.Enum): - r"""The document types enum.""" + r"""The document types enum. + + Values: + TYPE_UNSPECIFIED (0): + The content type is not specified. + PLAIN_TEXT (1): + Plain text + HTML (2): + HTML + """ TYPE_UNSPECIFIED = 0 PLAIN_TEXT = 1 HTML = 2 @@ -194,6 +224,69 @@ class Type(proto.Enum): metadata is a Wikipedia URL (``wikipedia_url``) and Knowledge Graph MID (``mid``). The table below lists the associated fields for entities that have different metadata. + + Values: + UNKNOWN (0): + Unknown + PERSON (1): + Person + LOCATION (2): + Location + ORGANIZATION (3): + Organization + EVENT (4): + Event + WORK_OF_ART (5): + Artwork + CONSUMER_GOOD (6): + Consumer product + OTHER (7): + Other types of entities + PHONE_NUMBER (9): + Phone number + + The metadata lists the phone number, formatted according to + local convention, plus whichever additional elements appear + in the text: + + - ``number`` - the actual number, broken down into sections + as per local convention + - ``national_prefix`` - country code, if detected + - ``area_code`` - region or area code, if detected + - ``extension`` - phone extension (to be dialed after + connection), if detected + ADDRESS (10): + Address + + The metadata identifies the street number and locality plus + whichever additional elements appear in the text: + + - ``street_number`` - street number + - ``locality`` - city or town + - ``street_name`` - street/route name, if detected + - ``postal_code`` - postal code, if detected + - ``country`` - country, if detected< + - ``broad_region`` - administrative area, such as the + state, if detected + - ``narrow_region`` - smaller administrative area, such as + county, if detected + - ``sublocality`` - used in Asian addresses to demark a + district within a city, if detected + DATE (11): + Date + + The metadata identifies the components of the date: + + - ``year`` - four digit year, if detected + - ``month`` - two digit month number, if detected + - ``day`` - two digit day number, if detected + NUMBER (12): + Number + The metadata is the number itself. + PRICE (13): + Price + + The metadata identifies the ``value`` and ``currency``. """ UNKNOWN = 0 PERSON = 1 @@ -332,7 +425,38 @@ class PartOfSpeech(proto.Message): """ class Tag(proto.Enum): - r"""The part of speech tags enum.""" + r"""The part of speech tags enum. + + Values: + UNKNOWN (0): + Unknown + ADJ (1): + Adjective + ADP (2): + Adposition (preposition and postposition) + ADV (3): + Adverb + CONJ (4): + Conjunction + DET (5): + Determiner + NOUN (6): + Noun (common and proper) + NUM (7): + Cardinal number + PRON (8): + Pronoun + PRT (9): + Particle or other function word + PUNCT (10): + Punctuation + VERB (11): + Verb (all tenses and modes) + X (12): + Other: foreign words, typos, abbreviations + AFFIX (13): + Affix + """ UNKNOWN = 0 ADJ = 1 ADP = 2 @@ -351,6 +475,17 @@ class Tag(proto.Enum): class Aspect(proto.Enum): r"""The characteristic of a verb that expresses time flow during an event. + + Values: + ASPECT_UNKNOWN (0): + Aspect is not applicable in the analyzed + language or is not predicted. + PERFECTIVE (1): + Perfective + IMPERFECTIVE (2): + Imperfective + PROGRESSIVE (3): + Progressive """ ASPECT_UNKNOWN = 0 PERFECTIVE = 1 @@ -362,6 +497,39 @@ class Case(proto.Enum): phrase, clause, or sentence. In some languages, other parts of speech, such as adjective and determiner, take case inflection in agreement with the noun. + + Values: + CASE_UNKNOWN (0): + Case is not applicable in the analyzed + language or is not predicted. + ACCUSATIVE (1): + Accusative + ADVERBIAL (2): + Adverbial + COMPLEMENTIVE (3): + Complementive + DATIVE (4): + Dative + GENITIVE (5): + Genitive + INSTRUMENTAL (6): + Instrumental + LOCATIVE (7): + Locative + NOMINATIVE (8): + Nominative + OBLIQUE (9): + Oblique + PARTITIVE (10): + Partitive + PREPOSITIONAL (11): + Prepositional + REFLEXIVE_CASE (12): + Reflexive + RELATIVE_CASE (13): + Relative + VOCATIVE (14): + Vocative """ CASE_UNKNOWN = 0 ACCUSATIVE = 1 @@ -385,6 +553,33 @@ class Form(proto.Enum): categorizing inflected endings of verbs and adjectives or distinguishing between short and long forms of adjectives and participles + + Values: + FORM_UNKNOWN (0): + Form is not applicable in the analyzed + language or is not predicted. + ADNOMIAL (1): + Adnomial + AUXILIARY (2): + Auxiliary + COMPLEMENTIZER (3): + Complementizer + FINAL_ENDING (4): + Final ending + GERUND (5): + Gerund + REALIS (6): + Realis + IRREALIS (7): + Irrealis + SHORT (8): + Short form + LONG (9): + Long form + ORDER (10): + Order form + SPECIFIC (11): + Specific form """ FORM_UNKNOWN = 0 ADNOMIAL = 1 @@ -402,6 +597,17 @@ class Form(proto.Enum): class Gender(proto.Enum): r"""Gender classes of nouns reflected in the behaviour of associated words. + + Values: + GENDER_UNKNOWN (0): + Gender is not applicable in the analyzed + language or is not predicted. + FEMININE (1): + Feminine + MASCULINE (2): + Masculine + NEUTER (3): + Neuter """ GENDER_UNKNOWN = 0 FEMININE = 1 @@ -411,6 +617,23 @@ class Gender(proto.Enum): class Mood(proto.Enum): r"""The grammatical feature of verbs, used for showing modality and attitude. + + Values: + MOOD_UNKNOWN (0): + Mood is not applicable in the analyzed + language or is not predicted. + CONDITIONAL_MOOD (1): + Conditional + IMPERATIVE (2): + Imperative + INDICATIVE (3): + Indicative + INTERROGATIVE (4): + Interrogative + JUSSIVE (5): + Jussive + SUBJUNCTIVE (6): + Subjunctive """ MOOD_UNKNOWN = 0 CONDITIONAL_MOOD = 1 @@ -421,7 +644,19 @@ class Mood(proto.Enum): SUBJUNCTIVE = 6 class Number(proto.Enum): - r"""Count distinctions.""" + r"""Count distinctions. + + Values: + NUMBER_UNKNOWN (0): + Number is not applicable in the analyzed + language or is not predicted. + SINGULAR (1): + Singular + PLURAL (2): + Plural + DUAL (3): + Dual + """ NUMBER_UNKNOWN = 0 SINGULAR = 1 PLURAL = 2 @@ -430,6 +665,19 @@ class Number(proto.Enum): class Person(proto.Enum): r"""The distinction between the speaker, second person, third person, etc. + + Values: + PERSON_UNKNOWN (0): + Person is not applicable in the analyzed + language or is not predicted. + FIRST (1): + First + SECOND (2): + Second + THIRD (3): + Third + REFLEXIVE_PERSON (4): + Reflexive """ PERSON_UNKNOWN = 0 FIRST = 1 @@ -438,19 +686,57 @@ class Person(proto.Enum): REFLEXIVE_PERSON = 4 class Proper(proto.Enum): - r"""This category shows if the token is part of a proper name.""" + r"""This category shows if the token is part of a proper name. + + Values: + PROPER_UNKNOWN (0): + Proper is not applicable in the analyzed + language or is not predicted. + PROPER (1): + Proper + NOT_PROPER (2): + Not proper + """ PROPER_UNKNOWN = 0 PROPER = 1 NOT_PROPER = 2 class Reciprocity(proto.Enum): - r"""Reciprocal features of a pronoun.""" + r"""Reciprocal features of a pronoun. + + Values: + RECIPROCITY_UNKNOWN (0): + Reciprocity is not applicable in the analyzed + language or is not predicted. + RECIPROCAL (1): + Reciprocal + NON_RECIPROCAL (2): + Non-reciprocal + """ RECIPROCITY_UNKNOWN = 0 RECIPROCAL = 1 NON_RECIPROCAL = 2 class Tense(proto.Enum): - r"""Time reference.""" + r"""Time reference. + + Values: + TENSE_UNKNOWN (0): + Tense is not applicable in the analyzed + language or is not predicted. + CONDITIONAL_TENSE (1): + Conditional + FUTURE (2): + Future + PAST (3): + Past + PRESENT (4): + Present + IMPERFECT (5): + Imperfect + PLUPERFECT (6): + Pluperfect + """ TENSE_UNKNOWN = 0 CONDITIONAL_TENSE = 1 FUTURE = 2 @@ -462,6 +748,17 @@ class Tense(proto.Enum): class Voice(proto.Enum): r"""The relationship between the action that a verb expresses and the participants identified by its arguments. + + Values: + VOICE_UNKNOWN (0): + Voice is not applicable in the analyzed + language or is not predicted. + ACTIVE (1): + Active + CAUSATIVE (2): + Causative + PASSIVE (3): + Passive """ VOICE_UNKNOWN = 0 ACTIVE = 1 @@ -548,7 +845,181 @@ class DependencyEdge(proto.Message): """ class Label(proto.Enum): - r"""The parse label enum for the token.""" + r"""The parse label enum for the token. + + Values: + UNKNOWN (0): + Unknown + ABBREV (1): + Abbreviation modifier + ACOMP (2): + Adjectival complement + ADVCL (3): + Adverbial clause modifier + ADVMOD (4): + Adverbial modifier + AMOD (5): + Adjectival modifier of an NP + APPOS (6): + Appositional modifier of an NP + ATTR (7): + Attribute dependent of a copular verb + AUX (8): + Auxiliary (non-main) verb + AUXPASS (9): + Passive auxiliary + CC (10): + Coordinating conjunction + CCOMP (11): + Clausal complement of a verb or adjective + CONJ (12): + Conjunct + CSUBJ (13): + Clausal subject + CSUBJPASS (14): + Clausal passive subject + DEP (15): + Dependency (unable to determine) + DET (16): + Determiner + DISCOURSE (17): + Discourse + DOBJ (18): + Direct object + EXPL (19): + Expletive + GOESWITH (20): + Goes with (part of a word in a text not well + edited) + IOBJ (21): + Indirect object + MARK (22): + Marker (word introducing a subordinate + clause) + MWE (23): + Multi-word expression + MWV (24): + Multi-word verbal expression + NEG (25): + Negation modifier + NN (26): + Noun compound modifier + NPADVMOD (27): + Noun phrase used as an adverbial modifier + NSUBJ (28): + Nominal subject + NSUBJPASS (29): + Passive nominal subject + NUM (30): + Numeric modifier of a noun + NUMBER (31): + Element of compound number + P (32): + Punctuation mark + PARATAXIS (33): + Parataxis relation + PARTMOD (34): + Participial modifier + PCOMP (35): + The complement of a preposition is a clause + POBJ (36): + Object of a preposition + POSS (37): + Possession modifier + POSTNEG (38): + Postverbal negative particle + PRECOMP (39): + Predicate complement + PRECONJ (40): + Preconjunt + PREDET (41): + Predeterminer + PREF (42): + Prefix + PREP (43): + Prepositional modifier + PRONL (44): + The relationship between a verb and verbal + morpheme + PRT (45): + Particle + PS (46): + Associative or possessive marker + QUANTMOD (47): + Quantifier phrase modifier + RCMOD (48): + Relative clause modifier + RCMODREL (49): + Complementizer in relative clause + RDROP (50): + Ellipsis without a preceding predicate + REF (51): + Referent + REMNANT (52): + Remnant + REPARANDUM (53): + Reparandum + ROOT (54): + Root + SNUM (55): + Suffix specifying a unit of number + SUFF (56): + Suffix + TMOD (57): + Temporal modifier + TOPIC (58): + Topic marker + VMOD (59): + Clause headed by an infinite form of the verb + that modifies a noun + VOCATIVE (60): + Vocative + XCOMP (61): + Open clausal complement + SUFFIX (62): + Name suffix + TITLE (63): + Name title + ADVPHMOD (64): + Adverbial phrase modifier + AUXCAUS (65): + Causative auxiliary + AUXVV (66): + Helper auxiliary + DTMOD (67): + Rentaishi (Prenominal modifier) + FOREIGN (68): + Foreign words + KW (69): + Keyword + LIST (70): + List for chains of comparable items + NOMC (71): + Nominalized clause + NOMCSUBJ (72): + Nominalized clausal subject + NOMCSUBJPASS (73): + Nominalized clausal passive + NUMC (74): + Compound of numeric modifier + COP (75): + Copula + DISLOCATED (76): + Dislocated relation (for fronted/topicalized + elements) + ASP (77): + Aspect marker + GMOD (78): + Genitive modifier + GOBJ (79): + Genitive object + INFMOD (80): + Infinitival modifier + MES (81): + Measure + NCOMP (82): + Nominal complement of a noun + """ UNKNOWN = 0 ABBREV = 1 ACOMP = 2 @@ -662,7 +1133,16 @@ class EntityMention(proto.Message): """ class Type(proto.Enum): - r"""The supported types of mentions.""" + r"""The supported types of mentions. + + Values: + TYPE_UNKNOWN (0): + Unknown + PROPER (1): + Proper name + COMMON (2): + Common noun (or noun compound) + """ TYPE_UNKNOWN = 0 PROPER = 1 COMMON = 2 @@ -770,7 +1250,18 @@ class V2Model(proto.Message): """ class ContentCategoriesVersion(proto.Enum): - r"""The content categories used for classification.""" + r"""The content categories used for classification. + + Values: + CONTENT_CATEGORIES_VERSION_UNSPECIFIED (0): + If ``ContentCategoriesVersion`` is not specified, this + option will default to ``V1``. + V1 (1): + Legacy content categories of our initial + launch in 2017. + V2 (2): + Updated content categories in 2022. + """ CONTENT_CATEGORIES_VERSION_UNSPECIFIED = 0 V1 = 1 V2 = 2 diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 3b46e9bd..10d44fa5 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -1068,7 +1068,7 @@ def sample_annotate_text(): # Done; return the response. return response - def __enter__(self): + def __enter__(self) -> "LanguageServiceClient": return self def __exit__(self, type, value, traceback): diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 7e98b632..cd661423 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -54,6 +54,27 @@ class EncodingType(proto.Enum): provides the beginning offsets for various outputs, such as tokens and mentions, and languages that natively use different text encodings may access offsets differently. + + Values: + NONE (0): + If ``EncodingType`` is not specified, encoding-dependent + information (such as ``begin_offset``) will be set at + ``-1``. + UTF8 (1): + Encoding-dependent information (such as ``begin_offset``) is + calculated based on the UTF-8 encoding of the input. C++ and + Go are examples of languages that use this encoding + natively. + UTF16 (2): + Encoding-dependent information (such as ``begin_offset``) is + calculated based on the UTF-16 encoding of the input. Java + and JavaScript are examples of languages that use this + encoding natively. + UTF32 (3): + Encoding-dependent information (such as ``begin_offset``) is + calculated based on the UTF-32 encoding of the input. Python + is an example of a language that uses this encoding + natively. """ NONE = 0 UTF8 = 1 @@ -111,13 +132,33 @@ class Document(proto.Message): """ class Type(proto.Enum): - r"""The document types enum.""" + r"""The document types enum. + + Values: + TYPE_UNSPECIFIED (0): + The content type is not specified. + PLAIN_TEXT (1): + Plain text + HTML (2): + HTML + """ TYPE_UNSPECIFIED = 0 PLAIN_TEXT = 1 HTML = 2 class BoilerplateHandling(proto.Enum): - r"""Ways of handling boilerplate detected in the document""" + r"""Ways of handling boilerplate detected in the document + + Values: + BOILERPLATE_HANDLING_UNSPECIFIED (0): + The boilerplate handling is not specified. + SKIP_BOILERPLATE (1): + Do not analyze detected boilerplate. + Reference web URI is required for detecting + boilerplate. + KEEP_BOILERPLATE (2): + Treat boilerplate the same as content. + """ BOILERPLATE_HANDLING_UNSPECIFIED = 0 SKIP_BOILERPLATE = 1 KEEP_BOILERPLATE = 2 @@ -219,6 +260,69 @@ class Type(proto.Enum): metadata is a Wikipedia URL (``wikipedia_url``) and Knowledge Graph MID (``mid``). The table below lists the associated fields for entities that have different metadata. + + Values: + UNKNOWN (0): + Unknown + PERSON (1): + Person + LOCATION (2): + Location + ORGANIZATION (3): + Organization + EVENT (4): + Event + WORK_OF_ART (5): + Artwork + CONSUMER_GOOD (6): + Consumer product + OTHER (7): + Other types of entities + PHONE_NUMBER (9): + Phone number + + The metadata lists the phone number, formatted according to + local convention, plus whichever additional elements appear + in the text: + + - ``number`` - the actual number, broken down into sections + as per local convention + - ``national_prefix`` - country code, if detected + - ``area_code`` - region or area code, if detected + - ``extension`` - phone extension (to be dialed after + connection), if detected + ADDRESS (10): + Address + + The metadata identifies the street number and locality plus + whichever additional elements appear in the text: + + - ``street_number`` - street number + - ``locality`` - city or town + - ``street_name`` - street/route name, if detected + - ``postal_code`` - postal code, if detected + - ``country`` - country, if detected< + - ``broad_region`` - administrative area, such as the + state, if detected + - ``narrow_region`` - smaller administrative area, such as + county, if detected + - ``sublocality`` - used in Asian addresses to demark a + district within a city, if detected + DATE (11): + Date + + The metadata identifies the components of the date: + + - ``year`` - four digit year, if detected + - ``month`` - two digit month number, if detected + - ``day`` - two digit day number, if detected + NUMBER (12): + Number + The metadata is the number itself. + PRICE (13): + Price + + The metadata identifies the ``value`` and ``currency``. """ UNKNOWN = 0 PERSON = 1 @@ -356,7 +460,38 @@ class PartOfSpeech(proto.Message): """ class Tag(proto.Enum): - r"""The part of speech tags enum.""" + r"""The part of speech tags enum. + + Values: + UNKNOWN (0): + Unknown + ADJ (1): + Adjective + ADP (2): + Adposition (preposition and postposition) + ADV (3): + Adverb + CONJ (4): + Conjunction + DET (5): + Determiner + NOUN (6): + Noun (common and proper) + NUM (7): + Cardinal number + PRON (8): + Pronoun + PRT (9): + Particle or other function word + PUNCT (10): + Punctuation + VERB (11): + Verb (all tenses and modes) + X (12): + Other: foreign words, typos, abbreviations + AFFIX (13): + Affix + """ UNKNOWN = 0 ADJ = 1 ADP = 2 @@ -375,6 +510,17 @@ class Tag(proto.Enum): class Aspect(proto.Enum): r"""The characteristic of a verb that expresses time flow during an event. + + Values: + ASPECT_UNKNOWN (0): + Aspect is not applicable in the analyzed + language or is not predicted. + PERFECTIVE (1): + Perfective + IMPERFECTIVE (2): + Imperfective + PROGRESSIVE (3): + Progressive """ ASPECT_UNKNOWN = 0 PERFECTIVE = 1 @@ -386,6 +532,39 @@ class Case(proto.Enum): phrase, clause, or sentence. In some languages, other parts of speech, such as adjective and determiner, take case inflection in agreement with the noun. + + Values: + CASE_UNKNOWN (0): + Case is not applicable in the analyzed + language or is not predicted. + ACCUSATIVE (1): + Accusative + ADVERBIAL (2): + Adverbial + COMPLEMENTIVE (3): + Complementive + DATIVE (4): + Dative + GENITIVE (5): + Genitive + INSTRUMENTAL (6): + Instrumental + LOCATIVE (7): + Locative + NOMINATIVE (8): + Nominative + OBLIQUE (9): + Oblique + PARTITIVE (10): + Partitive + PREPOSITIONAL (11): + Prepositional + REFLEXIVE_CASE (12): + Reflexive + RELATIVE_CASE (13): + Relative + VOCATIVE (14): + Vocative """ CASE_UNKNOWN = 0 ACCUSATIVE = 1 @@ -409,6 +588,33 @@ class Form(proto.Enum): categorizing inflected endings of verbs and adjectives or distinguishing between short and long forms of adjectives and participles + + Values: + FORM_UNKNOWN (0): + Form is not applicable in the analyzed + language or is not predicted. + ADNOMIAL (1): + Adnomial + AUXILIARY (2): + Auxiliary + COMPLEMENTIZER (3): + Complementizer + FINAL_ENDING (4): + Final ending + GERUND (5): + Gerund + REALIS (6): + Realis + IRREALIS (7): + Irrealis + SHORT (8): + Short form + LONG (9): + Long form + ORDER (10): + Order form + SPECIFIC (11): + Specific form """ FORM_UNKNOWN = 0 ADNOMIAL = 1 @@ -426,6 +632,17 @@ class Form(proto.Enum): class Gender(proto.Enum): r"""Gender classes of nouns reflected in the behaviour of associated words. + + Values: + GENDER_UNKNOWN (0): + Gender is not applicable in the analyzed + language or is not predicted. + FEMININE (1): + Feminine + MASCULINE (2): + Masculine + NEUTER (3): + Neuter """ GENDER_UNKNOWN = 0 FEMININE = 1 @@ -435,6 +652,23 @@ class Gender(proto.Enum): class Mood(proto.Enum): r"""The grammatical feature of verbs, used for showing modality and attitude. + + Values: + MOOD_UNKNOWN (0): + Mood is not applicable in the analyzed + language or is not predicted. + CONDITIONAL_MOOD (1): + Conditional + IMPERATIVE (2): + Imperative + INDICATIVE (3): + Indicative + INTERROGATIVE (4): + Interrogative + JUSSIVE (5): + Jussive + SUBJUNCTIVE (6): + Subjunctive """ MOOD_UNKNOWN = 0 CONDITIONAL_MOOD = 1 @@ -445,7 +679,19 @@ class Mood(proto.Enum): SUBJUNCTIVE = 6 class Number(proto.Enum): - r"""Count distinctions.""" + r"""Count distinctions. + + Values: + NUMBER_UNKNOWN (0): + Number is not applicable in the analyzed + language or is not predicted. + SINGULAR (1): + Singular + PLURAL (2): + Plural + DUAL (3): + Dual + """ NUMBER_UNKNOWN = 0 SINGULAR = 1 PLURAL = 2 @@ -454,6 +700,19 @@ class Number(proto.Enum): class Person(proto.Enum): r"""The distinction between the speaker, second person, third person, etc. + + Values: + PERSON_UNKNOWN (0): + Person is not applicable in the analyzed + language or is not predicted. + FIRST (1): + First + SECOND (2): + Second + THIRD (3): + Third + REFLEXIVE_PERSON (4): + Reflexive """ PERSON_UNKNOWN = 0 FIRST = 1 @@ -462,19 +721,57 @@ class Person(proto.Enum): REFLEXIVE_PERSON = 4 class Proper(proto.Enum): - r"""This category shows if the token is part of a proper name.""" + r"""This category shows if the token is part of a proper name. + + Values: + PROPER_UNKNOWN (0): + Proper is not applicable in the analyzed + language or is not predicted. + PROPER (1): + Proper + NOT_PROPER (2): + Not proper + """ PROPER_UNKNOWN = 0 PROPER = 1 NOT_PROPER = 2 class Reciprocity(proto.Enum): - r"""Reciprocal features of a pronoun.""" + r"""Reciprocal features of a pronoun. + + Values: + RECIPROCITY_UNKNOWN (0): + Reciprocity is not applicable in the analyzed + language or is not predicted. + RECIPROCAL (1): + Reciprocal + NON_RECIPROCAL (2): + Non-reciprocal + """ RECIPROCITY_UNKNOWN = 0 RECIPROCAL = 1 NON_RECIPROCAL = 2 class Tense(proto.Enum): - r"""Time reference.""" + r"""Time reference. + + Values: + TENSE_UNKNOWN (0): + Tense is not applicable in the analyzed + language or is not predicted. + CONDITIONAL_TENSE (1): + Conditional + FUTURE (2): + Future + PAST (3): + Past + PRESENT (4): + Present + IMPERFECT (5): + Imperfect + PLUPERFECT (6): + Pluperfect + """ TENSE_UNKNOWN = 0 CONDITIONAL_TENSE = 1 FUTURE = 2 @@ -486,6 +783,17 @@ class Tense(proto.Enum): class Voice(proto.Enum): r"""The relationship between the action that a verb expresses and the participants identified by its arguments. + + Values: + VOICE_UNKNOWN (0): + Voice is not applicable in the analyzed + language or is not predicted. + ACTIVE (1): + Active + CAUSATIVE (2): + Causative + PASSIVE (3): + Passive """ VOICE_UNKNOWN = 0 ACTIVE = 1 @@ -570,7 +878,181 @@ class DependencyEdge(proto.Message): """ class Label(proto.Enum): - r"""The parse label enum for the token.""" + r"""The parse label enum for the token. + + Values: + UNKNOWN (0): + Unknown + ABBREV (1): + Abbreviation modifier + ACOMP (2): + Adjectival complement + ADVCL (3): + Adverbial clause modifier + ADVMOD (4): + Adverbial modifier + AMOD (5): + Adjectival modifier of an NP + APPOS (6): + Appositional modifier of an NP + ATTR (7): + Attribute dependent of a copular verb + AUX (8): + Auxiliary (non-main) verb + AUXPASS (9): + Passive auxiliary + CC (10): + Coordinating conjunction + CCOMP (11): + Clausal complement of a verb or adjective + CONJ (12): + Conjunct + CSUBJ (13): + Clausal subject + CSUBJPASS (14): + Clausal passive subject + DEP (15): + Dependency (unable to determine) + DET (16): + Determiner + DISCOURSE (17): + Discourse + DOBJ (18): + Direct object + EXPL (19): + Expletive + GOESWITH (20): + Goes with (part of a word in a text not well + edited) + IOBJ (21): + Indirect object + MARK (22): + Marker (word introducing a subordinate + clause) + MWE (23): + Multi-word expression + MWV (24): + Multi-word verbal expression + NEG (25): + Negation modifier + NN (26): + Noun compound modifier + NPADVMOD (27): + Noun phrase used as an adverbial modifier + NSUBJ (28): + Nominal subject + NSUBJPASS (29): + Passive nominal subject + NUM (30): + Numeric modifier of a noun + NUMBER (31): + Element of compound number + P (32): + Punctuation mark + PARATAXIS (33): + Parataxis relation + PARTMOD (34): + Participial modifier + PCOMP (35): + The complement of a preposition is a clause + POBJ (36): + Object of a preposition + POSS (37): + Possession modifier + POSTNEG (38): + Postverbal negative particle + PRECOMP (39): + Predicate complement + PRECONJ (40): + Preconjunt + PREDET (41): + Predeterminer + PREF (42): + Prefix + PREP (43): + Prepositional modifier + PRONL (44): + The relationship between a verb and verbal + morpheme + PRT (45): + Particle + PS (46): + Associative or possessive marker + QUANTMOD (47): + Quantifier phrase modifier + RCMOD (48): + Relative clause modifier + RCMODREL (49): + Complementizer in relative clause + RDROP (50): + Ellipsis without a preceding predicate + REF (51): + Referent + REMNANT (52): + Remnant + REPARANDUM (53): + Reparandum + ROOT (54): + Root + SNUM (55): + Suffix specifying a unit of number + SUFF (56): + Suffix + TMOD (57): + Temporal modifier + TOPIC (58): + Topic marker + VMOD (59): + Clause headed by an infinite form of the verb + that modifies a noun + VOCATIVE (60): + Vocative + XCOMP (61): + Open clausal complement + SUFFIX (62): + Name suffix + TITLE (63): + Name title + ADVPHMOD (64): + Adverbial phrase modifier + AUXCAUS (65): + Causative auxiliary + AUXVV (66): + Helper auxiliary + DTMOD (67): + Rentaishi (Prenominal modifier) + FOREIGN (68): + Foreign words + KW (69): + Keyword + LIST (70): + List for chains of comparable items + NOMC (71): + Nominalized clause + NOMCSUBJ (72): + Nominalized clausal subject + NOMCSUBJPASS (73): + Nominalized clausal passive + NUMC (74): + Compound of numeric modifier + COP (75): + Copula + DISLOCATED (76): + Dislocated relation (for fronted/topicalized + elements) + ASP (77): + Aspect marker + GMOD (78): + Genitive modifier + GOBJ (79): + Genitive object + INFMOD (80): + Infinitival modifier + MES (81): + Measure + NCOMP (82): + Nominal complement of a noun + """ UNKNOWN = 0 ABBREV = 1 ACOMP = 2 @@ -684,7 +1166,16 @@ class EntityMention(proto.Message): """ class Type(proto.Enum): - r"""The supported types of mentions.""" + r"""The supported types of mentions. + + Values: + TYPE_UNKNOWN (0): + Unknown + PROPER (1): + Proper name + COMMON (2): + Common noun (or noun compound) + """ TYPE_UNKNOWN = 0 PROPER = 1 COMMON = 2 @@ -792,7 +1283,18 @@ class V2Model(proto.Message): """ class ContentCategoriesVersion(proto.Enum): - r"""The content categories used for classification.""" + r"""The content categories used for classification. + + Values: + CONTENT_CATEGORIES_VERSION_UNSPECIFIED (0): + If ``ContentCategoriesVersion`` is not specified, this + option will default to ``V1``. + V1 (1): + Legacy content categories of our initial + launch in 2017. + V2 (2): + Updated content categories in 2022. + """ CONTENT_CATEGORIES_VERSION_UNSPECIFIED = 0 V1 = 1 V2 = 2 diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index ca7dff9f..936a8b70 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.8.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index a3527b53..a4368f2d 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.8.0" + "version": "0.1.0" }, "snippets": [ { From fd695406d855b9aeaf3aab185c622494c02a33fb Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 23 Jan 2023 10:41:17 -0500 Subject: [PATCH 234/254] chore(main): release 2.8.1 (#416) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 12 ++++++++++++ google/cloud/language/gapic_version.py | 2 +- google/cloud/language_v1/gapic_version.py | 2 +- google/cloud/language_v1beta2/gapic_version.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- ...ippet_metadata_google.cloud.language.v1beta2.json | 2 +- 7 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 8388fe10..9c62c130 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.8.0" + ".": "2.8.1" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 711c0394..0ec4d2ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.8.1](https://github.com/googleapis/python-language/compare/v2.8.0...v2.8.1) (2023-01-20) + + +### Bug Fixes + +* Add context manager return types ([a26c418](https://github.com/googleapis/python-language/commit/a26c418a54cb26825c9c539282ed37cb9d9eac0c)) + + +### Documentation + +* Add documentation for enums ([a26c418](https://github.com/googleapis/python-language/commit/a26c418a54cb26825c9c539282ed37cb9d9eac0c)) + ## [2.8.0](https://github.com/googleapis/python-language/compare/v2.7.0...v2.8.0) (2023-01-10) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index e248a9ca..15e84ffd 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.8.0" # {x-release-please-version} +__version__ = "2.8.1" # {x-release-please-version} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py index e248a9ca..15e84ffd 100644 --- a/google/cloud/language_v1/gapic_version.py +++ b/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.8.0" # {x-release-please-version} +__version__ = "2.8.1" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py index e248a9ca..15e84ffd 100644 --- a/google/cloud/language_v1beta2/gapic_version.py +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.8.0" # {x-release-please-version} +__version__ = "2.8.1" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 936a8b70..692fa6a2 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.8.1" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index a4368f2d..8c3a1b37 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.8.1" }, "snippets": [ { From 4f96fe1cd29110d345b3f73a05845b313f21d545 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 25 Jan 2023 11:33:37 -0500 Subject: [PATCH 235/254] chore: Update gapic-generator-python to v1.8.2 (#417) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.2 PiperOrigin-RevId: 504289125 Source-Link: https://github.com/googleapis/googleapis/commit/38a48a44a44279e9cf9f2f864b588958a2d87491 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2dc22663dbe47a972c8d8c2f8a4df013dafdcbc Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJkYzIyNjYzZGJlNDdhOTcyYzhkOGMyZjhhNGRmMDEzZGFmZGNiYyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .coveragerc | 1 + google/cloud/language_v1/__init__.py | 2 +- google/cloud/language_v1beta2/__init__.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.coveragerc b/.coveragerc index 4a9db2a6..c1f51536 100644 --- a/.coveragerc +++ b/.coveragerc @@ -5,6 +5,7 @@ branch = True show_missing = True omit = google/cloud/language/__init__.py + google/cloud/language/gapic_version.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py index 3c9bd856..6df3e48a 100644 --- a/google/cloud/language_v1/__init__.py +++ b/google/cloud/language_v1/__init__.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.language import gapic_version as package_version +from google.cloud.language_v1 import gapic_version as package_version __version__ = package_version.__version__ diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py index 3c9bd856..459b226d 100644 --- a/google/cloud/language_v1beta2/__init__.py +++ b/google/cloud/language_v1beta2/__init__.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.language import gapic_version as package_version +from google.cloud.language_v1beta2 import gapic_version as package_version __version__ = package_version.__version__ diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 692fa6a2..936a8b70 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.8.1" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index 8c3a1b37..a4368f2d 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.8.1" + "version": "0.1.0" }, "snippets": [ { From 9fe566146ce81042ccf8212b108bf77a19d45e50 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 30 Jan 2023 16:52:31 +0000 Subject: [PATCH 236/254] chore: fix prerelease_deps nox session [autoapprove] (#418) Source-Link: https://togithub.com/googleapis/synthtool/commit/26c7505b2f76981ec1707b851e1595c8c06e90fc Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 --- .github/.OwlBot.lock.yaml | 2 +- noxfile.py | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 889f77df..f0f3b24b 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 + digest: sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 diff --git a/noxfile.py b/noxfile.py index e716318b..95e58c52 100644 --- a/noxfile.py +++ b/noxfile.py @@ -189,9 +189,9 @@ def unit(session): def install_systemtest_dependencies(session, *constraints): # Use pre-release gRPC for system tests. - # Exclude version 1.49.0rc1 which has a known issue. - # See https://github.com/grpc/grpc/pull/30642 - session.install("--pre", "grpcio!=1.49.0rc1") + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) @@ -346,9 +346,7 @@ def prerelease_deps(session): unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES session.install(*unit_deps_all) system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS + SYSTEM_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_EXTERNAL_DEPENDENCIES ) session.install(*system_deps_all) @@ -378,8 +376,8 @@ def prerelease_deps(session): # dependency of grpc "six", "googleapis-common-protos", - # Exclude version 1.49.0rc1 which has a known issue. See https://github.com/grpc/grpc/pull/30642 - "grpcio!=1.49.0rc1", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", "grpcio-status", "google-api-core", "proto-plus", From 77bdac304ffc2d3138c60bf49c6bf843f75ab665 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 8 Feb 2023 07:07:51 -0500 Subject: [PATCH 237/254] chore: Update gapic-generator-python to v1.8.4 (#419) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.4 PiperOrigin-RevId: 507808936 Source-Link: https://github.com/googleapis/googleapis/commit/64cf8492b21778ce62c66ecee81b468a293bfd4c Source-Link: https://github.com/googleapis/googleapis-gen/commit/53c48cac153d3b37f3d2c2dec4830cfd91ec4153 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTNjNDhjYWMxNTNkM2IzN2YzZDJjMmRlYzQ4MzBjZmQ5MWVjNDE1MyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- setup.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 5a29f742..8991c6f5 100644 --- a/setup.py +++ b/setup.py @@ -55,9 +55,7 @@ if package.startswith("google") ] -namespaces = ["google"] -if "google.cloud" in packages: - namespaces.append("google.cloud") +namespaces = ["google", "google.cloud"] setuptools.setup( name=name, From 58a7be2de1912aa388c3098b3e523e190ec11978 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 8 Feb 2023 16:18:23 +0000 Subject: [PATCH 238/254] build(deps): bump cryptography from 38.0.3 to 39.0.1 in /synthtool/gcp/templates/python_library/.kokoro (#421) Source-Link: https://togithub.com/googleapis/synthtool/commit/bb171351c3946d3c3c32e60f5f18cee8c464ec51 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf --- .github/.OwlBot.lock.yaml | 4 +++- .kokoro/requirements.txt | 49 ++++++++++++++++++--------------------- 2 files changed, 25 insertions(+), 28 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index f0f3b24b..0245dd69 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,6 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 + digest: sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf + +trigger ci diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 05dc4672..096e4800 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -113,33 +113,28 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==38.0.3 \ - --hash=sha256:068147f32fa662c81aebab95c74679b401b12b57494872886eb5c1139250ec5d \ - --hash=sha256:06fc3cc7b6f6cca87bd56ec80a580c88f1da5306f505876a71c8cfa7050257dd \ - --hash=sha256:25c1d1f19729fb09d42e06b4bf9895212292cb27bb50229f5aa64d039ab29146 \ - --hash=sha256:402852a0aea73833d982cabb6d0c3bb582c15483d29fb7085ef2c42bfa7e38d7 \ - --hash=sha256:4e269dcd9b102c5a3d72be3c45d8ce20377b8076a43cbed6f660a1afe365e436 \ - --hash=sha256:5419a127426084933076132d317911e3c6eb77568a1ce23c3ac1e12d111e61e0 \ - --hash=sha256:554bec92ee7d1e9d10ded2f7e92a5d70c1f74ba9524947c0ba0c850c7b011828 \ - --hash=sha256:5e89468fbd2fcd733b5899333bc54d0d06c80e04cd23d8c6f3e0542358c6060b \ - --hash=sha256:65535bc550b70bd6271984d9863a37741352b4aad6fb1b3344a54e6950249b55 \ - --hash=sha256:6ab9516b85bebe7aa83f309bacc5f44a61eeb90d0b4ec125d2d003ce41932d36 \ - --hash=sha256:6addc3b6d593cd980989261dc1cce38263c76954d758c3c94de51f1e010c9a50 \ - --hash=sha256:728f2694fa743a996d7784a6194da430f197d5c58e2f4e278612b359f455e4a2 \ - --hash=sha256:785e4056b5a8b28f05a533fab69febf5004458e20dad7e2e13a3120d8ecec75a \ - --hash=sha256:78cf5eefac2b52c10398a42765bfa981ce2372cbc0457e6bf9658f41ec3c41d8 \ - --hash=sha256:7f836217000342d448e1c9a342e9163149e45d5b5eca76a30e84503a5a96cab0 \ - --hash=sha256:8d41a46251bf0634e21fac50ffd643216ccecfaf3701a063257fe0b2be1b6548 \ - --hash=sha256:984fe150f350a3c91e84de405fe49e688aa6092b3525f407a18b9646f6612320 \ - --hash=sha256:9b24bcff7853ed18a63cfb0c2b008936a9554af24af2fb146e16d8e1aed75748 \ - --hash=sha256:b1b35d9d3a65542ed2e9d90115dfd16bbc027b3f07ee3304fc83580f26e43249 \ - --hash=sha256:b1b52c9e5f8aa2b802d48bd693190341fae201ea51c7a167d69fc48b60e8a959 \ - --hash=sha256:bbf203f1a814007ce24bd4d51362991d5cb90ba0c177a9c08825f2cc304d871f \ - --hash=sha256:be243c7e2bfcf6cc4cb350c0d5cdf15ca6383bbcb2a8ef51d3c9411a9d4386f0 \ - --hash=sha256:bfbe6ee19615b07a98b1d2287d6a6073f734735b49ee45b11324d85efc4d5cbd \ - --hash=sha256:c46837ea467ed1efea562bbeb543994c2d1f6e800785bd5a2c98bc096f5cb220 \ - --hash=sha256:dfb4f4dd568de1b6af9f4cda334adf7d72cf5bc052516e1b2608b683375dd95c \ - --hash=sha256:ed7b00096790213e09eb11c97cc6e2b757f15f3d2f85833cd2d3ec3fe37c1722 +cryptography==39.0.1 \ + --hash=sha256:0f8da300b5c8af9f98111ffd512910bc792b4c77392a9523624680f7956a99d4 \ + --hash=sha256:35f7c7d015d474f4011e859e93e789c87d21f6f4880ebdc29896a60403328f1f \ + --hash=sha256:5aa67414fcdfa22cf052e640cb5ddc461924a045cacf325cd164e65312d99502 \ + --hash=sha256:5d2d8b87a490bfcd407ed9d49093793d0f75198a35e6eb1a923ce1ee86c62b41 \ + --hash=sha256:6687ef6d0a6497e2b58e7c5b852b53f62142cfa7cd1555795758934da363a965 \ + --hash=sha256:6f8ba7f0328b79f08bdacc3e4e66fb4d7aab0c3584e0bd41328dce5262e26b2e \ + --hash=sha256:706843b48f9a3f9b9911979761c91541e3d90db1ca905fd63fee540a217698bc \ + --hash=sha256:807ce09d4434881ca3a7594733669bd834f5b2c6d5c7e36f8c00f691887042ad \ + --hash=sha256:83e17b26de248c33f3acffb922748151d71827d6021d98c70e6c1a25ddd78505 \ + --hash=sha256:96f1157a7c08b5b189b16b47bc9db2332269d6680a196341bf30046330d15388 \ + --hash=sha256:aec5a6c9864be7df2240c382740fcf3b96928c46604eaa7f3091f58b878c0bb6 \ + --hash=sha256:b0afd054cd42f3d213bf82c629efb1ee5f22eba35bf0eec88ea9ea7304f511a2 \ + --hash=sha256:ced4e447ae29ca194449a3f1ce132ded8fcab06971ef5f618605aacaa612beac \ + --hash=sha256:d1f6198ee6d9148405e49887803907fe8962a23e6c6f83ea7d98f1c0de375695 \ + --hash=sha256:e124352fd3db36a9d4a21c1aa27fd5d051e621845cb87fb851c08f4f75ce8be6 \ + --hash=sha256:e422abdec8b5fa8462aa016786680720d78bdce7a30c652b7fadf83a4ba35336 \ + --hash=sha256:ef8b72fa70b348724ff1218267e7f7375b8de4e8194d1636ee60510aae104cd0 \ + --hash=sha256:f0c64d1bd842ca2633e74a1a28033d139368ad959872533b1bab8c80e8240a0c \ + --hash=sha256:f24077a3b5298a5a06a8e0536e3ea9ec60e4c7ac486755e5fb6e6ea9b3500106 \ + --hash=sha256:fdd188c8a6ef8769f148f88f859884507b954cc64db6b52f66ef199bb9ad660a \ + --hash=sha256:fe913f20024eb2cb2f323e42a64bdf2911bb9738a15dba7d3cce48151034e3a8 # via # gcp-releasetool # secretstorage From 21c09b8e009a560c77d96f8fa92c5e91cfdad29f Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 16 Feb 2023 05:44:50 -0500 Subject: [PATCH 239/254] feat: enable "rest" transport in Python for services supporting numeric enums (#423) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * fix typo * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .github/.OwlBot.lock.yaml | 2 - google/cloud/language_v1/gapic_metadata.json | 35 + .../services/language_service/client.py | 2 + .../language_service/transports/__init__.py | 4 + .../language_service/transports/rest.py | 1023 +++++++++ .../language_v1beta2/gapic_metadata.json | 35 + .../services/language_service/client.py | 2 + .../language_service/transports/__init__.py | 4 + .../language_service/transports/rest.py | 1023 +++++++++ .../language_v1/test_language_service.py | 1980 ++++++++++++++-- .../language_v1beta2/test_language_service.py | 1981 +++++++++++++++-- 11 files changed, 5825 insertions(+), 266 deletions(-) create mode 100644 google/cloud/language_v1/services/language_service/transports/rest.py create mode 100644 google/cloud/language_v1beta2/services/language_service/transports/rest.py diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0245dd69..894fb6bc 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -14,5 +14,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest digest: sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf - -trigger ci diff --git a/google/cloud/language_v1/gapic_metadata.json b/google/cloud/language_v1/gapic_metadata.json index 64d3c3e4..e475aad9 100644 --- a/google/cloud/language_v1/gapic_metadata.json +++ b/google/cloud/language_v1/gapic_metadata.json @@ -76,6 +76,41 @@ ] } } + }, + "rest": { + "libraryClient": "LanguageServiceClient", + "rpcs": { + "AnalyzeEntities": { + "methods": [ + "analyze_entities" + ] + }, + "AnalyzeEntitySentiment": { + "methods": [ + "analyze_entity_sentiment" + ] + }, + "AnalyzeSentiment": { + "methods": [ + "analyze_sentiment" + ] + }, + "AnalyzeSyntax": { + "methods": [ + "analyze_syntax" + ] + }, + "AnnotateText": { + "methods": [ + "annotate_text" + ] + }, + "ClassifyText": { + "methods": [ + "classify_text" + ] + } + } } } } diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index 276e9489..e97f3240 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -51,6 +51,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport from .transports.grpc import LanguageServiceGrpcTransport from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport +from .transports.rest import LanguageServiceRestTransport class LanguageServiceClientMeta(type): @@ -66,6 +67,7 @@ class LanguageServiceClientMeta(type): ) # type: Dict[str, Type[LanguageServiceTransport]] _transport_registry["grpc"] = LanguageServiceGrpcTransport _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LanguageServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/language_v1/services/language_service/transports/__init__.py b/google/cloud/language_v1/services/language_service/transports/__init__.py index 5ec2196c..12a453a7 100644 --- a/google/cloud/language_v1/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1/services/language_service/transports/__init__.py @@ -19,14 +19,18 @@ from .base import LanguageServiceTransport from .grpc import LanguageServiceGrpcTransport from .grpc_asyncio import LanguageServiceGrpcAsyncIOTransport +from .rest import LanguageServiceRestInterceptor, LanguageServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[LanguageServiceTransport]] _transport_registry["grpc"] = LanguageServiceGrpcTransport _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport +_transport_registry["rest"] = LanguageServiceRestTransport __all__ = ( "LanguageServiceTransport", "LanguageServiceGrpcTransport", "LanguageServiceGrpcAsyncIOTransport", + "LanguageServiceRestTransport", + "LanguageServiceRestInterceptor", ) diff --git a/google/cloud/language_v1/services/language_service/transports/rest.py b/google/cloud/language_v1/services/language_service/transports/rest.py new file mode 100644 index 00000000..e9b0585f --- /dev/null +++ b/google/cloud/language_v1/services/language_service/transports/rest.py @@ -0,0 +1,1023 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.language_v1.types import language_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import LanguageServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class LanguageServiceRestInterceptor: + """Interceptor for LanguageService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the LanguageServiceRestTransport. + + .. code-block:: python + class MyCustomLanguageServiceInterceptor(LanguageServiceRestInterceptor): + def pre_analyze_entities(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_entities(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_entity_sentiment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_entity_sentiment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_sentiment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_sentiment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_syntax(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_syntax(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_annotate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_annotate_text(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_classify_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_classify_text(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LanguageServiceRestTransport(interceptor=MyCustomLanguageServiceInterceptor()) + client = LanguageServiceClient(transport=transport) + + + """ + + def pre_analyze_entities( + self, + request: language_service.AnalyzeEntitiesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnalyzeEntitiesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_entities + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_entities( + self, response: language_service.AnalyzeEntitiesResponse + ) -> language_service.AnalyzeEntitiesResponse: + """Post-rpc interceptor for analyze_entities + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_analyze_entity_sentiment( + self, + request: language_service.AnalyzeEntitySentimentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + language_service.AnalyzeEntitySentimentRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for analyze_entity_sentiment + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_entity_sentiment( + self, response: language_service.AnalyzeEntitySentimentResponse + ) -> language_service.AnalyzeEntitySentimentResponse: + """Post-rpc interceptor for analyze_entity_sentiment + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_analyze_sentiment( + self, + request: language_service.AnalyzeSentimentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnalyzeSentimentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_sentiment + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_sentiment( + self, response: language_service.AnalyzeSentimentResponse + ) -> language_service.AnalyzeSentimentResponse: + """Post-rpc interceptor for analyze_sentiment + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_analyze_syntax( + self, + request: language_service.AnalyzeSyntaxRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnalyzeSyntaxRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_syntax + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_syntax( + self, response: language_service.AnalyzeSyntaxResponse + ) -> language_service.AnalyzeSyntaxResponse: + """Post-rpc interceptor for analyze_syntax + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_annotate_text( + self, + request: language_service.AnnotateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnnotateTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for annotate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_annotate_text( + self, response: language_service.AnnotateTextResponse + ) -> language_service.AnnotateTextResponse: + """Post-rpc interceptor for annotate_text + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_classify_text( + self, + request: language_service.ClassifyTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.ClassifyTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for classify_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_classify_text( + self, response: language_service.ClassifyTextResponse + ) -> language_service.ClassifyTextResponse: + """Post-rpc interceptor for classify_text + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LanguageServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LanguageServiceRestInterceptor + + +class LanguageServiceRestTransport(LanguageServiceTransport): + """REST backend transport for LanguageService. + + Provides text analysis operations such as sentiment analysis + and entity recognition. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "language.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[LanguageServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or LanguageServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AnalyzeEntities(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeEntities") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeEntitiesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeEntitiesResponse: + r"""Call the analyze entities method over HTTP. + + Args: + request (~.language_service.AnalyzeEntitiesRequest): + The request object. The entity analysis request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeEntitiesResponse: + The entity analysis response message. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/documents:analyzeEntities", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_entities( + request, metadata + ) + pb_request = language_service.AnalyzeEntitiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeEntitiesResponse() + pb_resp = language_service.AnalyzeEntitiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_entities(resp) + return resp + + class _AnalyzeEntitySentiment(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeEntitySentiment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeEntitySentimentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeEntitySentimentResponse: + r"""Call the analyze entity sentiment method over HTTP. + + Args: + request (~.language_service.AnalyzeEntitySentimentRequest): + The request object. The entity-level sentiment analysis + request message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeEntitySentimentResponse: + The entity-level sentiment analysis + response message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/documents:analyzeEntitySentiment", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_entity_sentiment( + request, metadata + ) + pb_request = language_service.AnalyzeEntitySentimentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeEntitySentimentResponse() + pb_resp = language_service.AnalyzeEntitySentimentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_entity_sentiment(resp) + return resp + + class _AnalyzeSentiment(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeSentiment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeSentimentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeSentimentResponse: + r"""Call the analyze sentiment method over HTTP. + + Args: + request (~.language_service.AnalyzeSentimentRequest): + The request object. The sentiment analysis request + message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeSentimentResponse: + The sentiment analysis response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/documents:analyzeSentiment", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_sentiment( + request, metadata + ) + pb_request = language_service.AnalyzeSentimentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeSentimentResponse() + pb_resp = language_service.AnalyzeSentimentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_sentiment(resp) + return resp + + class _AnalyzeSyntax(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeSyntax") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeSyntaxRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeSyntaxResponse: + r"""Call the analyze syntax method over HTTP. + + Args: + request (~.language_service.AnalyzeSyntaxRequest): + The request object. The syntax analysis request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeSyntaxResponse: + The syntax analysis response message. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/documents:analyzeSyntax", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_syntax(request, metadata) + pb_request = language_service.AnalyzeSyntaxRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeSyntaxResponse() + pb_resp = language_service.AnalyzeSyntaxResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_syntax(resp) + return resp + + class _AnnotateText(LanguageServiceRestStub): + def __hash__(self): + return hash("AnnotateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnnotateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnnotateTextResponse: + r"""Call the annotate text method over HTTP. + + Args: + request (~.language_service.AnnotateTextRequest): + The request object. The request message for the text + annotation API, which can perform + multiple analysis types (sentiment, + entities, and syntax) in one call. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnnotateTextResponse: + The text annotations response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/documents:annotateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_annotate_text(request, metadata) + pb_request = language_service.AnnotateTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnnotateTextResponse() + pb_resp = language_service.AnnotateTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_annotate_text(resp) + return resp + + class _ClassifyText(LanguageServiceRestStub): + def __hash__(self): + return hash("ClassifyText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.ClassifyTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ClassifyTextResponse: + r"""Call the classify text method over HTTP. + + Args: + request (~.language_service.ClassifyTextRequest): + The request object. The document classification request + message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.ClassifyTextResponse: + The document classification response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/documents:classifyText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_classify_text(request, metadata) + pb_request = language_service.ClassifyTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.ClassifyTextResponse() + pb_resp = language_service.ClassifyTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_classify_text(resp) + return resp + + @property + def analyze_entities( + self, + ) -> Callable[ + [language_service.AnalyzeEntitiesRequest], + language_service.AnalyzeEntitiesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeEntities(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_entity_sentiment( + self, + ) -> Callable[ + [language_service.AnalyzeEntitySentimentRequest], + language_service.AnalyzeEntitySentimentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeEntitySentiment(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_sentiment( + self, + ) -> Callable[ + [language_service.AnalyzeSentimentRequest], + language_service.AnalyzeSentimentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeSentiment(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_syntax( + self, + ) -> Callable[ + [language_service.AnalyzeSyntaxRequest], language_service.AnalyzeSyntaxResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeSyntax(self._session, self._host, self._interceptor) # type: ignore + + @property + def annotate_text( + self, + ) -> Callable[ + [language_service.AnnotateTextRequest], language_service.AnnotateTextResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnnotateText(self._session, self._host, self._interceptor) # type: ignore + + @property + def classify_text( + self, + ) -> Callable[ + [language_service.ClassifyTextRequest], language_service.ClassifyTextResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ClassifyText(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("LanguageServiceRestTransport",) diff --git a/google/cloud/language_v1beta2/gapic_metadata.json b/google/cloud/language_v1beta2/gapic_metadata.json index dbb6d13e..fca8f442 100644 --- a/google/cloud/language_v1beta2/gapic_metadata.json +++ b/google/cloud/language_v1beta2/gapic_metadata.json @@ -76,6 +76,41 @@ ] } } + }, + "rest": { + "libraryClient": "LanguageServiceClient", + "rpcs": { + "AnalyzeEntities": { + "methods": [ + "analyze_entities" + ] + }, + "AnalyzeEntitySentiment": { + "methods": [ + "analyze_entity_sentiment" + ] + }, + "AnalyzeSentiment": { + "methods": [ + "analyze_sentiment" + ] + }, + "AnalyzeSyntax": { + "methods": [ + "analyze_syntax" + ] + }, + "AnnotateText": { + "methods": [ + "annotate_text" + ] + }, + "ClassifyText": { + "methods": [ + "classify_text" + ] + } + } } } } diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 10d44fa5..613c8c88 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -51,6 +51,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport from .transports.grpc import LanguageServiceGrpcTransport from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport +from .transports.rest import LanguageServiceRestTransport class LanguageServiceClientMeta(type): @@ -66,6 +67,7 @@ class LanguageServiceClientMeta(type): ) # type: Dict[str, Type[LanguageServiceTransport]] _transport_registry["grpc"] = LanguageServiceGrpcTransport _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LanguageServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py index 5ec2196c..12a453a7 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py @@ -19,14 +19,18 @@ from .base import LanguageServiceTransport from .grpc import LanguageServiceGrpcTransport from .grpc_asyncio import LanguageServiceGrpcAsyncIOTransport +from .rest import LanguageServiceRestInterceptor, LanguageServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[LanguageServiceTransport]] _transport_registry["grpc"] = LanguageServiceGrpcTransport _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport +_transport_registry["rest"] = LanguageServiceRestTransport __all__ = ( "LanguageServiceTransport", "LanguageServiceGrpcTransport", "LanguageServiceGrpcAsyncIOTransport", + "LanguageServiceRestTransport", + "LanguageServiceRestInterceptor", ) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/rest.py b/google/cloud/language_v1beta2/services/language_service/transports/rest.py new file mode 100644 index 00000000..6ab75ba5 --- /dev/null +++ b/google/cloud/language_v1beta2/services/language_service/transports/rest.py @@ -0,0 +1,1023 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.language_v1beta2.types import language_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import LanguageServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class LanguageServiceRestInterceptor: + """Interceptor for LanguageService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the LanguageServiceRestTransport. + + .. code-block:: python + class MyCustomLanguageServiceInterceptor(LanguageServiceRestInterceptor): + def pre_analyze_entities(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_entities(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_entity_sentiment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_entity_sentiment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_sentiment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_sentiment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_syntax(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_syntax(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_annotate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_annotate_text(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_classify_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_classify_text(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LanguageServiceRestTransport(interceptor=MyCustomLanguageServiceInterceptor()) + client = LanguageServiceClient(transport=transport) + + + """ + + def pre_analyze_entities( + self, + request: language_service.AnalyzeEntitiesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnalyzeEntitiesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_entities + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_entities( + self, response: language_service.AnalyzeEntitiesResponse + ) -> language_service.AnalyzeEntitiesResponse: + """Post-rpc interceptor for analyze_entities + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_analyze_entity_sentiment( + self, + request: language_service.AnalyzeEntitySentimentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + language_service.AnalyzeEntitySentimentRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for analyze_entity_sentiment + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_entity_sentiment( + self, response: language_service.AnalyzeEntitySentimentResponse + ) -> language_service.AnalyzeEntitySentimentResponse: + """Post-rpc interceptor for analyze_entity_sentiment + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_analyze_sentiment( + self, + request: language_service.AnalyzeSentimentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnalyzeSentimentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_sentiment + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_sentiment( + self, response: language_service.AnalyzeSentimentResponse + ) -> language_service.AnalyzeSentimentResponse: + """Post-rpc interceptor for analyze_sentiment + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_analyze_syntax( + self, + request: language_service.AnalyzeSyntaxRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnalyzeSyntaxRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_syntax + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_analyze_syntax( + self, response: language_service.AnalyzeSyntaxResponse + ) -> language_service.AnalyzeSyntaxResponse: + """Post-rpc interceptor for analyze_syntax + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_annotate_text( + self, + request: language_service.AnnotateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.AnnotateTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for annotate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_annotate_text( + self, response: language_service.AnnotateTextResponse + ) -> language_service.AnnotateTextResponse: + """Post-rpc interceptor for annotate_text + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + def pre_classify_text( + self, + request: language_service.ClassifyTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.ClassifyTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for classify_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_classify_text( + self, response: language_service.ClassifyTextResponse + ) -> language_service.ClassifyTextResponse: + """Post-rpc interceptor for classify_text + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class LanguageServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LanguageServiceRestInterceptor + + +class LanguageServiceRestTransport(LanguageServiceTransport): + """REST backend transport for LanguageService. + + Provides text analysis operations such as sentiment analysis + and entity recognition. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "language.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[LanguageServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or LanguageServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AnalyzeEntities(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeEntities") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeEntitiesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeEntitiesResponse: + r"""Call the analyze entities method over HTTP. + + Args: + request (~.language_service.AnalyzeEntitiesRequest): + The request object. The entity analysis request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeEntitiesResponse: + The entity analysis response message. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta2/documents:analyzeEntities", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_entities( + request, metadata + ) + pb_request = language_service.AnalyzeEntitiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeEntitiesResponse() + pb_resp = language_service.AnalyzeEntitiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_entities(resp) + return resp + + class _AnalyzeEntitySentiment(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeEntitySentiment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeEntitySentimentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeEntitySentimentResponse: + r"""Call the analyze entity sentiment method over HTTP. + + Args: + request (~.language_service.AnalyzeEntitySentimentRequest): + The request object. The entity-level sentiment analysis + request message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeEntitySentimentResponse: + The entity-level sentiment analysis + response message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta2/documents:analyzeEntitySentiment", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_entity_sentiment( + request, metadata + ) + pb_request = language_service.AnalyzeEntitySentimentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeEntitySentimentResponse() + pb_resp = language_service.AnalyzeEntitySentimentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_entity_sentiment(resp) + return resp + + class _AnalyzeSentiment(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeSentiment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeSentimentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeSentimentResponse: + r"""Call the analyze sentiment method over HTTP. + + Args: + request (~.language_service.AnalyzeSentimentRequest): + The request object. The sentiment analysis request + message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeSentimentResponse: + The sentiment analysis response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta2/documents:analyzeSentiment", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_sentiment( + request, metadata + ) + pb_request = language_service.AnalyzeSentimentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeSentimentResponse() + pb_resp = language_service.AnalyzeSentimentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_sentiment(resp) + return resp + + class _AnalyzeSyntax(LanguageServiceRestStub): + def __hash__(self): + return hash("AnalyzeSyntax") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnalyzeSyntaxRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnalyzeSyntaxResponse: + r"""Call the analyze syntax method over HTTP. + + Args: + request (~.language_service.AnalyzeSyntaxRequest): + The request object. The syntax analysis request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnalyzeSyntaxResponse: + The syntax analysis response message. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta2/documents:analyzeSyntax", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_analyze_syntax(request, metadata) + pb_request = language_service.AnalyzeSyntaxRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnalyzeSyntaxResponse() + pb_resp = language_service.AnalyzeSyntaxResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_syntax(resp) + return resp + + class _AnnotateText(LanguageServiceRestStub): + def __hash__(self): + return hash("AnnotateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.AnnotateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.AnnotateTextResponse: + r"""Call the annotate text method over HTTP. + + Args: + request (~.language_service.AnnotateTextRequest): + The request object. The request message for the text + annotation API, which can perform + multiple analysis types (sentiment, + entities, and syntax) in one call. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.AnnotateTextResponse: + The text annotations response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta2/documents:annotateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_annotate_text(request, metadata) + pb_request = language_service.AnnotateTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.AnnotateTextResponse() + pb_resp = language_service.AnnotateTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_annotate_text(resp) + return resp + + class _ClassifyText(LanguageServiceRestStub): + def __hash__(self): + return hash("ClassifyText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.ClassifyTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ClassifyTextResponse: + r"""Call the classify text method over HTTP. + + Args: + request (~.language_service.ClassifyTextRequest): + The request object. The document classification request + message. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.ClassifyTextResponse: + The document classification response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta2/documents:classifyText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_classify_text(request, metadata) + pb_request = language_service.ClassifyTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.ClassifyTextResponse() + pb_resp = language_service.ClassifyTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_classify_text(resp) + return resp + + @property + def analyze_entities( + self, + ) -> Callable[ + [language_service.AnalyzeEntitiesRequest], + language_service.AnalyzeEntitiesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeEntities(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_entity_sentiment( + self, + ) -> Callable[ + [language_service.AnalyzeEntitySentimentRequest], + language_service.AnalyzeEntitySentimentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeEntitySentiment(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_sentiment( + self, + ) -> Callable[ + [language_service.AnalyzeSentimentRequest], + language_service.AnalyzeSentimentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeSentiment(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_syntax( + self, + ) -> Callable[ + [language_service.AnalyzeSyntaxRequest], language_service.AnalyzeSyntaxResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnalyzeSyntax(self._session, self._host, self._interceptor) # type: ignore + + @property + def annotate_text( + self, + ) -> Callable[ + [language_service.AnnotateTextRequest], language_service.AnnotateTextResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AnnotateText(self._session, self._host, self._interceptor) # type: ignore + + @property + def classify_text( + self, + ) -> Callable[ + [language_service.ClassifyTextRequest], language_service.ClassifyTextResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ClassifyText(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("LanguageServiceRestTransport",) diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 2e656801..4904c456 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,11 +33,14 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.language_v1.services.language_service import ( LanguageServiceAsyncClient, @@ -94,6 +99,7 @@ def test__get_default_mtls_endpoint(): [ (LanguageServiceClient, "grpc"), (LanguageServiceAsyncClient, "grpc_asyncio"), + (LanguageServiceClient, "rest"), ], ) def test_language_service_client_from_service_account_info( @@ -109,7 +115,11 @@ def test_language_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("language.googleapis.com:443") + assert client.transport._host == ( + "language.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com" + ) @pytest.mark.parametrize( @@ -117,6 +127,7 @@ def test_language_service_client_from_service_account_info( [ (transports.LanguageServiceGrpcTransport, "grpc"), (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LanguageServiceRestTransport, "rest"), ], ) def test_language_service_client_service_account_always_use_jwt( @@ -142,6 +153,7 @@ def test_language_service_client_service_account_always_use_jwt( [ (LanguageServiceClient, "grpc"), (LanguageServiceAsyncClient, "grpc_asyncio"), + (LanguageServiceClient, "rest"), ], ) def test_language_service_client_from_service_account_file( @@ -164,13 +176,18 @@ def test_language_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("language.googleapis.com:443") + assert client.transport._host == ( + "language.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com" + ) def test_language_service_client_get_transport_class(): transport = LanguageServiceClient.get_transport_class() available_transports = [ transports.LanguageServiceGrpcTransport, + transports.LanguageServiceRestTransport, ] assert transport in available_transports @@ -187,6 +204,7 @@ def test_language_service_client_get_transport_class(): transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -342,6 +360,18 @@ def test_language_service_client_client_options( "grpc_asyncio", "false", ), + ( + LanguageServiceClient, + transports.LanguageServiceRestTransport, + "rest", + "true", + ), + ( + LanguageServiceClient, + transports.LanguageServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -541,6 +571,7 @@ def test_language_service_client_get_mtls_endpoint_and_cert_source(client_class) transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), ], ) def test_language_service_client_client_options_scopes( @@ -581,6 +612,7 @@ def test_language_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest", None), ], ) def test_language_service_client_client_options_credentials_file( @@ -1871,186 +1903,1809 @@ async def test_annotate_text_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LanguageServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeSentimentRequest, + dict, + ], +) +def test_analyze_sentiment_rest(request_type): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSentimentResponse( + language="language_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_sentiment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeSentimentResponse) + assert response.language == "language_value" + + +def test_analyze_sentiment_rest_required_fields( + request_type=language_service.AnalyzeSentimentRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.LanguageServiceGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSentimentResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_sentiment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_sentiment_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + unset_fields = transport.analyze_sentiment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) - # It is an error to provide scopes and a transport instance. - transport = transports.LanguageServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_sentiment_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_sentiment" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_sentiment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeSentimentRequest.pb( + language_service.AnalyzeSentimentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnalyzeSentimentResponse.to_json( + language_service.AnalyzeSentimentResponse() ) + request = language_service.AnalyzeSentimentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeSentimentResponse() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( + client.analyze_sentiment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_sentiment_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeSentimentRequest +): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = LanguageServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_sentiment(request) + + +def test_analyze_sentiment_rest_flattened(): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.LanguageServiceGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSentimentResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_sentiment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/documents:analyzeSentiment" % client.transport._host, args[1] + ) + + +def test_analyze_sentiment_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_sentiment( + language_service.AnalyzeSentimentRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_analyze_sentiment_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + language_service.AnalyzeEntitiesRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = LanguageServiceClient.get_transport_class(transport_name)( +def test_analyze_entities_rest(request_type): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitiesResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_entities(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeEntitiesResponse) + assert response.language == "language_value" + + +def test_analyze_entities_rest_required_fields( + request_type=language_service.AnalyzeEntitiesRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entities._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entities._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.LanguageServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitiesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_entities(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_entities_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.analyze_entities._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) -def test_language_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_entities_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_entities" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_entities" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeEntitiesRequest.pb( + language_service.AnalyzeEntitiesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnalyzeEntitiesResponse.to_json( + language_service.AnalyzeEntitiesResponse() ) + request = language_service.AnalyzeEntitiesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeEntitiesResponse() -def test_language_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.language_v1.services.language_service.transports.LanguageServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.analyze_entities( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "analyze_sentiment", - "analyze_entities", - "analyze_entity_sentiment", - "analyze_syntax", - "classify_text", - "annotate_text", + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_entities_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeEntitiesRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_entities(request) -def test_language_service_base_transport_with_credentials_file(): - # 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.language_v1.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport( - 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-language", - "https://www.googleapis.com/auth/cloud-platform", - ), +def test_analyze_entities_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitiesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_entities(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/documents:analyzeEntities" % client.transport._host, args[1] + ) + + +def test_analyze_entities_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_entities( + language_service.AnalyzeEntitiesRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_analyze_entities_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeEntitySentimentRequest, + dict, + ], +) +def test_analyze_entity_sentiment_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitySentimentResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_entity_sentiment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) + assert response.language == "language_value" + + +def test_analyze_entity_sentiment_rest_required_fields( + request_type=language_service.AnalyzeEntitySentimentRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitySentimentResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_entity_sentiment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_entity_sentiment_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.analyze_entity_sentiment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_entity_sentiment_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_entity_sentiment" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_entity_sentiment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeEntitySentimentRequest.pb( + language_service.AnalyzeEntitySentimentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + language_service.AnalyzeEntitySentimentResponse.to_json( + language_service.AnalyzeEntitySentimentResponse() + ) + ) + + request = language_service.AnalyzeEntitySentimentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeEntitySentimentResponse() + + client.analyze_entity_sentiment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_entity_sentiment_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeEntitySentimentRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_entity_sentiment(request) + + +def test_analyze_entity_sentiment_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitySentimentResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_entity_sentiment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/documents:analyzeEntitySentiment" % client.transport._host, args[1] + ) + + +def test_analyze_entity_sentiment_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_entity_sentiment( + language_service.AnalyzeEntitySentimentRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_analyze_entity_sentiment_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeSyntaxRequest, + dict, + ], +) +def test_analyze_syntax_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSyntaxResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_syntax(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeSyntaxResponse) + assert response.language == "language_value" + + +def test_analyze_syntax_rest_required_fields( + request_type=language_service.AnalyzeSyntaxRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_syntax._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_syntax._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSyntaxResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_syntax(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_syntax_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.analyze_syntax._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_syntax_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_syntax" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_syntax" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeSyntaxRequest.pb( + language_service.AnalyzeSyntaxRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnalyzeSyntaxResponse.to_json( + language_service.AnalyzeSyntaxResponse() + ) + + request = language_service.AnalyzeSyntaxRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeSyntaxResponse() + + client.analyze_syntax( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_syntax_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeSyntaxRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_syntax(request) + + +def test_analyze_syntax_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSyntaxResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_syntax(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/documents:analyzeSyntax" % client.transport._host, args[1] + ) + + +def test_analyze_syntax_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_syntax( + language_service.AnalyzeSyntaxRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_analyze_syntax_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.ClassifyTextRequest, + dict, + ], +) +def test_classify_text_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ClassifyTextResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ClassifyTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.classify_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ClassifyTextResponse) + + +def test_classify_text_rest_required_fields( + request_type=language_service.ClassifyTextRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).classify_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).classify_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.ClassifyTextResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.ClassifyTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.classify_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_classify_text_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.classify_text._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_classify_text_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_classify_text" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_classify_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.ClassifyTextRequest.pb( + language_service.ClassifyTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.ClassifyTextResponse.to_json( + language_service.ClassifyTextResponse() + ) + + request = language_service.ClassifyTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.ClassifyTextResponse() + + client.classify_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_classify_text_rest_bad_request( + transport: str = "rest", request_type=language_service.ClassifyTextRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.classify_text(request) + + +def test_classify_text_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ClassifyTextResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ClassifyTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.classify_text(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/documents:classifyText" % client.transport._host, args[1] + ) + + +def test_classify_text_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.classify_text( + language_service.ClassifyTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + +def test_classify_text_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnnotateTextRequest, + dict, + ], +) +def test_annotate_text_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnnotateTextResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnnotateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.annotate_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnnotateTextResponse) + assert response.language == "language_value" + + +def test_annotate_text_rest_required_fields( + request_type=language_service.AnnotateTextRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).annotate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).annotate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnnotateTextResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnnotateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.annotate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_annotate_text_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.annotate_text._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "document", + "features", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_annotate_text_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_annotate_text" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_annotate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnnotateTextRequest.pb( + language_service.AnnotateTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnnotateTextResponse.to_json( + language_service.AnnotateTextResponse() + ) + + request = language_service.AnnotateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnnotateTextResponse() + + client.annotate_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_annotate_text_rest_bad_request( + transport: str = "rest", request_type=language_service.AnnotateTextRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.annotate_text(request) + + +def test_annotate_text_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnnotateTextResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + features=language_service.AnnotateTextRequest.Features(extract_syntax=True), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnnotateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.annotate_text(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/documents:annotateText" % client.transport._host, args[1] + ) + + +def test_annotate_text_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_text( + language_service.AnnotateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + features=language_service.AnnotateTextRequest.Features(extract_syntax=True), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_annotate_text_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LanguageServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LanguageServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + transports.LanguageServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = LanguageServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LanguageServiceGrpcTransport, + ) + + +def test_language_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LanguageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_language_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.language_v1.services.language_service.transports.LanguageServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.LanguageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "analyze_sentiment", + "analyze_entities", + "analyze_entity_sentiment", + "analyze_syntax", + "classify_text", + "annotate_text", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_language_service_base_transport_with_credentials_file(): + # 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.language_v1.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LanguageServiceTransport( + 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-language", + "https://www.googleapis.com/auth/cloud-platform", + ), quota_project_id="octopus", ) @@ -2109,6 +3764,7 @@ def test_language_service_transport_auth_adc(transport_class): [ transports.LanguageServiceGrpcTransport, transports.LanguageServiceGrpcAsyncIOTransport, + transports.LanguageServiceRestTransport, ], ) def test_language_service_transport_auth_gdch_credentials(transport_class): @@ -2209,11 +3865,23 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c ) +def test_language_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.LanguageServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_language_service_host_no_port(transport_name): @@ -2224,7 +3892,11 @@ def test_language_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("language.googleapis.com:443") + assert client.transport._host == ( + "language.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com" + ) @pytest.mark.parametrize( @@ -2232,6 +3904,7 @@ def test_language_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_language_service_host_with_port(transport_name): @@ -2242,7 +3915,48 @@ def test_language_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("language.googleapis.com:8000") + assert client.transport._host == ( + "language.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_language_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LanguageServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LanguageServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.analyze_sentiment._session + session2 = client2.transport.analyze_sentiment._session + assert session1 != session2 + session1 = client1.transport.analyze_entities._session + session2 = client2.transport.analyze_entities._session + assert session1 != session2 + session1 = client1.transport.analyze_entity_sentiment._session + session2 = client2.transport.analyze_entity_sentiment._session + assert session1 != session2 + session1 = client1.transport.analyze_syntax._session + session2 = client2.transport.analyze_syntax._session + assert session1 != session2 + session1 = client1.transport.classify_text._session + session2 = client2.transport.classify_text._session + assert session1 != session2 + session1 = client1.transport.annotate_text._session + session2 = client2.transport.annotate_text._session + assert session1 != session2 def test_language_service_grpc_transport_channel(): @@ -2513,6 +4227,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2530,6 +4245,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index ae913b69..809ce0e0 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,11 +33,14 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.language_v1beta2.services.language_service import ( LanguageServiceAsyncClient, @@ -94,6 +99,7 @@ def test__get_default_mtls_endpoint(): [ (LanguageServiceClient, "grpc"), (LanguageServiceAsyncClient, "grpc_asyncio"), + (LanguageServiceClient, "rest"), ], ) def test_language_service_client_from_service_account_info( @@ -109,7 +115,11 @@ def test_language_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("language.googleapis.com:443") + assert client.transport._host == ( + "language.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com" + ) @pytest.mark.parametrize( @@ -117,6 +127,7 @@ def test_language_service_client_from_service_account_info( [ (transports.LanguageServiceGrpcTransport, "grpc"), (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LanguageServiceRestTransport, "rest"), ], ) def test_language_service_client_service_account_always_use_jwt( @@ -142,6 +153,7 @@ def test_language_service_client_service_account_always_use_jwt( [ (LanguageServiceClient, "grpc"), (LanguageServiceAsyncClient, "grpc_asyncio"), + (LanguageServiceClient, "rest"), ], ) def test_language_service_client_from_service_account_file( @@ -164,13 +176,18 @@ def test_language_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("language.googleapis.com:443") + assert client.transport._host == ( + "language.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com" + ) def test_language_service_client_get_transport_class(): transport = LanguageServiceClient.get_transport_class() available_transports = [ transports.LanguageServiceGrpcTransport, + transports.LanguageServiceRestTransport, ] assert transport in available_transports @@ -187,6 +204,7 @@ def test_language_service_client_get_transport_class(): transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -342,6 +360,18 @@ def test_language_service_client_client_options( "grpc_asyncio", "false", ), + ( + LanguageServiceClient, + transports.LanguageServiceRestTransport, + "rest", + "true", + ), + ( + LanguageServiceClient, + transports.LanguageServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -541,6 +571,7 @@ def test_language_service_client_get_mtls_endpoint_and_cert_source(client_class) transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), ], ) def test_language_service_client_client_options_scopes( @@ -581,6 +612,7 @@ def test_language_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest", None), ], ) def test_language_service_client_client_options_credentials_file( @@ -1871,186 +1903,1810 @@ async def test_annotate_text_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LanguageServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeSentimentRequest, + dict, + ], +) +def test_analyze_sentiment_rest(request_type): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSentimentResponse( + language="language_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_sentiment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeSentimentResponse) + assert response.language == "language_value" + + +def test_analyze_sentiment_rest_required_fields( + request_type=language_service.AnalyzeSentimentRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.LanguageServiceGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSentimentResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_sentiment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_sentiment_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + unset_fields = transport.analyze_sentiment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) - # It is an error to provide scopes and a transport instance. - transport = transports.LanguageServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_sentiment_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_sentiment" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_sentiment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeSentimentRequest.pb( + language_service.AnalyzeSentimentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnalyzeSentimentResponse.to_json( + language_service.AnalyzeSentimentResponse() ) + request = language_service.AnalyzeSentimentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeSentimentResponse() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( + client.analyze_sentiment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_sentiment_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeSentimentRequest +): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = LanguageServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_sentiment(request) + + +def test_analyze_sentiment_rest_flattened(): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.LanguageServiceGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSentimentResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_sentiment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta2/documents:analyzeSentiment" % client.transport._host, args[1] + ) + + +def test_analyze_sentiment_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_sentiment( + language_service.AnalyzeSentimentRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_analyze_sentiment_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + language_service.AnalyzeEntitiesRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = LanguageServiceClient.get_transport_class(transport_name)( +def test_analyze_entities_rest(request_type): + client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitiesResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_entities(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeEntitiesResponse) + assert response.language == "language_value" + + +def test_analyze_entities_rest_required_fields( + request_type=language_service.AnalyzeEntitiesRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entities._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entities._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = LanguageServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.LanguageServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitiesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_entities(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_entities_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.analyze_entities._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) -def test_language_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_entities_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_entities" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_entities" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeEntitiesRequest.pb( + language_service.AnalyzeEntitiesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnalyzeEntitiesResponse.to_json( + language_service.AnalyzeEntitiesResponse() ) + request = language_service.AnalyzeEntitiesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeEntitiesResponse() -def test_language_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.language_v1beta2.services.language_service.transports.LanguageServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.analyze_entities( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "analyze_sentiment", - "analyze_entities", - "analyze_entity_sentiment", - "analyze_syntax", - "classify_text", - "annotate_text", + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_entities_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeEntitiesRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_entities(request) -def test_language_service_base_transport_with_credentials_file(): - # 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.language_v1beta2.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport( - 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-language", - "https://www.googleapis.com/auth/cloud-platform", - ), +def test_analyze_entities_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitiesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_entities(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta2/documents:analyzeEntities" % client.transport._host, args[1] + ) + + +def test_analyze_entities_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_entities( + language_service.AnalyzeEntitiesRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_analyze_entities_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeEntitySentimentRequest, + dict, + ], +) +def test_analyze_entity_sentiment_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitySentimentResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_entity_sentiment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) + assert response.language == "language_value" + + +def test_analyze_entity_sentiment_rest_required_fields( + request_type=language_service.AnalyzeEntitySentimentRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitySentimentResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_entity_sentiment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_entity_sentiment_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.analyze_entity_sentiment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_entity_sentiment_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_entity_sentiment" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_entity_sentiment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeEntitySentimentRequest.pb( + language_service.AnalyzeEntitySentimentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + language_service.AnalyzeEntitySentimentResponse.to_json( + language_service.AnalyzeEntitySentimentResponse() + ) + ) + + request = language_service.AnalyzeEntitySentimentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeEntitySentimentResponse() + + client.analyze_entity_sentiment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_entity_sentiment_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeEntitySentimentRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_entity_sentiment(request) + + +def test_analyze_entity_sentiment_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeEntitySentimentResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_entity_sentiment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta2/documents:analyzeEntitySentiment" % client.transport._host, + args[1], + ) + + +def test_analyze_entity_sentiment_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_entity_sentiment( + language_service.AnalyzeEntitySentimentRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_analyze_entity_sentiment_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnalyzeSyntaxRequest, + dict, + ], +) +def test_analyze_syntax_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSyntaxResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.analyze_syntax(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnalyzeSyntaxResponse) + assert response.language == "language_value" + + +def test_analyze_syntax_rest_required_fields( + request_type=language_service.AnalyzeSyntaxRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_syntax._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).analyze_syntax._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSyntaxResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.analyze_syntax(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_analyze_syntax_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.analyze_syntax._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_syntax_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_analyze_syntax" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_analyze_syntax" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnalyzeSyntaxRequest.pb( + language_service.AnalyzeSyntaxRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnalyzeSyntaxResponse.to_json( + language_service.AnalyzeSyntaxResponse() + ) + + request = language_service.AnalyzeSyntaxRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnalyzeSyntaxResponse() + + client.analyze_syntax( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_syntax_rest_bad_request( + transport: str = "rest", request_type=language_service.AnalyzeSyntaxRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.analyze_syntax(request) + + +def test_analyze_syntax_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnalyzeSyntaxResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.analyze_syntax(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta2/documents:analyzeSyntax" % client.transport._host, args[1] + ) + + +def test_analyze_syntax_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.analyze_syntax( + language_service.AnalyzeSyntaxRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_analyze_syntax_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.ClassifyTextRequest, + dict, + ], +) +def test_classify_text_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ClassifyTextResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ClassifyTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.classify_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ClassifyTextResponse) + + +def test_classify_text_rest_required_fields( + request_type=language_service.ClassifyTextRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).classify_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).classify_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.ClassifyTextResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.ClassifyTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.classify_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_classify_text_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.classify_text._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_classify_text_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_classify_text" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_classify_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.ClassifyTextRequest.pb( + language_service.ClassifyTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.ClassifyTextResponse.to_json( + language_service.ClassifyTextResponse() + ) + + request = language_service.ClassifyTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.ClassifyTextResponse() + + client.classify_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_classify_text_rest_bad_request( + transport: str = "rest", request_type=language_service.ClassifyTextRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.classify_text(request) + + +def test_classify_text_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ClassifyTextResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ClassifyTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.classify_text(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta2/documents:classifyText" % client.transport._host, args[1] + ) + + +def test_classify_text_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.classify_text( + language_service.ClassifyTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + +def test_classify_text_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + language_service.AnnotateTextRequest, + dict, + ], +) +def test_annotate_text_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnnotateTextResponse( + language="language_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnnotateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.annotate_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.AnnotateTextResponse) + assert response.language == "language_value" + + +def test_annotate_text_rest_required_fields( + request_type=language_service.AnnotateTextRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).annotate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).annotate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.AnnotateTextResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.AnnotateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.annotate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_annotate_text_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.annotate_text._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "document", + "features", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_annotate_text_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_annotate_text" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_annotate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.AnnotateTextRequest.pb( + language_service.AnnotateTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.AnnotateTextResponse.to_json( + language_service.AnnotateTextResponse() + ) + + request = language_service.AnnotateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.AnnotateTextResponse() + + client.annotate_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_annotate_text_rest_bad_request( + transport: str = "rest", request_type=language_service.AnnotateTextRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.annotate_text(request) + + +def test_annotate_text_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.AnnotateTextResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + features=language_service.AnnotateTextRequest.Features(extract_syntax=True), + encoding_type=language_service.EncodingType.UTF8, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.AnnotateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.annotate_text(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta2/documents:annotateText" % client.transport._host, args[1] + ) + + +def test_annotate_text_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_text( + language_service.AnnotateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + features=language_service.AnnotateTextRequest.Features(extract_syntax=True), + encoding_type=language_service.EncodingType.UTF8, + ) + + +def test_annotate_text_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LanguageServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LanguageServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LanguageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LanguageServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LanguageServiceGrpcTransport, + transports.LanguageServiceGrpcAsyncIOTransport, + transports.LanguageServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = LanguageServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LanguageServiceGrpcTransport, + ) + + +def test_language_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LanguageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_language_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.language_v1beta2.services.language_service.transports.LanguageServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.LanguageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "analyze_sentiment", + "analyze_entities", + "analyze_entity_sentiment", + "analyze_syntax", + "classify_text", + "annotate_text", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_language_service_base_transport_with_credentials_file(): + # 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.language_v1beta2.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LanguageServiceTransport( + 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-language", + "https://www.googleapis.com/auth/cloud-platform", + ), quota_project_id="octopus", ) @@ -2109,6 +3765,7 @@ def test_language_service_transport_auth_adc(transport_class): [ transports.LanguageServiceGrpcTransport, transports.LanguageServiceGrpcAsyncIOTransport, + transports.LanguageServiceRestTransport, ], ) def test_language_service_transport_auth_gdch_credentials(transport_class): @@ -2209,11 +3866,23 @@ def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_c ) +def test_language_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.LanguageServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_language_service_host_no_port(transport_name): @@ -2224,7 +3893,11 @@ def test_language_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("language.googleapis.com:443") + assert client.transport._host == ( + "language.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com" + ) @pytest.mark.parametrize( @@ -2232,6 +3905,7 @@ def test_language_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_language_service_host_with_port(transport_name): @@ -2242,7 +3916,48 @@ def test_language_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("language.googleapis.com:8000") + assert client.transport._host == ( + "language.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://language.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_language_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LanguageServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LanguageServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.analyze_sentiment._session + session2 = client2.transport.analyze_sentiment._session + assert session1 != session2 + session1 = client1.transport.analyze_entities._session + session2 = client2.transport.analyze_entities._session + assert session1 != session2 + session1 = client1.transport.analyze_entity_sentiment._session + session2 = client2.transport.analyze_entity_sentiment._session + assert session1 != session2 + session1 = client1.transport.analyze_syntax._session + session2 = client2.transport.analyze_syntax._session + assert session1 != session2 + session1 = client1.transport.classify_text._session + session2 = client2.transport.classify_text._session + assert session1 != session2 + session1 = client1.transport.annotate_text._session + session2 = client2.transport.annotate_text._session + assert session1 != session2 def test_language_service_grpc_transport_channel(): @@ -2513,6 +4228,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2530,6 +4246,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: From d4a7d689ba49061ad89bba886235e96aa8695208 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 16 Feb 2023 15:21:36 -0500 Subject: [PATCH 240/254] chore(main): release 2.9.0 (#424) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ google/cloud/language/gapic_version.py | 2 +- google/cloud/language_v1/gapic_version.py | 2 +- google/cloud/language_v1beta2/gapic_version.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- 7 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9c62c130..6bb50d96 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.8.1" + ".": "2.9.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ec4d2ff..d2c09dd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.9.0](https://github.com/googleapis/python-language/compare/v2.8.1...v2.9.0) (2023-02-16) + + +### Features + +* Enable "rest" transport in Python for services supporting numeric enums ([#423](https://github.com/googleapis/python-language/issues/423)) ([21c09b8](https://github.com/googleapis/python-language/commit/21c09b8e009a560c77d96f8fa92c5e91cfdad29f)) + ## [2.8.1](https://github.com/googleapis/python-language/compare/v2.8.0...v2.8.1) (2023-01-20) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index 15e84ffd..60aeb18d 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.8.1" # {x-release-please-version} +__version__ = "2.9.0" # {x-release-please-version} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py index 15e84ffd..60aeb18d 100644 --- a/google/cloud/language_v1/gapic_version.py +++ b/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.8.1" # {x-release-please-version} +__version__ = "2.9.0" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py index 15e84ffd..60aeb18d 100644 --- a/google/cloud/language_v1beta2/gapic_version.py +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.8.1" # {x-release-please-version} +__version__ = "2.9.0" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 936a8b70..49ffe084 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.9.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index a4368f2d..f84b1cfc 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.9.0" }, "snippets": [ { From e8c4463c704edd0e5d80bb191a73ec4f5e56d795 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 27 Feb 2023 16:36:18 +0000 Subject: [PATCH 241/254] chore(python): upgrade gcp-releasetool in .kokoro [autoapprove] (#427) Source-Link: https://togithub.com/googleapis/synthtool/commit/5f2a6089f73abf06238fe4310f6a14d6f6d1eed3 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:8555f0e37e6261408f792bfd6635102d2da5ad73f8f09bcb24f25e6afb5fac97 --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/requirements.in | 2 +- .kokoro/requirements.txt | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 894fb6bc..5fc5daa3 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf + digest: sha256:8555f0e37e6261408f792bfd6635102d2da5ad73f8f09bcb24f25e6afb5fac97 diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in index cbd7e77f..882178ce 100644 --- a/.kokoro/requirements.in +++ b/.kokoro/requirements.in @@ -1,5 +1,5 @@ gcp-docuploader -gcp-releasetool +gcp-releasetool>=1.10.5 # required for compatibility with cryptography>=39.x importlib-metadata typing-extensions twine diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 096e4800..fa99c129 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -154,9 +154,9 @@ gcp-docuploader==0.6.4 \ --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf # via -r requirements.in -gcp-releasetool==1.10.0 \ - --hash=sha256:72a38ca91b59c24f7e699e9227c90cbe4dd71b789383cb0164b088abae294c83 \ - --hash=sha256:8c7c99320208383d4bb2b808c6880eb7a81424afe7cdba3c8d84b25f4f0e097d +gcp-releasetool==1.10.5 \ + --hash=sha256:174b7b102d704b254f2a26a3eda2c684fd3543320ec239baf771542a2e58e109 \ + --hash=sha256:e29d29927fe2ca493105a82958c6873bb2b90d503acac56be2c229e74de0eec9 # via -r requirements.in google-api-core==2.10.2 \ --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ From 8fd465593144b3335245194fbf432ec8e6c46399 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 28 Feb 2023 06:07:44 -0500 Subject: [PATCH 242/254] chore: Update gapic-generator-python to v1.8.5 (#426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.5 PiperOrigin-RevId: 511892190 Source-Link: https://github.com/googleapis/googleapis/commit/a45d9c09c1287ffdf938f4e8083e791046c0b23b Source-Link: https://github.com/googleapis/googleapis-gen/commit/1907294b1d8365ea24f8c5f2e059a64124c4ed3b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMTkwNzI5NGIxZDgzNjVlYTI0ZjhjNWYyZTA1OWE2NDEyNGM0ZWQzYiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .../services/language_service/transports/rest.py | 14 +++++++------- google/cloud/language_v1/types/language_service.py | 2 ++ .../services/language_service/transports/rest.py | 14 +++++++------- .../language_v1beta2/types/language_service.py | 2 ++ .../snippet_metadata_google.cloud.language.v1.json | 2 +- ...pet_metadata_google.cloud.language.v1beta2.json | 2 +- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/transports/rest.py b/google/cloud/language_v1/services/language_service/transports/rest.py index e9b0585f..8fc0f295 100644 --- a/google/cloud/language_v1/services/language_service/transports/rest.py +++ b/google/cloud/language_v1/services/language_service/transports/rest.py @@ -17,7 +17,7 @@ import dataclasses import json # type: ignore import re -from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming @@ -359,7 +359,7 @@ class _AnalyzeEntities(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeEntities") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -456,7 +456,7 @@ class _AnalyzeEntitySentiment(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeEntitySentiment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -557,7 +557,7 @@ class _AnalyzeSentiment(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeSentiment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -658,7 +658,7 @@ class _AnalyzeSyntax(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeSyntax") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -753,7 +753,7 @@ class _AnnotateText(LanguageServiceRestStub): def __hash__(self): return hash("AnnotateText") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -854,7 +854,7 @@ class _ClassifyText(LanguageServiceRestStub): def __hash__(self): return hash("ClassifyText") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index 6eb54e90..bd330ffe 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/language_v1beta2/services/language_service/transports/rest.py b/google/cloud/language_v1beta2/services/language_service/transports/rest.py index 6ab75ba5..b9e3f2c2 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/rest.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/rest.py @@ -17,7 +17,7 @@ import dataclasses import json # type: ignore import re -from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming @@ -359,7 +359,7 @@ class _AnalyzeEntities(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeEntities") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -456,7 +456,7 @@ class _AnalyzeEntitySentiment(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeEntitySentiment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -557,7 +557,7 @@ class _AnalyzeSentiment(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeSentiment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -658,7 +658,7 @@ class _AnalyzeSyntax(LanguageServiceRestStub): def __hash__(self): return hash("AnalyzeSyntax") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -753,7 +753,7 @@ class _AnnotateText(LanguageServiceRestStub): def __hash__(self): return hash("AnnotateText") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -854,7 +854,7 @@ class _ClassifyText(LanguageServiceRestStub): def __hash__(self): return hash("ClassifyText") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index cd661423..884a1512 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 49ffe084..936a8b70 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.9.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index f84b1cfc..a4368f2d 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.9.0" + "version": "0.1.0" }, "snippets": [ { From a65c85d4aad2ed06f99568286f6529259c83f3dc Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 16 Mar 2023 11:48:13 +0000 Subject: [PATCH 243/254] chore(deps): Update nox in .kokoro/requirements.in [autoapprove] (#428) Source-Link: https://togithub.com/googleapis/synthtool/commit/92006bb3cdc84677aa93c7f5235424ec2b157146 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:2e247c7bf5154df7f98cce087a20ca7605e236340c7d6d1a14447e5c06791bd6 --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/requirements.in | 2 +- .kokoro/requirements.txt | 14 +++++--------- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 5fc5daa3..b8edda51 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:8555f0e37e6261408f792bfd6635102d2da5ad73f8f09bcb24f25e6afb5fac97 + digest: sha256:2e247c7bf5154df7f98cce087a20ca7605e236340c7d6d1a14447e5c06791bd6 diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in index 882178ce..ec867d9f 100644 --- a/.kokoro/requirements.in +++ b/.kokoro/requirements.in @@ -5,6 +5,6 @@ typing-extensions twine wheel setuptools -nox +nox>=2022.11.21 # required to remove dependency on py charset-normalizer<3 click<8.1.0 diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index fa99c129..66a2172a 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -1,6 +1,6 @@ # -# This file is autogenerated by pip-compile with python 3.10 -# To update, run: +# This file is autogenerated by pip-compile with Python 3.9 +# by the following command: # # pip-compile --allow-unsafe --generate-hashes requirements.in # @@ -335,9 +335,9 @@ more-itertools==9.0.0 \ --hash=sha256:250e83d7e81d0c87ca6bd942e6aeab8cc9daa6096d12c5308f3f92fa5e5c1f41 \ --hash=sha256:5a6257e40878ef0520b1803990e3e22303a41b5714006c32a3fd8304b26ea1ab # via jaraco-classes -nox==2022.8.7 \ - --hash=sha256:1b894940551dc5c389f9271d197ca5d655d40bdc6ccf93ed6880e4042760a34b \ - --hash=sha256:96cca88779e08282a699d672258ec01eb7c792d35bbbf538c723172bce23212c +nox==2022.11.21 \ + --hash=sha256:0e41a990e290e274cb205a976c4c97ee3c5234441a8132c8c3fd9ea3c22149eb \ + --hash=sha256:e21c31de0711d1274ca585a2c5fde36b1aa962005ba8e9322bf5eeed16dcd684 # via -r requirements.in packaging==21.3 \ --hash=sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb \ @@ -380,10 +380,6 @@ protobuf==3.20.3 \ # gcp-docuploader # gcp-releasetool # google-api-core -py==1.11.0 \ - --hash=sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719 \ - --hash=sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378 - # via nox pyasn1==0.4.8 \ --hash=sha256:39c7e2ec30515947ff4e87fb6f456dfc6e84857d34be479c9d4a4ba4bf46aa5d \ --hash=sha256:aef77c9fb94a3ac588e87841208bdec464471d9871bd5050a287cc9a475cd0ba From 475e787aa7c2cd6a6268c2656d6d9e3cd3a76735 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 23 Mar 2023 09:30:45 -0400 Subject: [PATCH 244/254] docs: Fix formatting of request arg in docstring (#429) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: Fix formatting of request arg in docstring chore: Update gapic-generator-python to v1.9.1 PiperOrigin-RevId: 518604533 Source-Link: https://github.com/googleapis/googleapis/commit/8a085aeddfa010af5bcef090827aac5255383d7e Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2ab4b0a0ae2907e812c209198a74e0898afcb04 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJhYjRiMGEwYWUyOTA3ZTgxMmMyMDkxOThhNzRlMDg5OGFmY2IwNCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../language_v1/services/language_service/async_client.py | 5 +++-- google/cloud/language_v1/services/language_service/client.py | 5 +++-- .../language_v1/services/language_service/transports/rest.py | 4 ---- .../services/language_service/async_client.py | 5 +++-- .../language_v1beta2/services/language_service/client.py | 5 +++-- .../services/language_service/transports/rest.py | 4 ---- 6 files changed, 12 insertions(+), 16 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 605df5b5..8389f19c 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -839,8 +839,9 @@ async def sample_annotate_text(): Args: request (Optional[Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]]): The request object. The request message for the text - annotation API, which can perform multiple analysis - types (sentiment, entities, and syntax) in one call. + annotation API, which can perform + multiple analysis types (sentiment, + entities, and syntax) in one call. document (:class:`google.cloud.language_v1.types.Document`): Required. Input document. This corresponds to the ``document`` field diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index e97f3240..d79cffc5 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -998,8 +998,9 @@ def sample_annotate_text(): Args: request (Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]): The request object. The request message for the text - annotation API, which can perform multiple analysis - types (sentiment, entities, and syntax) in one call. + annotation API, which can perform + multiple analysis types (sentiment, + entities, and syntax) in one call. document (google.cloud.language_v1.types.Document): Required. Input document. This corresponds to the ``document`` field diff --git a/google/cloud/language_v1/services/language_service/transports/rest.py b/google/cloud/language_v1/services/language_service/transports/rest.py index 8fc0f295..d92e6672 100644 --- a/google/cloud/language_v1/services/language_service/transports/rest.py +++ b/google/cloud/language_v1/services/language_service/transports/rest.py @@ -480,7 +480,6 @@ def __call__( request (~.language_service.AnalyzeEntitySentimentRequest): The request object. The entity-level sentiment analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -581,7 +580,6 @@ def __call__( request (~.language_service.AnalyzeSentimentRequest): The request object. The sentiment analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -779,7 +777,6 @@ def __call__( annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -878,7 +875,6 @@ def __call__( request (~.language_service.ClassifyTextRequest): The request object. The document classification request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index d242f8df..2676da9f 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -840,8 +840,9 @@ async def sample_annotate_text(): Args: request (Optional[Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]]): The request object. The request message for the text - annotation API, which can perform multiple analysis - types (sentiment, entities, and syntax) in one call. + annotation API, which can perform + multiple analysis types (sentiment, + entities, and syntax) in one call. document (:class:`google.cloud.language_v1beta2.types.Document`): Required. Input document. This corresponds to the ``document`` field diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 613c8c88..4c45046d 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -999,8 +999,9 @@ def sample_annotate_text(): Args: request (Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]): The request object. The request message for the text - annotation API, which can perform multiple analysis - types (sentiment, entities, and syntax) in one call. + annotation API, which can perform + multiple analysis types (sentiment, + entities, and syntax) in one call. document (google.cloud.language_v1beta2.types.Document): Required. Input document. This corresponds to the ``document`` field diff --git a/google/cloud/language_v1beta2/services/language_service/transports/rest.py b/google/cloud/language_v1beta2/services/language_service/transports/rest.py index b9e3f2c2..e0821a77 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/rest.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/rest.py @@ -480,7 +480,6 @@ def __call__( request (~.language_service.AnalyzeEntitySentimentRequest): The request object. The entity-level sentiment analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -581,7 +580,6 @@ def __call__( request (~.language_service.AnalyzeSentimentRequest): The request object. The sentiment analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -779,7 +777,6 @@ def __call__( annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -878,7 +875,6 @@ def __call__( request (~.language_service.ClassifyTextRequest): The request object. The document classification request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. From 3338d05a263a608b1f64a8acc416aee1786f7b5a Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 27 Mar 2023 11:28:41 -0400 Subject: [PATCH 245/254] chore(main): release 2.9.1 (#430) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ google/cloud/language/gapic_version.py | 2 +- google/cloud/language_v1/gapic_version.py | 2 +- google/cloud/language_v1beta2/gapic_version.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- 7 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6bb50d96..13a0da6b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.9.0" + ".": "2.9.1" } diff --git a/CHANGELOG.md b/CHANGELOG.md index d2c09dd8..3244ccc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.9.1](https://github.com/googleapis/python-language/compare/v2.9.0...v2.9.1) (2023-03-23) + + +### Documentation + +* Fix formatting of request arg in docstring ([#429](https://github.com/googleapis/python-language/issues/429)) ([475e787](https://github.com/googleapis/python-language/commit/475e787aa7c2cd6a6268c2656d6d9e3cd3a76735)) + ## [2.9.0](https://github.com/googleapis/python-language/compare/v2.8.1...v2.9.0) (2023-02-16) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index 60aeb18d..18081a7d 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.9.0" # {x-release-please-version} +__version__ = "2.9.1" # {x-release-please-version} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py index 60aeb18d..18081a7d 100644 --- a/google/cloud/language_v1/gapic_version.py +++ b/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.9.0" # {x-release-please-version} +__version__ = "2.9.1" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py index 60aeb18d..18081a7d 100644 --- a/google/cloud/language_v1beta2/gapic_version.py +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.9.0" # {x-release-please-version} +__version__ = "2.9.1" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 936a8b70..9651e696 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.9.1" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index a4368f2d..6ef547cc 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.9.1" }, "snippets": [ { From 033a20bf9aee96b2cbadd15a36d520b4ec40c7ab Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 25 May 2023 10:28:52 -0400 Subject: [PATCH 246/254] feat: Add support for ModerateText (#433) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Added client library support for ModerateText in the Natural Language API (V1Beta2) PiperOrigin-RevId: 534975458 Source-Link: https://github.com/googleapis/googleapis/commit/392db1d5b03abe71647a69b28ea84b212a9978a9 Source-Link: https://github.com/googleapis/googleapis-gen/commit/df98b94b1218af16109fe3e1aef329732779c0a9 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiZGY5OGI5NGIxMjE4YWYxNjEwOWZlM2UxYWVmMzI5NzMyNzc5YzBhOSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * feat: Added client library support for ModerateText in the Natural Language API (V1) PiperOrigin-RevId: 534992604 Source-Link: https://github.com/googleapis/googleapis/commit/2400facb5e4d93de884e58d38656b707df43fffa Source-Link: https://github.com/googleapis/googleapis-gen/commit/32caa580131b05b880fa3b802ca0c21179881733 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMzJjYWE1ODAxMzFiMDViODgwZmEzYjgwMmNhMGMyMTE3OTg4MTczMyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- google/cloud/language/__init__.py | 4 + google/cloud/language_v1/__init__.py | 4 + google/cloud/language_v1/gapic_metadata.json | 15 + .../services/language_service/async_client.py | 98 ++++ .../services/language_service/client.py | 98 ++++ .../language_service/transports/base.py | 17 + .../language_service/transports/grpc.py | 29 ++ .../transports/grpc_asyncio.py | 30 ++ .../language_service/transports/rest.py | 139 ++++++ google/cloud/language_v1/types/__init__.py | 4 + .../language_v1/types/language_service.py | 57 ++- google/cloud/language_v1beta2/__init__.py | 4 + .../language_v1beta2/gapic_metadata.json | 15 + .../services/language_service/async_client.py | 98 ++++ .../services/language_service/client.py | 98 ++++ .../language_service/transports/base.py | 17 + .../language_service/transports/grpc.py | 29 ++ .../transports/grpc_asyncio.py | 30 ++ .../language_service/transports/rest.py | 139 ++++++ .../cloud/language_v1beta2/types/__init__.py | 4 + .../types/language_service.py | 59 ++- ...ed_language_service_moderate_text_async.py | 55 +++ ...ted_language_service_moderate_text_sync.py | 55 +++ ...ed_language_service_moderate_text_async.py | 55 +++ ...ted_language_service_moderate_text_sync.py | 55 +++ ...pet_metadata_google.cloud.language.v1.json | 163 ++++++- ...etadata_google.cloud.language.v1beta2.json | 163 ++++++- scripts/fixup_language_v1_keywords.py | 1 + scripts/fixup_language_v1beta2_keywords.py | 1 + .../language_v1/test_language_service.py | 444 ++++++++++++++++++ .../language_v1beta2/test_language_service.py | 444 ++++++++++++++++++ 31 files changed, 2415 insertions(+), 9 deletions(-) create mode 100644 samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py create mode 100644 samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py create mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py create mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py diff --git a/google/cloud/language/__init__.py b/google/cloud/language/__init__.py index 3e7674b2..a6faa72d 100644 --- a/google/cloud/language/__init__.py +++ b/google/cloud/language/__init__.py @@ -44,6 +44,8 @@ EncodingType, Entity, EntityMention, + ModerateTextRequest, + ModerateTextResponse, PartOfSpeech, Sentence, Sentiment, @@ -72,6 +74,8 @@ "Document", "Entity", "EntityMention", + "ModerateTextRequest", + "ModerateTextResponse", "PartOfSpeech", "Sentence", "Sentiment", diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py index 6df3e48a..166ac220 100644 --- a/google/cloud/language_v1/__init__.py +++ b/google/cloud/language_v1/__init__.py @@ -39,6 +39,8 @@ EncodingType, Entity, EntityMention, + ModerateTextRequest, + ModerateTextResponse, PartOfSpeech, Sentence, Sentiment, @@ -68,6 +70,8 @@ "Entity", "EntityMention", "LanguageServiceClient", + "ModerateTextRequest", + "ModerateTextResponse", "PartOfSpeech", "Sentence", "Sentiment", diff --git a/google/cloud/language_v1/gapic_metadata.json b/google/cloud/language_v1/gapic_metadata.json index e475aad9..fa2c065a 100644 --- a/google/cloud/language_v1/gapic_metadata.json +++ b/google/cloud/language_v1/gapic_metadata.json @@ -39,6 +39,11 @@ "methods": [ "classify_text" ] + }, + "ModerateText": { + "methods": [ + "moderate_text" + ] } } }, @@ -74,6 +79,11 @@ "methods": [ "classify_text" ] + }, + "ModerateText": { + "methods": [ + "moderate_text" + ] } } }, @@ -109,6 +119,11 @@ "methods": [ "classify_text" ] + }, + "ModerateText": { + "methods": [ + "moderate_text" + ] } } } diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 8389f19c..54fda3ae 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -792,6 +792,104 @@ async def sample_classify_text(): # Done; return the response. return response + async def moderate_text( + self, + request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, + *, + document: Optional[language_service.Document] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ModerateTextResponse: + r"""Moderates a document for harmful and sensitive + categories. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import language_v1 + + async def sample_moderate_text(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ModerateTextRequest( + document=document, + ) + + # Make the request + response = await client.moderate_text(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.language_v1.types.ModerateTextRequest, dict]]): + The request object. The document moderation request + message. + document (:class:`google.cloud.language_v1.types.Document`): + Required. Input document. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.language_v1.types.ModerateTextResponse: + The document moderation response + message. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([document]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = language_service.ModerateTextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.moderate_text, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def annotate_text( self, request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py index d79cffc5..e9b4ccec 100644 --- a/google/cloud/language_v1/services/language_service/client.py +++ b/google/cloud/language_v1/services/language_service/client.py @@ -951,6 +951,104 @@ def sample_classify_text(): # Done; return the response. return response + def moderate_text( + self, + request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, + *, + document: Optional[language_service.Document] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ModerateTextResponse: + r"""Moderates a document for harmful and sensitive + categories. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import language_v1 + + def sample_moderate_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ModerateTextRequest( + document=document, + ) + + # Make the request + response = client.moderate_text(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.language_v1.types.ModerateTextRequest, dict]): + The request object. The document moderation request + message. + document (google.cloud.language_v1.types.Document): + Required. Input document. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.language_v1.types.ModerateTextResponse: + The document moderation response + message. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([document]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a language_service.ModerateTextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, language_service.ModerateTextRequest): + request = language_service.ModerateTextRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.moderate_text] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def annotate_text( self, request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py index d8bfc5d9..c900f0af 100644 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ b/google/cloud/language_v1/services/language_service/transports/base.py @@ -200,6 +200,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.moderate_text: gapic_v1.method.wrap_method( + self.moderate_text, + default_timeout=None, + client_info=client_info, + ), self.annotate_text: gapic_v1.method.wrap_method( self.annotate_text, default_retry=retries.Retry( @@ -286,6 +291,18 @@ def classify_text( ]: raise NotImplementedError() + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], + Union[ + language_service.ModerateTextResponse, + Awaitable[language_service.ModerateTextResponse], + ], + ]: + raise NotImplementedError() + @property def annotate_text( self, diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py index f46b19fd..dd9abdb0 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc.py @@ -380,6 +380,35 @@ def classify_text( ) return self._stubs["classify_text"] + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], language_service.ModerateTextResponse + ]: + r"""Return a callable for the moderate text method over gRPC. + + Moderates a document for harmful and sensitive + categories. + + Returns: + Callable[[~.ModerateTextRequest], + ~.ModerateTextResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "moderate_text" not in self._stubs: + self._stubs["moderate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.language.v1.LanguageService/ModerateText", + request_serializer=language_service.ModerateTextRequest.serialize, + response_deserializer=language_service.ModerateTextResponse.deserialize, + ) + return self._stubs["moderate_text"] + @property def annotate_text( self, diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py index dd19f8f1..00e1ea21 100644 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py @@ -385,6 +385,36 @@ def classify_text( ) return self._stubs["classify_text"] + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], + Awaitable[language_service.ModerateTextResponse], + ]: + r"""Return a callable for the moderate text method over gRPC. + + Moderates a document for harmful and sensitive + categories. + + Returns: + Callable[[~.ModerateTextRequest], + Awaitable[~.ModerateTextResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "moderate_text" not in self._stubs: + self._stubs["moderate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.language.v1.LanguageService/ModerateText", + request_serializer=language_service.ModerateTextRequest.serialize, + response_deserializer=language_service.ModerateTextResponse.deserialize, + ) + return self._stubs["moderate_text"] + @property def annotate_text( self, diff --git a/google/cloud/language_v1/services/language_service/transports/rest.py b/google/cloud/language_v1/services/language_service/transports/rest.py index d92e6672..990da259 100644 --- a/google/cloud/language_v1/services/language_service/transports/rest.py +++ b/google/cloud/language_v1/services/language_service/transports/rest.py @@ -111,6 +111,14 @@ def post_classify_text(self, response): logging.log(f"Received response: {response}") return response + def pre_moderate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_moderate_text(self, response): + logging.log(f"Received response: {response}") + return response + transport = LanguageServiceRestTransport(interceptor=MyCustomLanguageServiceInterceptor()) client = LanguageServiceClient(transport=transport) @@ -257,6 +265,29 @@ def post_classify_text( """ return response + def pre_moderate_text( + self, + request: language_service.ModerateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.ModerateTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for moderate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_moderate_text( + self, response: language_service.ModerateTextResponse + ) -> language_service.ModerateTextResponse: + """Post-rpc interceptor for moderate_text + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class LanguageServiceRestStub: @@ -945,6 +976,104 @@ def __call__( resp = self._interceptor.post_classify_text(resp) return resp + class _ModerateText(LanguageServiceRestStub): + def __hash__(self): + return hash("ModerateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.ModerateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ModerateTextResponse: + r"""Call the moderate text method over HTTP. + + Args: + request (~.language_service.ModerateTextRequest): + The request object. The document moderation request + message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.ModerateTextResponse: + The document moderation response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/documents:moderateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_moderate_text(request, metadata) + pb_request = language_service.ModerateTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.ModerateTextResponse() + pb_resp = language_service.ModerateTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_moderate_text(resp) + return resp + @property def analyze_entities( self, @@ -1008,6 +1137,16 @@ def classify_text( # In C++ this would require a dynamic_cast return self._ClassifyText(self._session, self._host, self._interceptor) # type: ignore + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], language_service.ModerateTextResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ModerateText(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/google/cloud/language_v1/types/__init__.py b/google/cloud/language_v1/types/__init__.py index b4b20c9c..4f98d4d3 100644 --- a/google/cloud/language_v1/types/__init__.py +++ b/google/cloud/language_v1/types/__init__.py @@ -33,6 +33,8 @@ EncodingType, Entity, EntityMention, + ModerateTextRequest, + ModerateTextResponse, PartOfSpeech, Sentence, Sentiment, @@ -59,6 +61,8 @@ "Document", "Entity", "EntityMention", + "ModerateTextRequest", + "ModerateTextResponse", "PartOfSpeech", "Sentence", "Sentiment", diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py index bd330ffe..da423978 100644 --- a/google/cloud/language_v1/types/language_service.py +++ b/google/cloud/language_v1/types/language_service.py @@ -44,6 +44,8 @@ "AnalyzeSyntaxResponse", "ClassifyTextRequest", "ClassifyTextResponse", + "ModerateTextRequest", + "ModerateTextResponse", "AnnotateTextRequest", "AnnotateTextResponse", }, @@ -1194,9 +1196,8 @@ class ClassificationCategory(proto.Message): Attributes: name (str): - The name of the category representing the document, from the - `predefined - taxonomy <https://cloud.google.com/natural-language/docs/categories>`__. + The name of the category representing the + document. confidence (float): The classifier's confidence of the category. Number represents how certain the classifier is @@ -1536,6 +1537,39 @@ class ClassifyTextResponse(proto.Message): ) +class ModerateTextRequest(proto.Message): + r"""The document moderation request message. + + Attributes: + document (google.cloud.language_v1.types.Document): + Required. Input document. + """ + + document: "Document" = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + + +class ModerateTextResponse(proto.Message): + r"""The document moderation response message. + + Attributes: + moderation_categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): + Harmful and sensitive categories representing + the input document. + """ + + moderation_categories: MutableSequence[ + "ClassificationCategory" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ClassificationCategory", + ) + + class AnnotateTextRequest(proto.Message): r"""The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and @@ -1568,6 +1602,9 @@ class Features(proto.Message): sentiment. classify_text (bool): Classify the full document into categories. + moderate_text (bool): + Moderate the document for harmful and + sensitive categories. classification_model_options (google.cloud.language_v1.types.ClassificationModelOptions): The model options to use for classification. Defaults to v1 options if not specified. Only used if ``classify_text`` is @@ -1594,6 +1631,10 @@ class Features(proto.Message): proto.BOOL, number=6, ) + moderate_text: bool = proto.Field( + proto.BOOL, + number=11, + ) classification_model_options: "ClassificationModelOptions" = proto.Field( proto.MESSAGE, number=10, @@ -1645,6 +1686,9 @@ class AnnotateTextResponse(proto.Message): field for more details. categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): Categories identified in the input document. + moderation_categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): + Harmful and sensitive categories identified + in the input document. """ sentences: MutableSequence["Sentence"] = proto.RepeatedField( @@ -1676,6 +1720,13 @@ class AnnotateTextResponse(proto.Message): number=6, message="ClassificationCategory", ) + moderation_categories: MutableSequence[ + "ClassificationCategory" + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="ClassificationCategory", + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py index 459b226d..d8e5de1b 100644 --- a/google/cloud/language_v1beta2/__init__.py +++ b/google/cloud/language_v1beta2/__init__.py @@ -39,6 +39,8 @@ EncodingType, Entity, EntityMention, + ModerateTextRequest, + ModerateTextResponse, PartOfSpeech, Sentence, Sentiment, @@ -68,6 +70,8 @@ "Entity", "EntityMention", "LanguageServiceClient", + "ModerateTextRequest", + "ModerateTextResponse", "PartOfSpeech", "Sentence", "Sentiment", diff --git a/google/cloud/language_v1beta2/gapic_metadata.json b/google/cloud/language_v1beta2/gapic_metadata.json index fca8f442..85a901f9 100644 --- a/google/cloud/language_v1beta2/gapic_metadata.json +++ b/google/cloud/language_v1beta2/gapic_metadata.json @@ -39,6 +39,11 @@ "methods": [ "classify_text" ] + }, + "ModerateText": { + "methods": [ + "moderate_text" + ] } } }, @@ -74,6 +79,11 @@ "methods": [ "classify_text" ] + }, + "ModerateText": { + "methods": [ + "moderate_text" + ] } } }, @@ -109,6 +119,11 @@ "methods": [ "classify_text" ] + }, + "ModerateText": { + "methods": [ + "moderate_text" + ] } } } diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 2676da9f..0ce7f723 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -793,6 +793,104 @@ async def sample_classify_text(): # Done; return the response. return response + async def moderate_text( + self, + request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, + *, + document: Optional[language_service.Document] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ModerateTextResponse: + r"""Moderates a document for harmful and sensitive + categories. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import language_v1beta2 + + async def sample_moderate_text(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ModerateTextRequest( + document=document, + ) + + # Make the request + response = await client.moderate_text(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.language_v1beta2.types.ModerateTextRequest, dict]]): + The request object. The document moderation request + message. + document (:class:`google.cloud.language_v1beta2.types.Document`): + Required. Input document. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.language_v1beta2.types.ModerateTextResponse: + The document moderation response + message. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([document]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = language_service.ModerateTextRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.moderate_text, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def annotate_text( self, request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py index 4c45046d..4888fcfc 100644 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ b/google/cloud/language_v1beta2/services/language_service/client.py @@ -952,6 +952,104 @@ def sample_classify_text(): # Done; return the response. return response + def moderate_text( + self, + request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, + *, + document: Optional[language_service.Document] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ModerateTextResponse: + r"""Moderates a document for harmful and sensitive + categories. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import language_v1beta2 + + def sample_moderate_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ModerateTextRequest( + document=document, + ) + + # Make the request + response = client.moderate_text(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.language_v1beta2.types.ModerateTextRequest, dict]): + The request object. The document moderation request + message. + document (google.cloud.language_v1beta2.types.Document): + Required. Input document. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.language_v1beta2.types.ModerateTextResponse: + The document moderation response + message. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([document]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a language_service.ModerateTextRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, language_service.ModerateTextRequest): + request = language_service.ModerateTextRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.moderate_text] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def annotate_text( self, request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py index 5204e4c9..06cd03ef 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/base.py @@ -200,6 +200,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.moderate_text: gapic_v1.method.wrap_method( + self.moderate_text, + default_timeout=None, + client_info=client_info, + ), self.annotate_text: gapic_v1.method.wrap_method( self.annotate_text, default_retry=retries.Retry( @@ -286,6 +291,18 @@ def classify_text( ]: raise NotImplementedError() + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], + Union[ + language_service.ModerateTextResponse, + Awaitable[language_service.ModerateTextResponse], + ], + ]: + raise NotImplementedError() + @property def annotate_text( self, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py index f89362eb..ec629428 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py @@ -380,6 +380,35 @@ def classify_text( ) return self._stubs["classify_text"] + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], language_service.ModerateTextResponse + ]: + r"""Return a callable for the moderate text method over gRPC. + + Moderates a document for harmful and sensitive + categories. + + Returns: + Callable[[~.ModerateTextRequest], + ~.ModerateTextResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "moderate_text" not in self._stubs: + self._stubs["moderate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.language.v1beta2.LanguageService/ModerateText", + request_serializer=language_service.ModerateTextRequest.serialize, + response_deserializer=language_service.ModerateTextResponse.deserialize, + ) + return self._stubs["moderate_text"] + @property def annotate_text( self, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py index dc0f8f26..4d1a8065 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py @@ -385,6 +385,36 @@ def classify_text( ) return self._stubs["classify_text"] + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], + Awaitable[language_service.ModerateTextResponse], + ]: + r"""Return a callable for the moderate text method over gRPC. + + Moderates a document for harmful and sensitive + categories. + + Returns: + Callable[[~.ModerateTextRequest], + Awaitable[~.ModerateTextResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "moderate_text" not in self._stubs: + self._stubs["moderate_text"] = self.grpc_channel.unary_unary( + "/google.cloud.language.v1beta2.LanguageService/ModerateText", + request_serializer=language_service.ModerateTextRequest.serialize, + response_deserializer=language_service.ModerateTextResponse.deserialize, + ) + return self._stubs["moderate_text"] + @property def annotate_text( self, diff --git a/google/cloud/language_v1beta2/services/language_service/transports/rest.py b/google/cloud/language_v1beta2/services/language_service/transports/rest.py index e0821a77..90a221e3 100644 --- a/google/cloud/language_v1beta2/services/language_service/transports/rest.py +++ b/google/cloud/language_v1beta2/services/language_service/transports/rest.py @@ -111,6 +111,14 @@ def post_classify_text(self, response): logging.log(f"Received response: {response}") return response + def pre_moderate_text(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_moderate_text(self, response): + logging.log(f"Received response: {response}") + return response + transport = LanguageServiceRestTransport(interceptor=MyCustomLanguageServiceInterceptor()) client = LanguageServiceClient(transport=transport) @@ -257,6 +265,29 @@ def post_classify_text( """ return response + def pre_moderate_text( + self, + request: language_service.ModerateTextRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[language_service.ModerateTextRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for moderate_text + + Override in a subclass to manipulate the request or metadata + before they are sent to the LanguageService server. + """ + return request, metadata + + def post_moderate_text( + self, response: language_service.ModerateTextResponse + ) -> language_service.ModerateTextResponse: + """Post-rpc interceptor for moderate_text + + Override in a subclass to manipulate the response + after it is returned by the LanguageService server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class LanguageServiceRestStub: @@ -945,6 +976,104 @@ def __call__( resp = self._interceptor.post_classify_text(resp) return resp + class _ModerateText(LanguageServiceRestStub): + def __hash__(self): + return hash("ModerateText") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: language_service.ModerateTextRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> language_service.ModerateTextResponse: + r"""Call the moderate text method over HTTP. + + Args: + request (~.language_service.ModerateTextRequest): + The request object. The document moderation request + message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.language_service.ModerateTextResponse: + The document moderation response + message. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta2/documents:moderateText", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_moderate_text(request, metadata) + pb_request = language_service.ModerateTextRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = language_service.ModerateTextResponse() + pb_resp = language_service.ModerateTextResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_moderate_text(resp) + return resp + @property def analyze_entities( self, @@ -1008,6 +1137,16 @@ def classify_text( # In C++ this would require a dynamic_cast return self._ClassifyText(self._session, self._host, self._interceptor) # type: ignore + @property + def moderate_text( + self, + ) -> Callable[ + [language_service.ModerateTextRequest], language_service.ModerateTextResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ModerateText(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/google/cloud/language_v1beta2/types/__init__.py b/google/cloud/language_v1beta2/types/__init__.py index b4b20c9c..4f98d4d3 100644 --- a/google/cloud/language_v1beta2/types/__init__.py +++ b/google/cloud/language_v1beta2/types/__init__.py @@ -33,6 +33,8 @@ EncodingType, Entity, EntityMention, + ModerateTextRequest, + ModerateTextResponse, PartOfSpeech, Sentence, Sentiment, @@ -59,6 +61,8 @@ "Document", "Entity", "EntityMention", + "ModerateTextRequest", + "ModerateTextResponse", "PartOfSpeech", "Sentence", "Sentiment", diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py index 884a1512..d88273fd 100644 --- a/google/cloud/language_v1beta2/types/language_service.py +++ b/google/cloud/language_v1beta2/types/language_service.py @@ -44,6 +44,8 @@ "AnalyzeSyntaxResponse", "ClassifyTextRequest", "ClassifyTextResponse", + "ModerateTextRequest", + "ModerateTextResponse", "AnnotateTextRequest", "AnnotateTextResponse", }, @@ -1227,9 +1229,8 @@ class ClassificationCategory(proto.Message): Attributes: name (str): - The name of the category representing the document, from the - `predefined - taxonomy <https://cloud.google.com/natural-language/docs/categories>`__. + The name of the category representing the + document. confidence (float): The classifier's confidence of the category. Number represents how certain the classifier is @@ -1570,6 +1571,39 @@ class ClassifyTextResponse(proto.Message): ) +class ModerateTextRequest(proto.Message): + r"""The document moderation request message. + + Attributes: + document (google.cloud.language_v1beta2.types.Document): + Required. Input document. + """ + + document: "Document" = proto.Field( + proto.MESSAGE, + number=1, + message="Document", + ) + + +class ModerateTextResponse(proto.Message): + r"""The document moderation response message. + + Attributes: + moderation_categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): + Harmful and sensitive categories representing + the input document. + """ + + moderation_categories: MutableSequence[ + "ClassificationCategory" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ClassificationCategory", + ) + + class AnnotateTextRequest(proto.Message): r"""The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and @@ -1588,7 +1622,7 @@ class AnnotateTextRequest(proto.Message): class Features(proto.Message): r"""All available features for sentiment, syntax, and semantic analysis. Setting each one to true will enable that specific - analysis for the input. Next ID: 11 + analysis for the input. Next ID: 12 Attributes: extract_syntax (bool): @@ -1605,6 +1639,9 @@ class Features(proto.Message): the API will use the default model which classifies into a `predefined taxonomy <https://cloud.google.com/natural-language/docs/categories>`__. + moderate_text (bool): + Moderate the document for harmful and + sensitive categories. classification_model_options (google.cloud.language_v1beta2.types.ClassificationModelOptions): The model options to use for classification. Defaults to v1 options if not specified. Only used if ``classify_text`` is @@ -1631,6 +1668,10 @@ class Features(proto.Message): proto.BOOL, number=6, ) + moderate_text: bool = proto.Field( + proto.BOOL, + number=11, + ) classification_model_options: "ClassificationModelOptions" = proto.Field( proto.MESSAGE, number=10, @@ -1682,6 +1723,9 @@ class AnnotateTextResponse(proto.Message): field for more details. categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): Categories identified in the input document. + moderation_categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): + Harmful and sensitive categories identified + in the input document. """ sentences: MutableSequence["Sentence"] = proto.RepeatedField( @@ -1713,6 +1757,13 @@ class AnnotateTextResponse(proto.Message): number=6, message="ClassificationCategory", ) + moderation_categories: MutableSequence[ + "ClassificationCategory" + ] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="ClassificationCategory", + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py b/samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py new file mode 100644 index 00000000..6f4d033d --- /dev/null +++ b/samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ModerateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_v1_generated_LanguageService_ModerateText_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import language_v1 + + +async def sample_moderate_text(): + # Create a client + client = language_v1.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ModerateTextRequest( + document=document, + ) + + # Make the request + response = await client.moderate_text(request=request) + + # Handle the response + print(response) + +# [END language_v1_generated_LanguageService_ModerateText_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py new file mode 100644 index 00000000..788b4a08 --- /dev/null +++ b/samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ModerateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_v1_generated_LanguageService_ModerateText_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import language_v1 + + +def sample_moderate_text(): + # Create a client + client = language_v1.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1.Document() + document.content = "content_value" + + request = language_v1.ModerateTextRequest( + document=document, + ) + + # Make the request + response = client.moderate_text(request=request) + + # Handle the response + print(response) + +# [END language_v1_generated_LanguageService_ModerateText_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py new file mode 100644 index 00000000..d8385285 --- /dev/null +++ b/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ModerateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_v1beta2_generated_LanguageService_ModerateText_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import language_v1beta2 + + +async def sample_moderate_text(): + # Create a client + client = language_v1beta2.LanguageServiceAsyncClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ModerateTextRequest( + document=document, + ) + + # Make the request + response = await client.moderate_text(request=request) + + # Handle the response + print(response) + +# [END language_v1beta2_generated_LanguageService_ModerateText_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py new file mode 100644 index 00000000..78d11521 --- /dev/null +++ b/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ModerateText +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-language + + +# [START language_v1beta2_generated_LanguageService_ModerateText_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import language_v1beta2 + + +def sample_moderate_text(): + # Create a client + client = language_v1beta2.LanguageServiceClient() + + # Initialize request argument(s) + document = language_v1beta2.Document() + document.content = "content_value" + + request = language_v1beta2.ModerateTextRequest( + document=document, + ) + + # Make the request + response = client.moderate_text(request=request) + + # Handle the response + print(response) + +# [END language_v1beta2_generated_LanguageService_ModerateText_sync] diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 9651e696..4e481f59 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.9.1" + "version": "0.1.0" }, "snippets": [ { @@ -1024,6 +1024,167 @@ } ], "title": "language_v1_generated_language_service_classify_text_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.moderate_text", + "method": { + "fullName": "google.cloud.language.v1.LanguageService.ModerateText", + "service": { + "fullName": "google.cloud.language.v1.LanguageService", + "shortName": "LanguageService" + }, + "shortName": "ModerateText" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.ModerateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.ModerateTextResponse", + "shortName": "moderate_text" + }, + "description": "Sample for ModerateText", + "file": "language_v1_generated_language_service_moderate_text_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "language_v1_generated_LanguageService_ModerateText_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "language_v1_generated_language_service_moderate_text_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1.LanguageServiceClient.moderate_text", + "method": { + "fullName": "google.cloud.language.v1.LanguageService.ModerateText", + "service": { + "fullName": "google.cloud.language.v1.LanguageService", + "shortName": "LanguageService" + }, + "shortName": "ModerateText" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1.types.ModerateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1.types.ModerateTextResponse", + "shortName": "moderate_text" + }, + "description": "Sample for ModerateText", + "file": "language_v1_generated_language_service_moderate_text_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "language_v1_generated_LanguageService_ModerateText_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "language_v1_generated_language_service_moderate_text_sync.py" } ] } diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index 6ef547cc..fb6633f2 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.9.1" + "version": "0.1.0" }, "snippets": [ { @@ -1024,6 +1024,167 @@ } ], "title": "language_v1beta2_generated_language_service_classify_text_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", + "shortName": "LanguageServiceAsyncClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.moderate_text", + "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.ModerateText", + "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", + "shortName": "LanguageService" + }, + "shortName": "ModerateText" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.ModerateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.ModerateTextResponse", + "shortName": "moderate_text" + }, + "description": "Sample for ModerateText", + "file": "language_v1beta2_generated_language_service_moderate_text_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "language_v1beta2_generated_LanguageService_ModerateText_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "language_v1beta2_generated_language_service_moderate_text_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", + "shortName": "LanguageServiceClient" + }, + "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.moderate_text", + "method": { + "fullName": "google.cloud.language.v1beta2.LanguageService.ModerateText", + "service": { + "fullName": "google.cloud.language.v1beta2.LanguageService", + "shortName": "LanguageService" + }, + "shortName": "ModerateText" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.language_v1beta2.types.ModerateTextRequest" + }, + { + "name": "document", + "type": "google.cloud.language_v1beta2.types.Document" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.language_v1beta2.types.ModerateTextResponse", + "shortName": "moderate_text" + }, + "description": "Sample for ModerateText", + "file": "language_v1beta2_generated_language_service_moderate_text_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "language_v1beta2_generated_LanguageService_ModerateText_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "language_v1beta2_generated_language_service_moderate_text_sync.py" } ] } diff --git a/scripts/fixup_language_v1_keywords.py b/scripts/fixup_language_v1_keywords.py index fc15df57..10fa218c 100644 --- a/scripts/fixup_language_v1_keywords.py +++ b/scripts/fixup_language_v1_keywords.py @@ -45,6 +45,7 @@ class languageCallTransformer(cst.CSTTransformer): 'analyze_syntax': ('document', 'encoding_type', ), 'annotate_text': ('document', 'features', 'encoding_type', ), 'classify_text': ('document', 'classification_model_options', ), + 'moderate_text': ('document', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/scripts/fixup_language_v1beta2_keywords.py b/scripts/fixup_language_v1beta2_keywords.py index fc15df57..10fa218c 100644 --- a/scripts/fixup_language_v1beta2_keywords.py +++ b/scripts/fixup_language_v1beta2_keywords.py @@ -45,6 +45,7 @@ class languageCallTransformer(cst.CSTTransformer): 'analyze_syntax': ('document', 'encoding_type', ), 'annotate_text': ('document', 'features', 'encoding_type', ), 'classify_text': ('document', 'classification_model_options', ), + 'moderate_text': ('document', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py index 4904c456..77957902 100644 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ b/tests/unit/gapic/language_v1/test_language_service.py @@ -1700,6 +1700,183 @@ async def test_classify_text_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + language_service.ModerateTextRequest, + dict, + ], +) +def test_moderate_text(request_type, transport: str = "grpc"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = language_service.ModerateTextResponse() + response = client.moderate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == language_service.ModerateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ModerateTextResponse) + + +def test_moderate_text_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 = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + client.moderate_text() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == language_service.ModerateTextRequest() + + +@pytest.mark.asyncio +async def test_moderate_text_async( + transport: str = "grpc_asyncio", request_type=language_service.ModerateTextRequest +): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + language_service.ModerateTextResponse() + ) + response = await client.moderate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == language_service.ModerateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ModerateTextResponse) + + +@pytest.mark.asyncio +async def test_moderate_text_async_from_dict(): + await test_moderate_text_async(request_type=dict) + + +def test_moderate_text_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = language_service.ModerateTextResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.moderate_text( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ) + assert arg == mock_val + + +def test_moderate_text_flattened_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.moderate_text( + language_service.ModerateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + +@pytest.mark.asyncio +async def test_moderate_text_flattened_async(): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = language_service.ModerateTextResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + language_service.ModerateTextResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.moderate_text( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_moderate_text_flattened_error_async(): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.moderate_text( + language_service.ModerateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -3246,6 +3423,269 @@ def test_classify_text_rest_error(): ) +@pytest.mark.parametrize( + "request_type", + [ + language_service.ModerateTextRequest, + dict, + ], +) +def test_moderate_text_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ModerateTextResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ModerateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.moderate_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ModerateTextResponse) + + +def test_moderate_text_rest_required_fields( + request_type=language_service.ModerateTextRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).moderate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).moderate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.ModerateTextResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.ModerateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.moderate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_moderate_text_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.moderate_text._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_moderate_text_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_moderate_text" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_moderate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.ModerateTextRequest.pb( + language_service.ModerateTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.ModerateTextResponse.to_json( + language_service.ModerateTextResponse() + ) + + request = language_service.ModerateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.ModerateTextResponse() + + client.moderate_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_moderate_text_rest_bad_request( + transport: str = "rest", request_type=language_service.ModerateTextRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.moderate_text(request) + + +def test_moderate_text_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ModerateTextResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ModerateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.moderate_text(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/documents:moderateText" % client.transport._host, args[1] + ) + + +def test_moderate_text_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.moderate_text( + language_service.ModerateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + +def test_moderate_text_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + @pytest.mark.parametrize( "request_type", [ @@ -3668,6 +4108,7 @@ def test_language_service_base_transport(): "analyze_entity_sentiment", "analyze_syntax", "classify_text", + "moderate_text", "annotate_text", ) for method in methods: @@ -3954,6 +4395,9 @@ def test_language_service_client_transport_session_collision(transport_name): session1 = client1.transport.classify_text._session session2 = client2.transport.classify_text._session assert session1 != session2 + session1 = client1.transport.moderate_text._session + session2 = client2.transport.moderate_text._session + assert session1 != session2 session1 = client1.transport.annotate_text._session session2 = client2.transport.annotate_text._session assert session1 != session2 diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py index 809ce0e0..adfc2301 100644 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ b/tests/unit/gapic/language_v1beta2/test_language_service.py @@ -1700,6 +1700,183 @@ async def test_classify_text_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + language_service.ModerateTextRequest, + dict, + ], +) +def test_moderate_text(request_type, transport: str = "grpc"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = language_service.ModerateTextResponse() + response = client.moderate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == language_service.ModerateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ModerateTextResponse) + + +def test_moderate_text_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 = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + client.moderate_text() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == language_service.ModerateTextRequest() + + +@pytest.mark.asyncio +async def test_moderate_text_async( + transport: str = "grpc_asyncio", request_type=language_service.ModerateTextRequest +): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + language_service.ModerateTextResponse() + ) + response = await client.moderate_text(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == language_service.ModerateTextRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ModerateTextResponse) + + +@pytest.mark.asyncio +async def test_moderate_text_async_from_dict(): + await test_moderate_text_async(request_type=dict) + + +def test_moderate_text_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = language_service.ModerateTextResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.moderate_text( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ) + assert arg == mock_val + + +def test_moderate_text_flattened_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.moderate_text( + language_service.ModerateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + +@pytest.mark.asyncio +async def test_moderate_text_flattened_async(): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = language_service.ModerateTextResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + language_service.ModerateTextResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.moderate_text( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].document + mock_val = language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_moderate_text_flattened_error_async(): + client = LanguageServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.moderate_text( + language_service.ModerateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -3247,6 +3424,269 @@ def test_classify_text_rest_error(): ) +@pytest.mark.parametrize( + "request_type", + [ + language_service.ModerateTextRequest, + dict, + ], +) +def test_moderate_text_rest(request_type): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ModerateTextResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ModerateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.moderate_text(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, language_service.ModerateTextResponse) + + +def test_moderate_text_rest_required_fields( + request_type=language_service.ModerateTextRequest, +): + transport_class = transports.LanguageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).moderate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).moderate_text._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = language_service.ModerateTextResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = language_service.ModerateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.moderate_text(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_moderate_text_rest_unset_required_fields(): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.moderate_text._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("document",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_moderate_text_rest_interceptors(null_interceptor): + transport = transports.LanguageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LanguageServiceRestInterceptor(), + ) + client = LanguageServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LanguageServiceRestInterceptor, "post_moderate_text" + ) as post, mock.patch.object( + transports.LanguageServiceRestInterceptor, "pre_moderate_text" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = language_service.ModerateTextRequest.pb( + language_service.ModerateTextRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = language_service.ModerateTextResponse.to_json( + language_service.ModerateTextResponse() + ) + + request = language_service.ModerateTextRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = language_service.ModerateTextResponse() + + client.moderate_text( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_moderate_text_rest_bad_request( + transport: str = "rest", request_type=language_service.ModerateTextRequest +): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.moderate_text(request) + + +def test_moderate_text_rest_flattened(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = language_service.ModerateTextResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = language_service.ModerateTextResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.moderate_text(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta2/documents:moderateText" % client.transport._host, args[1] + ) + + +def test_moderate_text_rest_flattened_error(transport: str = "rest"): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.moderate_text( + language_service.ModerateTextRequest(), + document=language_service.Document( + type_=language_service.Document.Type.PLAIN_TEXT + ), + ) + + +def test_moderate_text_rest_error(): + client = LanguageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + @pytest.mark.parametrize( "request_type", [ @@ -3669,6 +4109,7 @@ def test_language_service_base_transport(): "analyze_entity_sentiment", "analyze_syntax", "classify_text", + "moderate_text", "annotate_text", ) for method in methods: @@ -3955,6 +4396,9 @@ def test_language_service_client_transport_session_collision(transport_name): session1 = client1.transport.classify_text._session session2 = client2.transport.classify_text._session assert session1 != session2 + session1 = client1.transport.moderate_text._session + session2 = client2.transport.moderate_text._session + assert session1 != session2 session1 = client1.transport.annotate_text._session session2 = client2.transport.annotate_text._session assert session1 != session2 From 7a581714b50e4b032441061219a76e189fc21b5d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 25 May 2023 16:22:13 +0000 Subject: [PATCH 247/254] build(deps): bump requests to 2.31.0 [autoapprove] (#435) Source-Link: https://togithub.com/googleapis/synthtool/commit/30bd01b4ab78bf1b2a425816e15b3e7e090993dd Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:9bc5fa3b62b091f60614c08a7fb4fd1d3e1678e326f34dd66ce1eefb5dc3267b --- .github/.OwlBot.lock.yaml | 3 ++- .kokoro/requirements.txt | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index b8edda51..32b3c486 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:2e247c7bf5154df7f98cce087a20ca7605e236340c7d6d1a14447e5c06791bd6 + digest: sha256:9bc5fa3b62b091f60614c08a7fb4fd1d3e1678e326f34dd66ce1eefb5dc3267b +# created: 2023-05-25T14:56:16.294623272Z diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 66a2172a..3b8d7ee8 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -419,9 +419,9 @@ readme-renderer==37.3 \ --hash=sha256:cd653186dfc73055656f090f227f5cb22a046d7f71a841dfa305f55c9a513273 \ --hash=sha256:f67a16caedfa71eef48a31b39708637a6f4664c4394801a7b0d6432d13907343 # via twine -requests==2.28.1 \ - --hash=sha256:7c5599b102feddaa661c826c56ab4fee28bfd17f5abca1ebbe3e7f19d7c97983 \ - --hash=sha256:8fefa2a1a1365bf5520aac41836fbee479da67864514bdb821f31ce07ce65349 +requests==2.31.0 \ + --hash=sha256:58cd2187c01e70e6e26505bca751777aa9f2ee0b7f4300988b709f44e013003f \ + --hash=sha256:942c5a758f98d790eaed1a29cb6eefc7ffb0d1cf7af05c3d2791656dbd6ad1e1 # via # gcp-releasetool # google-api-core From b4c3934e8ecfd2618003c539b8427e51722f1cc9 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 31 May 2023 15:05:41 -0400 Subject: [PATCH 248/254] chore(main): release 2.10.0 (#434) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ google/cloud/language/gapic_version.py | 2 +- google/cloud/language_v1/gapic_version.py | 2 +- google/cloud/language_v1beta2/gapic_version.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- 7 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 13a0da6b..5b009ae8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.9.1" + ".": "2.10.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 3244ccc8..c27e291b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.10.0](https://github.com/googleapis/python-language/compare/v2.9.1...v2.10.0) (2023-05-25) + + +### Features + +* Add support for ModerateText ([#433](https://github.com/googleapis/python-language/issues/433)) ([033a20b](https://github.com/googleapis/python-language/commit/033a20bf9aee96b2cbadd15a36d520b4ec40c7ab)) + ## [2.9.1](https://github.com/googleapis/python-language/compare/v2.9.0...v2.9.1) (2023-03-23) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index 18081a7d..00f0a8d0 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.9.1" # {x-release-please-version} +__version__ = "2.10.0" # {x-release-please-version} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py index 18081a7d..00f0a8d0 100644 --- a/google/cloud/language_v1/gapic_version.py +++ b/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.9.1" # {x-release-please-version} +__version__ = "2.10.0" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py index 18081a7d..00f0a8d0 100644 --- a/google/cloud/language_v1beta2/gapic_version.py +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.9.1" # {x-release-please-version} +__version__ = "2.10.0" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 4e481f59..6a8acce0 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.10.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index fb6633f2..e2c24656 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.10.0" }, "snippets": [ { From ceaf36908967656541e7e86e2953b56dc185dfa1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 3 Jun 2023 21:46:15 +0000 Subject: [PATCH 249/254] build(deps): bump cryptography to 41.0.0 [autoapprove] (#437) Source-Link: https://togithub.com/googleapis/synthtool/commit/d0f51a0c2a9a6bcca86911eabea9e484baadf64b Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:240b5bcc2bafd450912d2da2be15e62bc6de2cf839823ae4bf94d4f392b451dc --- .github/.OwlBot.lock.yaml | 4 ++-- .kokoro/requirements.txt | 42 +++++++++++++++++++-------------------- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 32b3c486..02a4dedc 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:9bc5fa3b62b091f60614c08a7fb4fd1d3e1678e326f34dd66ce1eefb5dc3267b -# created: 2023-05-25T14:56:16.294623272Z + digest: sha256:240b5bcc2bafd450912d2da2be15e62bc6de2cf839823ae4bf94d4f392b451dc +# created: 2023-06-03T21:25:37.968717478Z diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 3b8d7ee8..c7929db6 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -113,28 +113,26 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==39.0.1 \ - --hash=sha256:0f8da300b5c8af9f98111ffd512910bc792b4c77392a9523624680f7956a99d4 \ - --hash=sha256:35f7c7d015d474f4011e859e93e789c87d21f6f4880ebdc29896a60403328f1f \ - --hash=sha256:5aa67414fcdfa22cf052e640cb5ddc461924a045cacf325cd164e65312d99502 \ - --hash=sha256:5d2d8b87a490bfcd407ed9d49093793d0f75198a35e6eb1a923ce1ee86c62b41 \ - --hash=sha256:6687ef6d0a6497e2b58e7c5b852b53f62142cfa7cd1555795758934da363a965 \ - --hash=sha256:6f8ba7f0328b79f08bdacc3e4e66fb4d7aab0c3584e0bd41328dce5262e26b2e \ - --hash=sha256:706843b48f9a3f9b9911979761c91541e3d90db1ca905fd63fee540a217698bc \ - --hash=sha256:807ce09d4434881ca3a7594733669bd834f5b2c6d5c7e36f8c00f691887042ad \ - --hash=sha256:83e17b26de248c33f3acffb922748151d71827d6021d98c70e6c1a25ddd78505 \ - --hash=sha256:96f1157a7c08b5b189b16b47bc9db2332269d6680a196341bf30046330d15388 \ - --hash=sha256:aec5a6c9864be7df2240c382740fcf3b96928c46604eaa7f3091f58b878c0bb6 \ - --hash=sha256:b0afd054cd42f3d213bf82c629efb1ee5f22eba35bf0eec88ea9ea7304f511a2 \ - --hash=sha256:ced4e447ae29ca194449a3f1ce132ded8fcab06971ef5f618605aacaa612beac \ - --hash=sha256:d1f6198ee6d9148405e49887803907fe8962a23e6c6f83ea7d98f1c0de375695 \ - --hash=sha256:e124352fd3db36a9d4a21c1aa27fd5d051e621845cb87fb851c08f4f75ce8be6 \ - --hash=sha256:e422abdec8b5fa8462aa016786680720d78bdce7a30c652b7fadf83a4ba35336 \ - --hash=sha256:ef8b72fa70b348724ff1218267e7f7375b8de4e8194d1636ee60510aae104cd0 \ - --hash=sha256:f0c64d1bd842ca2633e74a1a28033d139368ad959872533b1bab8c80e8240a0c \ - --hash=sha256:f24077a3b5298a5a06a8e0536e3ea9ec60e4c7ac486755e5fb6e6ea9b3500106 \ - --hash=sha256:fdd188c8a6ef8769f148f88f859884507b954cc64db6b52f66ef199bb9ad660a \ - --hash=sha256:fe913f20024eb2cb2f323e42a64bdf2911bb9738a15dba7d3cce48151034e3a8 +cryptography==41.0.0 \ + --hash=sha256:0ddaee209d1cf1f180f1efa338a68c4621154de0afaef92b89486f5f96047c55 \ + --hash=sha256:14754bcdae909d66ff24b7b5f166d69340ccc6cb15731670435efd5719294895 \ + --hash=sha256:344c6de9f8bda3c425b3a41b319522ba3208551b70c2ae00099c205f0d9fd3be \ + --hash=sha256:34d405ea69a8b34566ba3dfb0521379b210ea5d560fafedf9f800a9a94a41928 \ + --hash=sha256:3680248309d340fda9611498a5319b0193a8dbdb73586a1acf8109d06f25b92d \ + --hash=sha256:3c5ef25d060c80d6d9f7f9892e1d41bb1c79b78ce74805b8cb4aa373cb7d5ec8 \ + --hash=sha256:4ab14d567f7bbe7f1cdff1c53d5324ed4d3fc8bd17c481b395db224fb405c237 \ + --hash=sha256:5c1f7293c31ebc72163a9a0df246f890d65f66b4a40d9ec80081969ba8c78cc9 \ + --hash=sha256:6b71f64beeea341c9b4f963b48ee3b62d62d57ba93eb120e1196b31dc1025e78 \ + --hash=sha256:7d92f0248d38faa411d17f4107fc0bce0c42cae0b0ba5415505df72d751bf62d \ + --hash=sha256:8362565b3835ceacf4dc8f3b56471a2289cf51ac80946f9087e66dc283a810e0 \ + --hash=sha256:84a165379cb9d411d58ed739e4af3396e544eac190805a54ba2e0322feb55c46 \ + --hash=sha256:88ff107f211ea696455ea8d911389f6d2b276aabf3231bf72c8853d22db755c5 \ + --hash=sha256:9f65e842cb02550fac96536edb1d17f24c0a338fd84eaf582be25926e993dde4 \ + --hash=sha256:a4fc68d1c5b951cfb72dfd54702afdbbf0fb7acdc9b7dc4301bbf2225a27714d \ + --hash=sha256:b7f2f5c525a642cecad24ee8670443ba27ac1fab81bba4cc24c7b6b41f2d0c75 \ + --hash=sha256:b846d59a8d5a9ba87e2c3d757ca019fa576793e8758174d3868aecb88d6fc8eb \ + --hash=sha256:bf8fc66012ca857d62f6a347007e166ed59c0bc150cefa49f28376ebe7d992a2 \ + --hash=sha256:f5d0bf9b252f30a31664b6f64432b4730bb7038339bd18b1fafe129cfc2be9be # via # gcp-releasetool # secretstorage From 47f57c5651647f13cbbefa4968bea38536928a8a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 27 Jun 2023 13:24:17 +0000 Subject: [PATCH 250/254] chore: remove pinned Sphinx version [autoapprove] (#438) Source-Link: https://togithub.com/googleapis/synthtool/commit/909573ce9da2819eeb835909c795d29aea5c724e Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:ddf4551385d566771dc713090feb7b4c1164fb8a698fe52bbe7670b24236565b --- .github/.OwlBot.lock.yaml | 4 ++-- noxfile.py | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 02a4dedc..1b3cb6c5 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:240b5bcc2bafd450912d2da2be15e62bc6de2cf839823ae4bf94d4f392b451dc -# created: 2023-06-03T21:25:37.968717478Z + digest: sha256:ddf4551385d566771dc713090feb7b4c1164fb8a698fe52bbe7670b24236565b +# created: 2023-06-27T13:04:21.96690344Z diff --git a/noxfile.py b/noxfile.py index 95e58c52..6b57c246 100644 --- a/noxfile.py +++ b/noxfile.py @@ -305,10 +305,9 @@ def docfx(session): session.install("-e", ".") session.install( - "sphinx==4.0.1", + "gcp-sphinx-docfx-yaml", "alabaster", "recommonmark", - "gcp-sphinx-docfx-yaml", ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) From 9e88bd3c823122cd99cd52f8c89a10cf3ce16402 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:30:24 +0000 Subject: [PATCH 251/254] chore: store artifacts in placer [autoapprove] (#439) Source-Link: https://togithub.com/googleapis/synthtool/commit/cb960373d12d20f8dc38beee2bf884d49627165e Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:2d816f26f728ac8b24248741e7d4c461c09764ef9f7be3684d557c9632e46dbd --- .github/.OwlBot.lock.yaml | 4 ++-- .kokoro/release/common.cfg | 9 +++++++++ noxfile.py | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 1b3cb6c5..98994f47 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ddf4551385d566771dc713090feb7b4c1164fb8a698fe52bbe7670b24236565b -# created: 2023-06-27T13:04:21.96690344Z + digest: sha256:2d816f26f728ac8b24248741e7d4c461c09764ef9f7be3684d557c9632e46dbd +# created: 2023-06-28T17:03:33.371210701Z diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 6c908a55..f38c1ae4 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -38,3 +38,12 @@ env_vars: { key: "SECRET_MANAGER_KEYS" value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" } + +# Store the packages we uploaded to PyPI. That way, we have a record of exactly +# what we published, which we can use to generate SBOMs and attestations. +action { + define_artifacts { + regex: "github/python-language/**/*.tar.gz" + strip_prefix: "github/python-language" + } +} diff --git a/noxfile.py b/noxfile.py index 6b57c246..7d411fea 100644 --- a/noxfile.py +++ b/noxfile.py @@ -379,6 +379,7 @@ def prerelease_deps(session): "grpcio!=1.52.0rc1", "grpcio-status", "google-api-core", + "google-auth", "proto-plus", "google-cloud-testutils", # dependencies of google-cloud-testutils" @@ -391,7 +392,6 @@ def prerelease_deps(session): # Remaining dependencies other_deps = [ "requests", - "google-auth", ] session.install(*other_deps) From f6322f471be25c7f8f5c1392d78ebfcb4f498785 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 4 Jul 2023 10:33:37 -0700 Subject: [PATCH 252/254] fix: Add async context manager return types (#440) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Add async context manager return types chore: Mock return_value should not populate oneof message fields chore: Support snippet generation for services that only support REST transport chore: Update gapic-generator-python to v1.11.0 PiperOrigin-RevId: 545430278 Source-Link: https://github.com/googleapis/googleapis/commit/601b5326107eeb74800b426d1f9933faa233258a Source-Link: https://github.com/googleapis/googleapis-gen/commit/b3f18d0f6560a855022fd058865e7620479d7af9 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjNmMThkMGY2NTYwYTg1NTAyMmZkMDU4ODY1ZTc2MjA0NzlkN2FmOSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../cloud/language_v1/services/language_service/async_client.py | 2 +- .../language_v1beta2/services/language_service/async_client.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py index 54fda3ae..fd09c872 100644 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ b/google/cloud/language_v1/services/language_service/async_client.py @@ -1019,7 +1019,7 @@ async def sample_annotate_text(): # Done; return the response. return response - async def __aenter__(self): + async def __aenter__(self) -> "LanguageServiceAsyncClient": return self async def __aexit__(self, exc_type, exc, tb): diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py index 0ce7f723..fe13e5fe 100644 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ b/google/cloud/language_v1beta2/services/language_service/async_client.py @@ -1020,7 +1020,7 @@ async def sample_annotate_text(): # Done; return the response. return response - async def __aenter__(self): + async def __aenter__(self) -> "LanguageServiceAsyncClient": return self async def __aexit__(self, exc_type, exc, tb): diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 6a8acce0..4e481f59 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.10.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index e2c24656..fb6633f2 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.10.0" + "version": "0.1.0" }, "snippets": [ { From e849f90b49a0f472194d349cd44841caafa53345 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 5 Jul 2023 11:04:40 -0400 Subject: [PATCH 253/254] chore(main): release 2.10.1 (#441) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ google/cloud/language/gapic_version.py | 2 +- google/cloud/language_v1/gapic_version.py | 2 +- google/cloud/language_v1beta2/gapic_version.py | 2 +- .../snippet_metadata_google.cloud.language.v1.json | 2 +- .../snippet_metadata_google.cloud.language.v1beta2.json | 2 +- 7 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5b009ae8..4186d431 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "2.10.0" + ".": "2.10.1" } diff --git a/CHANGELOG.md b/CHANGELOG.md index c27e291b..4ac2bc15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.10.1](https://github.com/googleapis/python-language/compare/v2.10.0...v2.10.1) (2023-07-04) + + +### Bug Fixes + +* Add async context manager return types ([#440](https://github.com/googleapis/python-language/issues/440)) ([f6322f4](https://github.com/googleapis/python-language/commit/f6322f471be25c7f8f5c1392d78ebfcb4f498785)) + ## [2.10.0](https://github.com/googleapis/python-language/compare/v2.9.1...v2.10.0) (2023-05-25) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py index 00f0a8d0..3dded207 100644 --- a/google/cloud/language/gapic_version.py +++ b/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.10.0" # {x-release-please-version} +__version__ = "2.10.1" # {x-release-please-version} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py index 00f0a8d0..3dded207 100644 --- a/google/cloud/language_v1/gapic_version.py +++ b/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.10.0" # {x-release-please-version} +__version__ = "2.10.1" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py index 00f0a8d0..3dded207 100644 --- a/google/cloud/language_v1beta2/gapic_version.py +++ b/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.10.0" # {x-release-please-version} +__version__ = "2.10.1" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index 4e481f59..c9fb8b8a 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.10.1" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index fb6633f2..e97d0475 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "0.1.0" + "version": "2.10.1" }, "snippets": [ { From 696c5427084c4f7445976c651b804b71321647f6 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou <partheniou@google.com> Date: Thu, 6 Jul 2023 17:52:04 -0400 Subject: [PATCH 254/254] build: update README to indicate that source has moved and delete all files (#442) --- .coveragerc | 13 - .flake8 | 33 - .github/.OwlBot.lock.yaml | 17 - .github/.OwlBot.yaml | 26 - .github/CODEOWNERS | 12 - .github/CONTRIBUTING.md | 28 - .github/ISSUE_TEMPLATE/bug_report.md | 43 - .github/ISSUE_TEMPLATE/feature_request.md | 18 - .github/ISSUE_TEMPLATE/support_request.md | 7 - .github/PULL_REQUEST_TEMPLATE.md | 7 - .github/auto-approve.yml | 3 - .github/auto-label.yaml | 15 - .github/header-checker-lint.yml | 15 - .github/release-please.yml | 12 - .github/release-trigger.yml | 1 - .github/snippet-bot.yml | 0 .github/sync-repo-settings.yaml | 14 - .github/workflows/docs.yml | 38 - .github/workflows/lint.yml | 25 - .github/workflows/unittest.yml | 57 - .gitignore | 63 - .kokoro/build.sh | 59 - .kokoro/continuous/common.cfg | 27 - .kokoro/continuous/continuous.cfg | 1 - .kokoro/continuous/prerelease-deps.cfg | 7 - .kokoro/docker/docs/Dockerfile | 83 - .kokoro/docs/common.cfg | 66 - .kokoro/docs/docs-presubmit.cfg | 28 - .kokoro/docs/docs.cfg | 1 - .kokoro/populate-secrets.sh | 43 - .kokoro/presubmit/common.cfg | 27 - .kokoro/presubmit/prerelease-deps.cfg | 7 - .kokoro/presubmit/presubmit.cfg | 1 - .kokoro/publish-docs.sh | 62 - .kokoro/release.sh | 29 - .kokoro/release/common.cfg | 49 - .kokoro/release/release.cfg | 1 - .kokoro/requirements.in | 10 - .kokoro/requirements.txt | 492 -- .kokoro/samples/lint/common.cfg | 34 - .kokoro/samples/lint/continuous.cfg | 6 - .kokoro/samples/lint/periodic.cfg | 6 - .kokoro/samples/lint/presubmit.cfg | 6 - .kokoro/samples/python3.10/common.cfg | 40 - .kokoro/samples/python3.10/continuous.cfg | 6 - .kokoro/samples/python3.10/periodic-head.cfg | 11 - .kokoro/samples/python3.10/periodic.cfg | 6 - .kokoro/samples/python3.10/presubmit.cfg | 6 - .kokoro/samples/python3.11/common.cfg | 40 - .kokoro/samples/python3.11/continuous.cfg | 6 - .kokoro/samples/python3.11/periodic-head.cfg | 11 - .kokoro/samples/python3.11/periodic.cfg | 6 - .kokoro/samples/python3.11/presubmit.cfg | 6 - .kokoro/samples/python3.7/common.cfg | 40 - .kokoro/samples/python3.7/continuous.cfg | 6 - .kokoro/samples/python3.7/periodic-head.cfg | 11 - .kokoro/samples/python3.7/periodic.cfg | 6 - .kokoro/samples/python3.7/presubmit.cfg | 6 - .kokoro/samples/python3.8/common.cfg | 40 - .kokoro/samples/python3.8/continuous.cfg | 6 - .kokoro/samples/python3.8/periodic-head.cfg | 11 - .kokoro/samples/python3.8/periodic.cfg | 6 - .kokoro/samples/python3.8/presubmit.cfg | 6 - .kokoro/samples/python3.9/common.cfg | 40 - .kokoro/samples/python3.9/continuous.cfg | 6 - .kokoro/samples/python3.9/periodic-head.cfg | 11 - .kokoro/samples/python3.9/periodic.cfg | 6 - .kokoro/samples/python3.9/presubmit.cfg | 6 - .kokoro/test-samples-against-head.sh | 26 - .kokoro/test-samples-impl.sh | 102 - .kokoro/test-samples.sh | 44 - .kokoro/trampoline.sh | 28 - .kokoro/trampoline_v2.sh | 487 -- .pre-commit-config.yaml | 31 - .release-please-manifest.json | 3 - .trampolinerc | 63 - CHANGELOG.md | 460 -- CODE_OF_CONDUCT.md | 95 - CONTRIBUTING.rst | 281 - MANIFEST.in | 25 - README.rst | 5 + UPGRADING.md | 140 - docs/README.rst | 1 - docs/UPGRADING.md | 1 - docs/_static/custom.css | 20 - docs/_templates/layout.html | 50 - docs/changelog.md | 1 - docs/conf.py | 384 -- docs/index.rst | 45 - docs/language_v1/language_service.rst | 6 - docs/language_v1/services.rst | 6 - docs/language_v1/types.rst | 6 - docs/language_v1beta2/language_service.rst | 6 - docs/language_v1beta2/services.rst | 6 - docs/language_v1beta2/types.rst | 6 - docs/multiprocessing.rst | 7 - google/cloud/language/__init__.py | 85 - google/cloud/language/gapic_version.py | 16 - google/cloud/language/py.typed | 2 - google/cloud/language_v1/__init__.py | 80 - google/cloud/language_v1/gapic_metadata.json | 133 - google/cloud/language_v1/gapic_version.py | 16 - google/cloud/language_v1/py.typed | 2 - google/cloud/language_v1/services/__init__.py | 15 - .../services/language_service/__init__.py | 22 - .../services/language_service/async_client.py | 1034 ---- .../services/language_service/client.py | 1190 ----- .../language_service/transports/__init__.py | 36 - .../language_service/transports/base.py | 323 -- .../language_service/transports/grpc.py | 450 -- .../transports/grpc_asyncio.py | 453 -- .../language_service/transports/rest.py | 1158 ---- google/cloud/language_v1/types/__init__.py | 72 - .../language_v1/types/language_service.py | 1732 ------ google/cloud/language_v1beta2/__init__.py | 80 - .../language_v1beta2/gapic_metadata.json | 133 - .../cloud/language_v1beta2/gapic_version.py | 16 - google/cloud/language_v1beta2/py.typed | 2 - .../language_v1beta2/services/__init__.py | 15 - .../services/language_service/__init__.py | 22 - .../services/language_service/async_client.py | 1035 ---- .../services/language_service/client.py | 1191 ----- .../language_service/transports/__init__.py | 36 - .../language_service/transports/base.py | 323 -- .../language_service/transports/grpc.py | 450 -- .../transports/grpc_asyncio.py | 453 -- .../language_service/transports/rest.py | 1158 ---- .../cloud/language_v1beta2/types/__init__.py | 72 - .../types/language_service.py | 1769 ------ language-v1beta2-py.tar.gz | 0 mypy.ini | 3 - noxfile.py | 425 -- owlbot.py | 56 - pylint.config.py | 25 - release-please-config.json | 30 - renovate.json | 12 - samples/README.txt | 3 - ...language_service_analyze_entities_async.py | 55 - ..._language_service_analyze_entities_sync.py | 55 - ..._service_analyze_entity_sentiment_async.py | 55 - ...e_service_analyze_entity_sentiment_sync.py | 55 - ...anguage_service_analyze_sentiment_async.py | 55 - ...language_service_analyze_sentiment_sync.py | 55 - ...d_language_service_analyze_syntax_async.py | 55 - ...ed_language_service_analyze_syntax_sync.py | 55 - ...ed_language_service_annotate_text_async.py | 55 - ...ted_language_service_annotate_text_sync.py | 55 - ...ed_language_service_classify_text_async.py | 55 - ...ted_language_service_classify_text_sync.py | 55 - ...ed_language_service_moderate_text_async.py | 55 - ...ted_language_service_moderate_text_sync.py | 55 - ...language_service_analyze_entities_async.py | 55 - ..._language_service_analyze_entities_sync.py | 55 - ..._service_analyze_entity_sentiment_async.py | 55 - ...e_service_analyze_entity_sentiment_sync.py | 55 - ...anguage_service_analyze_sentiment_async.py | 55 - ...language_service_analyze_sentiment_sync.py | 55 - ...d_language_service_analyze_syntax_async.py | 55 - ...ed_language_service_analyze_syntax_sync.py | 55 - ...ed_language_service_annotate_text_async.py | 55 - ...ted_language_service_annotate_text_sync.py | 55 - ...ed_language_service_classify_text_async.py | 55 - ...ted_language_service_classify_text_sync.py | 55 - ...ed_language_service_moderate_text_async.py | 55 - ...ted_language_service_moderate_text_sync.py | 55 - ...pet_metadata_google.cloud.language.v1.json | 1190 ----- ...etadata_google.cloud.language.v1beta2.json | 1190 ----- scripts/decrypt-secrets.sh | 46 - scripts/fixup_language_v1_keywords.py | 182 - scripts/fixup_language_v1beta2_keywords.py | 182 - scripts/readme-gen/readme_gen.py | 69 - scripts/readme-gen/templates/README.tmpl.rst | 87 - scripts/readme-gen/templates/auth.tmpl.rst | 9 - .../templates/auth_api_key.tmpl.rst | 14 - .../templates/install_deps.tmpl.rst | 29 - .../templates/install_portaudio.tmpl.rst | 35 - setup.cfg | 19 - setup.py | 90 - testing/.gitignore | 3 - testing/constraints-3.10.txt | 6 - testing/constraints-3.11.txt | 6 - testing/constraints-3.12.txt | 6 - testing/constraints-3.7.txt | 9 - testing/constraints-3.8.txt | 6 - testing/constraints-3.9.txt | 6 - tests/__init__.py | 15 - tests/unit/__init__.py | 15 - tests/unit/gapic/__init__.py | 15 - tests/unit/gapic/language_v1/__init__.py | 15 - .../language_v1/test_language_service.py | 4735 ---------------- tests/unit/gapic/language_v1beta2/__init__.py | 15 - .../language_v1beta2/test_language_service.py | 4736 ----------------- 192 files changed, 5 insertions(+), 32565 deletions(-) delete mode 100644 .coveragerc delete mode 100644 .flake8 delete mode 100644 .github/.OwlBot.lock.yaml delete mode 100644 .github/.OwlBot.yaml delete mode 100644 .github/CODEOWNERS delete mode 100644 .github/CONTRIBUTING.md delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md delete mode 100644 .github/ISSUE_TEMPLATE/feature_request.md delete mode 100644 .github/ISSUE_TEMPLATE/support_request.md delete mode 100644 .github/PULL_REQUEST_TEMPLATE.md delete mode 100644 .github/auto-approve.yml delete mode 100644 .github/auto-label.yaml delete mode 100644 .github/header-checker-lint.yml delete mode 100644 .github/release-please.yml delete mode 100644 .github/release-trigger.yml delete mode 100644 .github/snippet-bot.yml delete mode 100644 .github/sync-repo-settings.yaml delete mode 100644 .github/workflows/docs.yml delete mode 100644 .github/workflows/lint.yml delete mode 100644 .github/workflows/unittest.yml delete mode 100644 .gitignore delete mode 100755 .kokoro/build.sh delete mode 100644 .kokoro/continuous/common.cfg delete mode 100644 .kokoro/continuous/continuous.cfg delete mode 100644 .kokoro/continuous/prerelease-deps.cfg delete mode 100644 .kokoro/docker/docs/Dockerfile delete mode 100644 .kokoro/docs/common.cfg delete mode 100644 .kokoro/docs/docs-presubmit.cfg delete mode 100644 .kokoro/docs/docs.cfg delete mode 100755 .kokoro/populate-secrets.sh delete mode 100644 .kokoro/presubmit/common.cfg delete mode 100644 .kokoro/presubmit/prerelease-deps.cfg delete mode 100644 .kokoro/presubmit/presubmit.cfg delete mode 100755 .kokoro/publish-docs.sh delete mode 100755 .kokoro/release.sh delete mode 100644 .kokoro/release/common.cfg delete mode 100644 .kokoro/release/release.cfg delete mode 100644 .kokoro/requirements.in delete mode 100644 .kokoro/requirements.txt delete mode 100644 .kokoro/samples/lint/common.cfg delete mode 100644 .kokoro/samples/lint/continuous.cfg delete mode 100644 .kokoro/samples/lint/periodic.cfg delete mode 100644 .kokoro/samples/lint/presubmit.cfg delete mode 100644 .kokoro/samples/python3.10/common.cfg delete mode 100644 .kokoro/samples/python3.10/continuous.cfg delete mode 100644 .kokoro/samples/python3.10/periodic-head.cfg delete mode 100644 .kokoro/samples/python3.10/periodic.cfg delete mode 100644 .kokoro/samples/python3.10/presubmit.cfg delete mode 100644 .kokoro/samples/python3.11/common.cfg delete mode 100644 .kokoro/samples/python3.11/continuous.cfg delete mode 100644 .kokoro/samples/python3.11/periodic-head.cfg delete mode 100644 .kokoro/samples/python3.11/periodic.cfg delete mode 100644 .kokoro/samples/python3.11/presubmit.cfg delete mode 100644 .kokoro/samples/python3.7/common.cfg delete mode 100644 .kokoro/samples/python3.7/continuous.cfg delete mode 100644 .kokoro/samples/python3.7/periodic-head.cfg delete mode 100644 .kokoro/samples/python3.7/periodic.cfg delete mode 100644 .kokoro/samples/python3.7/presubmit.cfg delete mode 100644 .kokoro/samples/python3.8/common.cfg delete mode 100644 .kokoro/samples/python3.8/continuous.cfg delete mode 100644 .kokoro/samples/python3.8/periodic-head.cfg delete mode 100644 .kokoro/samples/python3.8/periodic.cfg delete mode 100644 .kokoro/samples/python3.8/presubmit.cfg delete mode 100644 .kokoro/samples/python3.9/common.cfg delete mode 100644 .kokoro/samples/python3.9/continuous.cfg delete mode 100644 .kokoro/samples/python3.9/periodic-head.cfg delete mode 100644 .kokoro/samples/python3.9/periodic.cfg delete mode 100644 .kokoro/samples/python3.9/presubmit.cfg delete mode 100755 .kokoro/test-samples-against-head.sh delete mode 100755 .kokoro/test-samples-impl.sh delete mode 100755 .kokoro/test-samples.sh delete mode 100755 .kokoro/trampoline.sh delete mode 100755 .kokoro/trampoline_v2.sh delete mode 100644 .pre-commit-config.yaml delete mode 100644 .release-please-manifest.json delete mode 100644 .trampolinerc delete mode 100644 CHANGELOG.md delete mode 100644 CODE_OF_CONDUCT.md delete mode 100644 CONTRIBUTING.rst delete mode 100644 MANIFEST.in delete mode 100644 UPGRADING.md delete mode 120000 docs/README.rst delete mode 120000 docs/UPGRADING.md delete mode 100644 docs/_static/custom.css delete mode 100644 docs/_templates/layout.html delete mode 120000 docs/changelog.md delete mode 100644 docs/conf.py delete mode 100644 docs/index.rst delete mode 100644 docs/language_v1/language_service.rst delete mode 100644 docs/language_v1/services.rst delete mode 100644 docs/language_v1/types.rst delete mode 100644 docs/language_v1beta2/language_service.rst delete mode 100644 docs/language_v1beta2/services.rst delete mode 100644 docs/language_v1beta2/types.rst delete mode 100644 docs/multiprocessing.rst delete mode 100644 google/cloud/language/__init__.py delete mode 100644 google/cloud/language/gapic_version.py delete mode 100644 google/cloud/language/py.typed delete mode 100644 google/cloud/language_v1/__init__.py delete mode 100644 google/cloud/language_v1/gapic_metadata.json delete mode 100644 google/cloud/language_v1/gapic_version.py delete mode 100644 google/cloud/language_v1/py.typed delete mode 100644 google/cloud/language_v1/services/__init__.py delete mode 100644 google/cloud/language_v1/services/language_service/__init__.py delete mode 100644 google/cloud/language_v1/services/language_service/async_client.py delete mode 100644 google/cloud/language_v1/services/language_service/client.py delete mode 100644 google/cloud/language_v1/services/language_service/transports/__init__.py delete mode 100644 google/cloud/language_v1/services/language_service/transports/base.py delete mode 100644 google/cloud/language_v1/services/language_service/transports/grpc.py delete mode 100644 google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py delete mode 100644 google/cloud/language_v1/services/language_service/transports/rest.py delete mode 100644 google/cloud/language_v1/types/__init__.py delete mode 100644 google/cloud/language_v1/types/language_service.py delete mode 100644 google/cloud/language_v1beta2/__init__.py delete mode 100644 google/cloud/language_v1beta2/gapic_metadata.json delete mode 100644 google/cloud/language_v1beta2/gapic_version.py delete mode 100644 google/cloud/language_v1beta2/py.typed delete mode 100644 google/cloud/language_v1beta2/services/__init__.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/__init__.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/async_client.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/client.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/transports/__init__.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/transports/base.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/transports/grpc.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py delete mode 100644 google/cloud/language_v1beta2/services/language_service/transports/rest.py delete mode 100644 google/cloud/language_v1beta2/types/__init__.py delete mode 100644 google/cloud/language_v1beta2/types/language_service.py delete mode 100644 language-v1beta2-py.tar.gz delete mode 100644 mypy.ini delete mode 100644 noxfile.py delete mode 100644 owlbot.py delete mode 100644 pylint.config.py delete mode 100644 release-please-config.json delete mode 100644 renovate.json delete mode 100644 samples/README.txt delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_classify_text_async.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py delete mode 100644 samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py delete mode 100644 samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py delete mode 100644 samples/generated_samples/snippet_metadata_google.cloud.language.v1.json delete mode 100644 samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json delete mode 100755 scripts/decrypt-secrets.sh delete mode 100644 scripts/fixup_language_v1_keywords.py delete mode 100644 scripts/fixup_language_v1beta2_keywords.py delete mode 100644 scripts/readme-gen/readme_gen.py delete mode 100644 scripts/readme-gen/templates/README.tmpl.rst delete mode 100644 scripts/readme-gen/templates/auth.tmpl.rst delete mode 100644 scripts/readme-gen/templates/auth_api_key.tmpl.rst delete mode 100644 scripts/readme-gen/templates/install_deps.tmpl.rst delete mode 100644 scripts/readme-gen/templates/install_portaudio.tmpl.rst delete mode 100644 setup.cfg delete mode 100644 setup.py delete mode 100644 testing/.gitignore delete mode 100644 testing/constraints-3.10.txt delete mode 100644 testing/constraints-3.11.txt delete mode 100644 testing/constraints-3.12.txt delete mode 100644 testing/constraints-3.7.txt delete mode 100644 testing/constraints-3.8.txt delete mode 100644 testing/constraints-3.9.txt delete mode 100644 tests/__init__.py delete mode 100644 tests/unit/__init__.py delete mode 100644 tests/unit/gapic/__init__.py delete mode 100644 tests/unit/gapic/language_v1/__init__.py delete mode 100644 tests/unit/gapic/language_v1/test_language_service.py delete mode 100644 tests/unit/gapic/language_v1beta2/__init__.py delete mode 100644 tests/unit/gapic/language_v1beta2/test_language_service.py diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index c1f51536..00000000 --- a/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/language/__init__.py - google/cloud/language/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 2e438749..00000000 --- a/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E231, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml deleted file mode 100644 index 98994f47..00000000 --- a/.github/.OwlBot.lock.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright 2023 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/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:2d816f26f728ac8b24248741e7d4c461c09764ef9f7be3684d557c9632e46dbd -# created: 2023-06-28T17:03:33.371210701Z diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml deleted file mode 100644 index 88452d4a..00000000 --- a/.github/.OwlBot.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# 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/cloud-devrel-public-resources/owlbot-python:latest - -deep-remove-regex: - - /owl-bot-staging - -deep-copy-regex: - - source: /google/cloud/language/(v.*)/.*-py/(.*) - dest: /owl-bot-staging/$1/$2 - -begin-after-commit-hash: 6a5da3f1274b088752f074da5bc9e30bd1beb27e - diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index 62aced93..00000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,12 +0,0 @@ -# Code owners file. -# This file controls who is tagged for review for any given pull request. -# -# For syntax help see: -# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax -# Note: This file is autogenerated. To make changes to the codeowner team, please update .repo-metadata.json. - -# @googleapis/yoshi-python @googleapis/cdpe-cloudai are the default owners for changes in this repo -* @googleapis/yoshi-python @googleapis/cdpe-cloudai - -# @googleapis/python-samples-reviewers @googleapis/cdpe-cloudai are the default owners for samples changes -/samples/ @googleapis/python-samples-reviewers @googleapis/cdpe-cloudai diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index 939e5341..00000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,28 +0,0 @@ -# How to Contribute - -We'd love to accept your patches and contributions to this project. There are -just a few small guidelines you need to follow. - -## Contributor License Agreement - -Contributions to this project must be accompanied by a Contributor License -Agreement. You (or your employer) retain the copyright to your contribution; -this simply gives us permission to use and redistribute your contributions as -part of the project. Head over to <https://cla.developers.google.com/> to see -your current agreements on file or to sign a new one. - -You generally only need to submit a CLA once, so if you've already submitted one -(even if it was for a different project), you probably don't need to do it -again. - -## Code reviews - -All submissions, including submissions by project members, require review. We -use GitHub pull requests for this purpose. Consult -[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more -information on using pull requests. - -## Community Guidelines - -This project follows [Google's Open Source Community -Guidelines](https://opensource.google.com/conduct/). diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index b9f06f21..00000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - -Thanks for stopping by to let us know something could be better! - -**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response. - -Please run down the following list and make sure you've tried the usual "quick fixes": - - - Search the issues already opened: https://github.com/googleapis/python-language/issues - - Search StackOverflow: https://stackoverflow.com/questions/tagged/google-cloud-platform+python - -If you are still having issues, please be sure to include as much information as possible: - -#### Environment details - - - OS type and version: - - Python version: `python --version` - - pip version: `pip --version` - - `google-cloud-language` version: `pip show google-cloud-language` - -#### Steps to reproduce - - 1. ? - 2. ? - -#### Code example - -```python -# example -``` - -#### Stack trace -``` -# example -``` - -Making sure to follow these steps will guarantee the quickest resolution possible. - -Thanks! diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 6365857f..00000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this library - ---- - -Thanks for stopping by to let us know something could be better! - -**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response. - - **Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - **Describe the solution you'd like** -A clear and concise description of what you want to happen. - **Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - **Additional context** -Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/support_request.md b/.github/ISSUE_TEMPLATE/support_request.md deleted file mode 100644 index 99586903..00000000 --- a/.github/ISSUE_TEMPLATE/support_request.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -name: Support request -about: If you have a support contract with Google, please create an issue in the Google Cloud Support console. - ---- - -**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index b7ee4967..00000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,7 +0,0 @@ -Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly: -- [ ] Make sure to open an issue as a [bug/issue](https://github.com/googleapis/python-language/issues/new/choose) before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea -- [ ] Ensure the tests and linter pass -- [ ] Code coverage does not decrease (if any source code was changed) -- [ ] Appropriate docs were updated (if necessary) - -Fixes #<issue_number_goes_here> 🦕 diff --git a/.github/auto-approve.yml b/.github/auto-approve.yml deleted file mode 100644 index 311ebbb8..00000000 --- a/.github/auto-approve.yml +++ /dev/null @@ -1,3 +0,0 @@ -# https://github.com/googleapis/repo-automation-bots/tree/main/packages/auto-approve -processes: - - "OwlBotTemplateChanges" diff --git a/.github/auto-label.yaml b/.github/auto-label.yaml deleted file mode 100644 index 41bff0b5..00000000 --- a/.github/auto-label.yaml +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2022 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. -requestsize: - enabled: true diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml deleted file mode 100644 index 6fe78aa7..00000000 --- a/.github/header-checker-lint.yml +++ /dev/null @@ -1,15 +0,0 @@ -{"allowedCopyrightHolders": ["Google LLC"], - "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], - "sourceFileExtensions": [ - "ts", - "js", - "java", - "sh", - "Dockerfile", - "yaml", - "py", - "html", - "txt" - ] -} \ No newline at end of file diff --git a/.github/release-please.yml b/.github/release-please.yml deleted file mode 100644 index fe749ff6..00000000 --- a/.github/release-please.yml +++ /dev/null @@ -1,12 +0,0 @@ -releaseType: python -handleGHRelease: true -manifest: true -# NOTE: this section is generated by synthtool.languages.python -# See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py -branches: -- branch: v1 - handleGHRelease: true - releaseType: python -- branch: v0 - handleGHRelease: true - releaseType: python diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml deleted file mode 100644 index d4ca9418..00000000 --- a/.github/release-trigger.yml +++ /dev/null @@ -1 +0,0 @@ -enabled: true diff --git a/.github/snippet-bot.yml b/.github/snippet-bot.yml deleted file mode 100644 index e69de29b..00000000 diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml deleted file mode 100644 index c60c5300..00000000 --- a/.github/sync-repo-settings.yaml +++ /dev/null @@ -1,14 +0,0 @@ -# https://github.com/googleapis/repo-automation-bots/tree/master/packages/sync-repo-settings -# Rules for master branch protection -branchProtectionRules: -# Identifies the protection rule pattern. Name of the branch to be protected. -# Defaults to `master` -- pattern: master - requiresCodeOwnerReviews: true - requiresStrictStatusChecks: true - requiredStatusCheckContexts: - - 'Kokoro' - - 'cla/google' - - 'Samples - Lint' - - 'Samples - Python 3.7' - - 'Samples - Python 3.8' diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml deleted file mode 100644 index e97d89e4..00000000 --- a/.github/workflows/docs.yml +++ /dev/null @@ -1,38 +0,0 @@ -on: - pull_request: - branches: - - main -name: docs -jobs: - docs: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Setup Python - uses: actions/setup-python@v4 - with: - python-version: "3.9" - - name: Install nox - run: | - python -m pip install --upgrade setuptools pip wheel - python -m pip install nox - - name: Run docs - run: | - nox -s docs - docfx: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Setup Python - uses: actions/setup-python@v4 - with: - python-version: "3.9" - - name: Install nox - run: | - python -m pip install --upgrade setuptools pip wheel - python -m pip install nox - - name: Run docfx - run: | - nox -s docfx diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml deleted file mode 100644 index 16d5a9e9..00000000 --- a/.github/workflows/lint.yml +++ /dev/null @@ -1,25 +0,0 @@ -on: - pull_request: - branches: - - main -name: lint -jobs: - lint: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Setup Python - uses: actions/setup-python@v4 - with: - python-version: "3.8" - - name: Install nox - run: | - python -m pip install --upgrade setuptools pip wheel - python -m pip install nox - - name: Run lint - run: | - nox -s lint - - name: Run lint_setup_py - run: | - nox -s lint_setup_py diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml deleted file mode 100644 index 8057a769..00000000 --- a/.github/workflows/unittest.yml +++ /dev/null @@ -1,57 +0,0 @@ -on: - pull_request: - branches: - - main -name: unittest -jobs: - unit: - runs-on: ubuntu-latest - strategy: - matrix: - python: ['3.7', '3.8', '3.9', '3.10', '3.11'] - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Setup Python - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python }} - - name: Install nox - run: | - python -m pip install --upgrade setuptools pip wheel - python -m pip install nox - - name: Run unit tests - env: - COVERAGE_FILE: .coverage-${{ matrix.python }} - run: | - nox -s unit-${{ matrix.python }} - - name: Upload coverage results - uses: actions/upload-artifact@v3 - with: - name: coverage-artifacts - path: .coverage-${{ matrix.python }} - - cover: - runs-on: ubuntu-latest - needs: - - unit - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Setup Python - uses: actions/setup-python@v4 - with: - python-version: "3.8" - - name: Install coverage - run: | - python -m pip install --upgrade setuptools pip wheel - python -m pip install coverage - - name: Download coverage results - uses: actions/download-artifact@v3 - with: - name: coverage-artifacts - path: .coverage-results/ - - name: Report coverage results - run: | - coverage combine .coverage-results/.coverage* - coverage report --show-missing --fail-under=100 diff --git a/.gitignore b/.gitignore deleted file mode 100644 index b4243ced..00000000 --- a/.gitignore +++ /dev/null @@ -1,63 +0,0 @@ -*.py[cod] -*.sw[op] - -# C extensions -*.so - -# Packages -*.egg -*.egg-info -dist -build -eggs -.eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg -lib -lib64 -__pycache__ - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.nox -.cache -.pytest_cache - - -# Mac -.DS_Store - -# JetBrains -.idea - -# VS Code -.vscode - -# emacs -*~ - -# Built documentation -docs/_build -bigquery/docs/generated -docs.metadata - -# Virtual environment -env/ - -# Test logs -coverage.xml -*sponge_log.xml - -# System test environment variables. -system_tests/local_test_setup - -# Make sure a generated file isn't accidentally committed. -pylintrc -pylintrc.test diff --git a/.kokoro/build.sh b/.kokoro/build.sh deleted file mode 100755 index 739ab8d9..00000000 --- a/.kokoro/build.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/bin/bash -# Copyright 2018 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -set -eo pipefail - -if [[ -z "${PROJECT_ROOT:-}" ]]; then - PROJECT_ROOT="github/python-language" -fi - -cd "${PROJECT_ROOT}" - -# Disable buffering, so that the logs stream through. -export PYTHONUNBUFFERED=1 - -# Debug: show build environment -env | grep KOKORO - -# Setup service account credentials. -export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/service-account.json - -# Setup project id. -export PROJECT_ID=$(cat "${KOKORO_GFILE_DIR}/project-id.json") - -# Remove old nox -python3 -m pip uninstall --yes --quiet nox-automation - -# Install nox -python3 -m pip install --upgrade --quiet nox -python3 -m nox --version - -# If this is a continuous build, send the test log to the FlakyBot. -# See https://github.com/googleapis/repo-automation-bots/tree/main/packages/flakybot. -if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]]; then - cleanup() { - chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot - $KOKORO_GFILE_DIR/linux_amd64/flakybot - } - trap cleanup EXIT HUP -fi - -# If NOX_SESSION is set, it only runs the specified session, -# otherwise run all the sessions. -if [[ -n "${NOX_SESSION:-}" ]]; then - python3 -m nox -s ${NOX_SESSION:-} -else - python3 -m nox -fi diff --git a/.kokoro/continuous/common.cfg b/.kokoro/continuous/common.cfg deleted file mode 100644 index ba6c6dd9..00000000 --- a/.kokoro/continuous/common.cfg +++ /dev/null @@ -1,27 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-python" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-multi" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/build.sh" -} diff --git a/.kokoro/continuous/continuous.cfg b/.kokoro/continuous/continuous.cfg deleted file mode 100644 index 8f43917d..00000000 --- a/.kokoro/continuous/continuous.cfg +++ /dev/null @@ -1 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto \ No newline at end of file diff --git a/.kokoro/continuous/prerelease-deps.cfg b/.kokoro/continuous/prerelease-deps.cfg deleted file mode 100644 index 3595fb43..00000000 --- a/.kokoro/continuous/prerelease-deps.cfg +++ /dev/null @@ -1,7 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Only run this nox session. -env_vars: { - key: "NOX_SESSION" - value: "prerelease_deps" -} diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile deleted file mode 100644 index f8137d0a..00000000 --- a/.kokoro/docker/docs/Dockerfile +++ /dev/null @@ -1,83 +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. - -from ubuntu:22.04 - -ENV DEBIAN_FRONTEND noninteractive - -# Ensure local Python is preferred over distribution Python. -ENV PATH /usr/local/bin:$PATH - -# Install dependencies. -RUN apt-get update \ - && apt-get install -y --no-install-recommends \ - apt-transport-https \ - build-essential \ - ca-certificates \ - curl \ - dirmngr \ - git \ - gpg-agent \ - graphviz \ - libbz2-dev \ - libdb5.3-dev \ - libexpat1-dev \ - libffi-dev \ - liblzma-dev \ - libreadline-dev \ - libsnappy-dev \ - libssl-dev \ - libsqlite3-dev \ - portaudio19-dev \ - python3-distutils \ - redis-server \ - software-properties-common \ - ssh \ - sudo \ - tcl \ - tcl-dev \ - tk \ - tk-dev \ - uuid-dev \ - wget \ - zlib1g-dev \ - && add-apt-repository universe \ - && apt-get update \ - && apt-get -y install jq \ - && apt-get clean autoclean \ - && apt-get autoremove -y \ - && rm -rf /var/lib/apt/lists/* \ - && rm -f /var/cache/apt/archives/*.deb - -###################### Install python 3.9.13 - -# Download python 3.9.13 -RUN wget https://www.python.org/ftp/python/3.9.13/Python-3.9.13.tgz - -# Extract files -RUN tar -xvf Python-3.9.13.tgz - -# Install python 3.9.13 -RUN ./Python-3.9.13/configure --enable-optimizations -RUN make altinstall - -###################### Install pip -RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ - && python3 /tmp/get-pip.py \ - && rm /tmp/get-pip.py - -# Test pip -RUN python3 -m pip - -CMD ["python3.8"] diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg deleted file mode 100644 index 520ba420..00000000 --- a/.kokoro/docs/common.cfg +++ /dev/null @@ -1,66 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-lib-docs" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/publish-docs.sh" -} - -env_vars: { - key: "STAGING_BUCKET" - value: "docs-staging" -} - -env_vars: { - key: "V2_STAGING_BUCKET" - # Push google cloud library docs to the Cloud RAD bucket `docs-staging-v2` - value: "docs-staging-v2" -} - -# It will upload the docker image after successful builds. -env_vars: { - key: "TRAMPOLINE_IMAGE_UPLOAD" - value: "true" -} - -# It will always build the docker image. -env_vars: { - key: "TRAMPOLINE_DOCKERFILE" - value: ".kokoro/docker/docs/Dockerfile" -} - -# Fetch the token needed for reporting release status to GitHub -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "yoshi-automation-github-key" - } - } -} - -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "docuploader_service_account" - } - } -} \ No newline at end of file diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg deleted file mode 100644 index 8ea6c422..00000000 --- a/.kokoro/docs/docs-presubmit.cfg +++ /dev/null @@ -1,28 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "STAGING_BUCKET" - value: "gcloud-python-test" -} - -env_vars: { - key: "V2_STAGING_BUCKET" - value: "gcloud-python-test" -} - -# We only upload the image in the main `docs` build. -env_vars: { - key: "TRAMPOLINE_IMAGE_UPLOAD" - value: "false" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/build.sh" -} - -# Only run this nox session. -env_vars: { - key: "NOX_SESSION" - value: "docs docfx" -} diff --git a/.kokoro/docs/docs.cfg b/.kokoro/docs/docs.cfg deleted file mode 100644 index 8f43917d..00000000 --- a/.kokoro/docs/docs.cfg +++ /dev/null @@ -1 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto \ No newline at end of file diff --git a/.kokoro/populate-secrets.sh b/.kokoro/populate-secrets.sh deleted file mode 100755 index f5251425..00000000 --- a/.kokoro/populate-secrets.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/bash -# Copyright 2020 Google LLC. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -set -eo pipefail - -function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} -function msg { println "$*" >&2 ;} -function println { printf '%s\n' "$(now) $*" ;} - - -# Populates requested secrets set in SECRET_MANAGER_KEYS from service account: -# kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com -SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" -msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" -mkdir -p ${SECRET_LOCATION} -for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") -do - msg "Retrieving secret ${key}" - docker run --entrypoint=gcloud \ - --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \ - gcr.io/google.com/cloudsdktool/cloud-sdk \ - secrets versions access latest \ - --project cloud-devrel-kokoro-resources \ - --secret ${key} > \ - "${SECRET_LOCATION}/${key}" - if [[ $? == 0 ]]; then - msg "Secret written to ${SECRET_LOCATION}/${key}" - else - msg "Error retrieving secret ${key}" - fi -done diff --git a/.kokoro/presubmit/common.cfg b/.kokoro/presubmit/common.cfg deleted file mode 100644 index ba6c6dd9..00000000 --- a/.kokoro/presubmit/common.cfg +++ /dev/null @@ -1,27 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-python" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-multi" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/build.sh" -} diff --git a/.kokoro/presubmit/prerelease-deps.cfg b/.kokoro/presubmit/prerelease-deps.cfg deleted file mode 100644 index 3595fb43..00000000 --- a/.kokoro/presubmit/prerelease-deps.cfg +++ /dev/null @@ -1,7 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Only run this nox session. -env_vars: { - key: "NOX_SESSION" - value: "prerelease_deps" -} diff --git a/.kokoro/presubmit/presubmit.cfg b/.kokoro/presubmit/presubmit.cfg deleted file mode 100644 index 8f43917d..00000000 --- a/.kokoro/presubmit/presubmit.cfg +++ /dev/null @@ -1 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto \ No newline at end of file diff --git a/.kokoro/publish-docs.sh b/.kokoro/publish-docs.sh deleted file mode 100755 index 1c4d6237..00000000 --- a/.kokoro/publish-docs.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/bash -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -set -eo pipefail - -# Disable buffering, so that the logs stream through. -export PYTHONUNBUFFERED=1 - -export PATH="${HOME}/.local/bin:${PATH}" - -# Install nox -python3 -m pip install --require-hashes -r .kokoro/requirements.txt -python3 -m nox --version - -# build docs -nox -s docs - -# create metadata -python3 -m docuploader create-metadata \ - --name=$(jq --raw-output '.name // empty' .repo-metadata.json) \ - --version=$(python3 setup.py --version) \ - --language=$(jq --raw-output '.language // empty' .repo-metadata.json) \ - --distribution-name=$(python3 setup.py --name) \ - --product-page=$(jq --raw-output '.product_documentation // empty' .repo-metadata.json) \ - --github-repository=$(jq --raw-output '.repo // empty' .repo-metadata.json) \ - --issue-tracker=$(jq --raw-output '.issue_tracker // empty' .repo-metadata.json) - -cat docs.metadata - -# upload docs -python3 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket "${STAGING_BUCKET}" - - -# docfx yaml files -nox -s docfx - -# create metadata. -python3 -m docuploader create-metadata \ - --name=$(jq --raw-output '.name // empty' .repo-metadata.json) \ - --version=$(python3 setup.py --version) \ - --language=$(jq --raw-output '.language // empty' .repo-metadata.json) \ - --distribution-name=$(python3 setup.py --name) \ - --product-page=$(jq --raw-output '.product_documentation // empty' .repo-metadata.json) \ - --github-repository=$(jq --raw-output '.repo // empty' .repo-metadata.json) \ - --issue-tracker=$(jq --raw-output '.issue_tracker // empty' .repo-metadata.json) - -cat docs.metadata - -# upload docs -python3 -m docuploader upload docs/_build/html/docfx_yaml --metadata-file docs.metadata --destination-prefix docfx --staging-bucket "${V2_STAGING_BUCKET}" diff --git a/.kokoro/release.sh b/.kokoro/release.sh deleted file mode 100755 index 02cc73b0..00000000 --- a/.kokoro/release.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -set -eo pipefail - -# Start the releasetool reporter -python3 -m pip install --require-hashes -r github/python-language/.kokoro/requirements.txt -python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script - -# Disable buffering, so that the logs stream through. -export PYTHONUNBUFFERED=1 - -# Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google-cloud-pypi-token-keystore-1") -cd github/python-language -python3 setup.py sdist bdist_wheel -twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg deleted file mode 100644 index f38c1ae4..00000000 --- a/.kokoro/release/common.cfg +++ /dev/null @@ -1,49 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-multi" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/release.sh" -} - -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google-cloud-pypi-token-keystore-1" - } - } -} - -# 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" -} - -# Store the packages we uploaded to PyPI. That way, we have a record of exactly -# what we published, which we can use to generate SBOMs and attestations. -action { - define_artifacts { - regex: "github/python-language/**/*.tar.gz" - strip_prefix: "github/python-language" - } -} diff --git a/.kokoro/release/release.cfg b/.kokoro/release/release.cfg deleted file mode 100644 index 8f43917d..00000000 --- a/.kokoro/release/release.cfg +++ /dev/null @@ -1 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto \ No newline at end of file diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in deleted file mode 100644 index ec867d9f..00000000 --- a/.kokoro/requirements.in +++ /dev/null @@ -1,10 +0,0 @@ -gcp-docuploader -gcp-releasetool>=1.10.5 # required for compatibility with cryptography>=39.x -importlib-metadata -typing-extensions -twine -wheel -setuptools -nox>=2022.11.21 # required to remove dependency on py -charset-normalizer<3 -click<8.1.0 diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt deleted file mode 100644 index c7929db6..00000000 --- a/.kokoro/requirements.txt +++ /dev/null @@ -1,492 +0,0 @@ -# -# This file is autogenerated by pip-compile with Python 3.9 -# by the following command: -# -# pip-compile --allow-unsafe --generate-hashes requirements.in -# -argcomplete==2.0.0 \ - --hash=sha256:6372ad78c89d662035101418ae253668445b391755cfe94ea52f1b9d22425b20 \ - --hash=sha256:cffa11ea77999bb0dd27bb25ff6dc142a6796142f68d45b1a26b11f58724561e - # via nox -attrs==22.1.0 \ - --hash=sha256:29adc2665447e5191d0e7c568fde78b21f9672d344281d0c6e1ab085429b22b6 \ - --hash=sha256:86efa402f67bf2df34f51a335487cf46b1ec130d02b8d39fd248abfd30da551c - # via gcp-releasetool -bleach==5.0.1 \ - --hash=sha256:085f7f33c15bd408dd9b17a4ad77c577db66d76203e5984b1bd59baeee948b2a \ - --hash=sha256:0d03255c47eb9bd2f26aa9bb7f2107732e7e8fe195ca2f64709fcf3b0a4a085c - # via readme-renderer -cachetools==5.2.0 \ - --hash=sha256:6a94c6402995a99c3970cc7e4884bb60b4a8639938157eeed436098bf9831757 \ - --hash=sha256:f9f17d2aec496a9aa6b76f53e3b614c965223c061982d434d160f930c698a9db - # via google-auth -certifi==2022.12.7 \ - --hash=sha256:35824b4c3a97115964b408844d64aa14db1cc518f6562e8d7261699d1350a9e3 \ - --hash=sha256:4ad3232f5e926d6718ec31cfc1fcadfde020920e278684144551c91769c7bc18 - # via requests -cffi==1.15.1 \ - --hash=sha256:00a9ed42e88df81ffae7a8ab6d9356b371399b91dbdf0c3cb1e84c03a13aceb5 \ - --hash=sha256:03425bdae262c76aad70202debd780501fabeaca237cdfddc008987c0e0f59ef \ - --hash=sha256:04ed324bda3cda42b9b695d51bb7d54b680b9719cfab04227cdd1e04e5de3104 \ - --hash=sha256:0e2642fe3142e4cc4af0799748233ad6da94c62a8bec3a6648bf8ee68b1c7426 \ - --hash=sha256:173379135477dc8cac4bc58f45db08ab45d228b3363adb7af79436135d028405 \ - --hash=sha256:198caafb44239b60e252492445da556afafc7d1e3ab7a1fb3f0584ef6d742375 \ - --hash=sha256:1e74c6b51a9ed6589199c787bf5f9875612ca4a8a0785fb2d4a84429badaf22a \ - --hash=sha256:2012c72d854c2d03e45d06ae57f40d78e5770d252f195b93f581acf3ba44496e \ - --hash=sha256:21157295583fe8943475029ed5abdcf71eb3911894724e360acff1d61c1d54bc \ - --hash=sha256:2470043b93ff09bf8fb1d46d1cb756ce6132c54826661a32d4e4d132e1977adf \ - --hash=sha256:285d29981935eb726a4399badae8f0ffdff4f5050eaa6d0cfc3f64b857b77185 \ - --hash=sha256:30d78fbc8ebf9c92c9b7823ee18eb92f2e6ef79b45ac84db507f52fbe3ec4497 \ - --hash=sha256:320dab6e7cb2eacdf0e658569d2575c4dad258c0fcc794f46215e1e39f90f2c3 \ - --hash=sha256:33ab79603146aace82c2427da5ca6e58f2b3f2fb5da893ceac0c42218a40be35 \ - --hash=sha256:3548db281cd7d2561c9ad9984681c95f7b0e38881201e157833a2342c30d5e8c \ - --hash=sha256:3799aecf2e17cf585d977b780ce79ff0dc9b78d799fc694221ce814c2c19db83 \ - --hash=sha256:39d39875251ca8f612b6f33e6b1195af86d1b3e60086068be9cc053aa4376e21 \ - --hash=sha256:3b926aa83d1edb5aa5b427b4053dc420ec295a08e40911296b9eb1b6170f6cca \ - --hash=sha256:3bcde07039e586f91b45c88f8583ea7cf7a0770df3a1649627bf598332cb6984 \ - --hash=sha256:3d08afd128ddaa624a48cf2b859afef385b720bb4b43df214f85616922e6a5ac \ - --hash=sha256:3eb6971dcff08619f8d91607cfc726518b6fa2a9eba42856be181c6d0d9515fd \ - --hash=sha256:40f4774f5a9d4f5e344f31a32b5096977b5d48560c5592e2f3d2c4374bd543ee \ - --hash=sha256:4289fc34b2f5316fbb762d75362931e351941fa95fa18789191b33fc4cf9504a \ - --hash=sha256:470c103ae716238bbe698d67ad020e1db9d9dba34fa5a899b5e21577e6d52ed2 \ - --hash=sha256:4f2c9f67e9821cad2e5f480bc8d83b8742896f1242dba247911072d4fa94c192 \ - --hash=sha256:50a74364d85fd319352182ef59c5c790484a336f6db772c1a9231f1c3ed0cbd7 \ - --hash=sha256:54a2db7b78338edd780e7ef7f9f6c442500fb0d41a5a4ea24fff1c929d5af585 \ - --hash=sha256:5635bd9cb9731e6d4a1132a498dd34f764034a8ce60cef4f5319c0541159392f \ - --hash=sha256:59c0b02d0a6c384d453fece7566d1c7e6b7bae4fc5874ef2ef46d56776d61c9e \ - --hash=sha256:5d598b938678ebf3c67377cdd45e09d431369c3b1a5b331058c338e201f12b27 \ - --hash=sha256:5df2768244d19ab7f60546d0c7c63ce1581f7af8b5de3eb3004b9b6fc8a9f84b \ - --hash=sha256:5ef34d190326c3b1f822a5b7a45f6c4535e2f47ed06fec77d3d799c450b2651e \ - --hash=sha256:6975a3fac6bc83c4a65c9f9fcab9e47019a11d3d2cf7f3c0d03431bf145a941e \ - --hash=sha256:6c9a799e985904922a4d207a94eae35c78ebae90e128f0c4e521ce339396be9d \ - --hash=sha256:70df4e3b545a17496c9b3f41f5115e69a4f2e77e94e1d2a8e1070bc0c38c8a3c \ - --hash=sha256:7473e861101c9e72452f9bf8acb984947aa1661a7704553a9f6e4baa5ba64415 \ - --hash=sha256:8102eaf27e1e448db915d08afa8b41d6c7ca7a04b7d73af6514df10a3e74bd82 \ - --hash=sha256:87c450779d0914f2861b8526e035c5e6da0a3199d8f1add1a665e1cbc6fc6d02 \ - --hash=sha256:8b7ee99e510d7b66cdb6c593f21c043c248537a32e0bedf02e01e9553a172314 \ - --hash=sha256:91fc98adde3d7881af9b59ed0294046f3806221863722ba7d8d120c575314325 \ - --hash=sha256:94411f22c3985acaec6f83c6df553f2dbe17b698cc7f8ae751ff2237d96b9e3c \ - --hash=sha256:98d85c6a2bef81588d9227dde12db8a7f47f639f4a17c9ae08e773aa9c697bf3 \ - --hash=sha256:9ad5db27f9cabae298d151c85cf2bad1d359a1b9c686a275df03385758e2f914 \ - --hash=sha256:a0b71b1b8fbf2b96e41c4d990244165e2c9be83d54962a9a1d118fd8657d2045 \ - --hash=sha256:a0f100c8912c114ff53e1202d0078b425bee3649ae34d7b070e9697f93c5d52d \ - --hash=sha256:a591fe9e525846e4d154205572a029f653ada1a78b93697f3b5a8f1f2bc055b9 \ - --hash=sha256:a5c84c68147988265e60416b57fc83425a78058853509c1b0629c180094904a5 \ - --hash=sha256:a66d3508133af6e8548451b25058d5812812ec3798c886bf38ed24a98216fab2 \ - --hash=sha256:a8c4917bd7ad33e8eb21e9a5bbba979b49d9a97acb3a803092cbc1133e20343c \ - --hash=sha256:b3bbeb01c2b273cca1e1e0c5df57f12dce9a4dd331b4fa1635b8bec26350bde3 \ - --hash=sha256:cba9d6b9a7d64d4bd46167096fc9d2f835e25d7e4c121fb2ddfc6528fb0413b2 \ - --hash=sha256:cc4d65aeeaa04136a12677d3dd0b1c0c94dc43abac5860ab33cceb42b801c1e8 \ - --hash=sha256:ce4bcc037df4fc5e3d184794f27bdaab018943698f4ca31630bc7f84a7b69c6d \ - --hash=sha256:cec7d9412a9102bdc577382c3929b337320c4c4c4849f2c5cdd14d7368c5562d \ - --hash=sha256:d400bfb9a37b1351253cb402671cea7e89bdecc294e8016a707f6d1d8ac934f9 \ - --hash=sha256:d61f4695e6c866a23a21acab0509af1cdfd2c013cf256bbf5b6b5e2695827162 \ - --hash=sha256:db0fbb9c62743ce59a9ff687eb5f4afbe77e5e8403d6697f7446e5f609976f76 \ - --hash=sha256:dd86c085fae2efd48ac91dd7ccffcfc0571387fe1193d33b6394db7ef31fe2a4 \ - --hash=sha256:e00b098126fd45523dd056d2efba6c5a63b71ffe9f2bbe1a4fe1716e1d0c331e \ - --hash=sha256:e229a521186c75c8ad9490854fd8bbdd9a0c9aa3a524326b55be83b54d4e0ad9 \ - --hash=sha256:e263d77ee3dd201c3a142934a086a4450861778baaeeb45db4591ef65550b0a6 \ - --hash=sha256:ed9cb427ba5504c1dc15ede7d516b84757c3e3d7868ccc85121d9310d27eed0b \ - --hash=sha256:fa6693661a4c91757f4412306191b6dc88c1703f780c8234035eac011922bc01 \ - --hash=sha256:fcd131dd944808b5bdb38e6f5b53013c5aa4f334c5cad0c72742f6eba4b73db0 - # via cryptography -charset-normalizer==2.1.1 \ - --hash=sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845 \ - --hash=sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f - # via - # -r requirements.in - # requests -click==8.0.4 \ - --hash=sha256:6a7a62563bbfabfda3a38f3023a1db4a35978c0abd76f6c9605ecd6554d6d9b1 \ - --hash=sha256:8458d7b1287c5fb128c90e23381cf99dcde74beaf6c7ff6384ce84d6fe090adb - # via - # -r requirements.in - # gcp-docuploader - # gcp-releasetool -colorlog==6.7.0 \ - --hash=sha256:0d33ca236784a1ba3ff9c532d4964126d8a2c44f1f0cb1d2b0728196f512f662 \ - --hash=sha256:bd94bd21c1e13fac7bd3153f4bc3a7dc0eb0974b8bc2fdf1a989e474f6e582e5 - # via - # gcp-docuploader - # nox -commonmark==0.9.1 \ - --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ - --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 - # via rich -cryptography==41.0.0 \ - --hash=sha256:0ddaee209d1cf1f180f1efa338a68c4621154de0afaef92b89486f5f96047c55 \ - --hash=sha256:14754bcdae909d66ff24b7b5f166d69340ccc6cb15731670435efd5719294895 \ - --hash=sha256:344c6de9f8bda3c425b3a41b319522ba3208551b70c2ae00099c205f0d9fd3be \ - --hash=sha256:34d405ea69a8b34566ba3dfb0521379b210ea5d560fafedf9f800a9a94a41928 \ - --hash=sha256:3680248309d340fda9611498a5319b0193a8dbdb73586a1acf8109d06f25b92d \ - --hash=sha256:3c5ef25d060c80d6d9f7f9892e1d41bb1c79b78ce74805b8cb4aa373cb7d5ec8 \ - --hash=sha256:4ab14d567f7bbe7f1cdff1c53d5324ed4d3fc8bd17c481b395db224fb405c237 \ - --hash=sha256:5c1f7293c31ebc72163a9a0df246f890d65f66b4a40d9ec80081969ba8c78cc9 \ - --hash=sha256:6b71f64beeea341c9b4f963b48ee3b62d62d57ba93eb120e1196b31dc1025e78 \ - --hash=sha256:7d92f0248d38faa411d17f4107fc0bce0c42cae0b0ba5415505df72d751bf62d \ - --hash=sha256:8362565b3835ceacf4dc8f3b56471a2289cf51ac80946f9087e66dc283a810e0 \ - --hash=sha256:84a165379cb9d411d58ed739e4af3396e544eac190805a54ba2e0322feb55c46 \ - --hash=sha256:88ff107f211ea696455ea8d911389f6d2b276aabf3231bf72c8853d22db755c5 \ - --hash=sha256:9f65e842cb02550fac96536edb1d17f24c0a338fd84eaf582be25926e993dde4 \ - --hash=sha256:a4fc68d1c5b951cfb72dfd54702afdbbf0fb7acdc9b7dc4301bbf2225a27714d \ - --hash=sha256:b7f2f5c525a642cecad24ee8670443ba27ac1fab81bba4cc24c7b6b41f2d0c75 \ - --hash=sha256:b846d59a8d5a9ba87e2c3d757ca019fa576793e8758174d3868aecb88d6fc8eb \ - --hash=sha256:bf8fc66012ca857d62f6a347007e166ed59c0bc150cefa49f28376ebe7d992a2 \ - --hash=sha256:f5d0bf9b252f30a31664b6f64432b4730bb7038339bd18b1fafe129cfc2be9be - # via - # gcp-releasetool - # secretstorage -distlib==0.3.6 \ - --hash=sha256:14bad2d9b04d3a36127ac97f30b12a19268f211063d8f8ee4f47108896e11b46 \ - --hash=sha256:f35c4b692542ca110de7ef0bea44d73981caeb34ca0b9b6b2e6d7790dda8f80e - # via virtualenv -docutils==0.19 \ - --hash=sha256:33995a6753c30b7f577febfc2c50411fec6aac7f7ffeb7c4cfe5991072dcf9e6 \ - --hash=sha256:5e1de4d849fee02c63b040a4a3fd567f4ab104defd8a5511fbbc24a8a017efbc - # via readme-renderer -filelock==3.8.0 \ - --hash=sha256:55447caa666f2198c5b6b13a26d2084d26fa5b115c00d065664b2124680c4edc \ - --hash=sha256:617eb4e5eedc82fc5f47b6d61e4d11cb837c56cb4544e39081099fa17ad109d4 - # via virtualenv -gcp-docuploader==0.6.4 \ - --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ - --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf - # via -r requirements.in -gcp-releasetool==1.10.5 \ - --hash=sha256:174b7b102d704b254f2a26a3eda2c684fd3543320ec239baf771542a2e58e109 \ - --hash=sha256:e29d29927fe2ca493105a82958c6873bb2b90d503acac56be2c229e74de0eec9 - # via -r requirements.in -google-api-core==2.10.2 \ - --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ - --hash=sha256:34f24bd1d5f72a8c4519773d99ca6bf080a6c4e041b4e9f024fe230191dda62e - # via - # google-cloud-core - # google-cloud-storage -google-auth==2.14.1 \ - --hash=sha256:ccaa901f31ad5cbb562615eb8b664b3dd0bf5404a67618e642307f00613eda4d \ - --hash=sha256:f5d8701633bebc12e0deea4df8abd8aff31c28b355360597f7f2ee60f2e4d016 - # via - # gcp-releasetool - # google-api-core - # google-cloud-core - # google-cloud-storage -google-cloud-core==2.3.2 \ - --hash=sha256:8417acf6466be2fa85123441696c4badda48db314c607cf1e5d543fa8bdc22fe \ - --hash=sha256:b9529ee7047fd8d4bf4a2182de619154240df17fbe60ead399078c1ae152af9a - # via google-cloud-storage -google-cloud-storage==2.6.0 \ - --hash=sha256:104ca28ae61243b637f2f01455cc8a05e8f15a2a18ced96cb587241cdd3820f5 \ - --hash=sha256:4ad0415ff61abdd8bb2ae81c1f8f7ec7d91a1011613f2db87c614c550f97bfe9 - # via gcp-docuploader -google-crc32c==1.5.0 \ - --hash=sha256:024894d9d3cfbc5943f8f230e23950cd4906b2fe004c72e29b209420a1e6b05a \ - --hash=sha256:02c65b9817512edc6a4ae7c7e987fea799d2e0ee40c53ec573a692bee24de876 \ - --hash=sha256:02ebb8bf46c13e36998aeaad1de9b48f4caf545e91d14041270d9dca767b780c \ - --hash=sha256:07eb3c611ce363c51a933bf6bd7f8e3878a51d124acfc89452a75120bc436289 \ - --hash=sha256:1034d91442ead5a95b5aaef90dbfaca8633b0247d1e41621d1e9f9db88c36298 \ - --hash=sha256:116a7c3c616dd14a3de8c64a965828b197e5f2d121fedd2f8c5585c547e87b02 \ - --hash=sha256:19e0a019d2c4dcc5e598cd4a4bc7b008546b0358bd322537c74ad47a5386884f \ - --hash=sha256:1c7abdac90433b09bad6c43a43af253e688c9cfc1c86d332aed13f9a7c7f65e2 \ - --hash=sha256:1e986b206dae4476f41bcec1faa057851f3889503a70e1bdb2378d406223994a \ - --hash=sha256:272d3892a1e1a2dbc39cc5cde96834c236d5327e2122d3aaa19f6614531bb6eb \ - --hash=sha256:278d2ed7c16cfc075c91378c4f47924c0625f5fc84b2d50d921b18b7975bd210 \ - --hash=sha256:2ad40e31093a4af319dadf503b2467ccdc8f67c72e4bcba97f8c10cb078207b5 \ - --hash=sha256:2e920d506ec85eb4ba50cd4228c2bec05642894d4c73c59b3a2fe20346bd00ee \ - --hash=sha256:3359fc442a743e870f4588fcf5dcbc1bf929df1fad8fb9905cd94e5edb02e84c \ - --hash=sha256:37933ec6e693e51a5b07505bd05de57eee12f3e8c32b07da7e73669398e6630a \ - --hash=sha256:398af5e3ba9cf768787eef45c803ff9614cc3e22a5b2f7d7ae116df8b11e3314 \ - --hash=sha256:3b747a674c20a67343cb61d43fdd9207ce5da6a99f629c6e2541aa0e89215bcd \ - --hash=sha256:461665ff58895f508e2866824a47bdee72497b091c730071f2b7575d5762ab65 \ - --hash=sha256:4c6fdd4fccbec90cc8a01fc00773fcd5fa28db683c116ee3cb35cd5da9ef6c37 \ - --hash=sha256:5829b792bf5822fd0a6f6eb34c5f81dd074f01d570ed7f36aa101d6fc7a0a6e4 \ - --hash=sha256:596d1f98fc70232fcb6590c439f43b350cb762fb5d61ce7b0e9db4539654cc13 \ - --hash=sha256:5ae44e10a8e3407dbe138984f21e536583f2bba1be9491239f942c2464ac0894 \ - --hash=sha256:635f5d4dd18758a1fbd1049a8e8d2fee4ffed124462d837d1a02a0e009c3ab31 \ - --hash=sha256:64e52e2b3970bd891309c113b54cf0e4384762c934d5ae56e283f9a0afcd953e \ - --hash=sha256:66741ef4ee08ea0b2cc3c86916ab66b6aef03768525627fd6a1b34968b4e3709 \ - --hash=sha256:67b741654b851abafb7bc625b6d1cdd520a379074e64b6a128e3b688c3c04740 \ - --hash=sha256:6ac08d24c1f16bd2bf5eca8eaf8304812f44af5cfe5062006ec676e7e1d50afc \ - --hash=sha256:6f998db4e71b645350b9ac28a2167e6632c239963ca9da411523bb439c5c514d \ - --hash=sha256:72218785ce41b9cfd2fc1d6a017dc1ff7acfc4c17d01053265c41a2c0cc39b8c \ - --hash=sha256:74dea7751d98034887dbd821b7aae3e1d36eda111d6ca36c206c44478035709c \ - --hash=sha256:759ce4851a4bb15ecabae28f4d2e18983c244eddd767f560165563bf9aefbc8d \ - --hash=sha256:77e2fd3057c9d78e225fa0a2160f96b64a824de17840351b26825b0848022906 \ - --hash=sha256:7c074fece789b5034b9b1404a1f8208fc2d4c6ce9decdd16e8220c5a793e6f61 \ - --hash=sha256:7c42c70cd1d362284289c6273adda4c6af8039a8ae12dc451dcd61cdabb8ab57 \ - --hash=sha256:7f57f14606cd1dd0f0de396e1e53824c371e9544a822648cd76c034d209b559c \ - --hash=sha256:83c681c526a3439b5cf94f7420471705bbf96262f49a6fe546a6db5f687a3d4a \ - --hash=sha256:8485b340a6a9e76c62a7dce3c98e5f102c9219f4cfbf896a00cf48caf078d438 \ - --hash=sha256:84e6e8cd997930fc66d5bb4fde61e2b62ba19d62b7abd7a69920406f9ecca946 \ - --hash=sha256:89284716bc6a5a415d4eaa11b1726d2d60a0cd12aadf5439828353662ede9dd7 \ - --hash=sha256:8b87e1a59c38f275c0e3676fc2ab6d59eccecfd460be267ac360cc31f7bcde96 \ - --hash=sha256:8f24ed114432de109aa9fd317278518a5af2d31ac2ea6b952b2f7782b43da091 \ - --hash=sha256:98cb4d057f285bd80d8778ebc4fde6b4d509ac3f331758fb1528b733215443ae \ - --hash=sha256:998679bf62b7fb599d2878aa3ed06b9ce688b8974893e7223c60db155f26bd8d \ - --hash=sha256:9ba053c5f50430a3fcfd36f75aff9caeba0440b2d076afdb79a318d6ca245f88 \ - --hash=sha256:9c99616c853bb585301df6de07ca2cadad344fd1ada6d62bb30aec05219c45d2 \ - --hash=sha256:a1fd716e7a01f8e717490fbe2e431d2905ab8aa598b9b12f8d10abebb36b04dd \ - --hash=sha256:a2355cba1f4ad8b6988a4ca3feed5bff33f6af2d7f134852cf279c2aebfde541 \ - --hash=sha256:b1f8133c9a275df5613a451e73f36c2aea4fe13c5c8997e22cf355ebd7bd0728 \ - --hash=sha256:b8667b48e7a7ef66afba2c81e1094ef526388d35b873966d8a9a447974ed9178 \ - --hash=sha256:ba1eb1843304b1e5537e1fca632fa894d6f6deca8d6389636ee5b4797affb968 \ - --hash=sha256:be82c3c8cfb15b30f36768797a640e800513793d6ae1724aaaafe5bf86f8f346 \ - --hash=sha256:c02ec1c5856179f171e032a31d6f8bf84e5a75c45c33b2e20a3de353b266ebd8 \ - --hash=sha256:c672d99a345849301784604bfeaeba4db0c7aae50b95be04dd651fd2a7310b93 \ - --hash=sha256:c6c777a480337ac14f38564ac88ae82d4cd238bf293f0a22295b66eb89ffced7 \ - --hash=sha256:cae0274952c079886567f3f4f685bcaf5708f0a23a5f5216fdab71f81a6c0273 \ - --hash=sha256:cd67cf24a553339d5062eff51013780a00d6f97a39ca062781d06b3a73b15462 \ - --hash=sha256:d3515f198eaa2f0ed49f8819d5732d70698c3fa37384146079b3799b97667a94 \ - --hash=sha256:d5280312b9af0976231f9e317c20e4a61cd2f9629b7bfea6a693d1878a264ebd \ - --hash=sha256:de06adc872bcd8c2a4e0dc51250e9e65ef2ca91be023b9d13ebd67c2ba552e1e \ - --hash=sha256:e1674e4307fa3024fc897ca774e9c7562c957af85df55efe2988ed9056dc4e57 \ - --hash=sha256:e2096eddb4e7c7bdae4bd69ad364e55e07b8316653234a56552d9c988bd2d61b \ - --hash=sha256:e560628513ed34759456a416bf86b54b2476c59144a9138165c9a1575801d0d9 \ - --hash=sha256:edfedb64740750e1a3b16152620220f51d58ff1b4abceb339ca92e934775c27a \ - --hash=sha256:f13cae8cc389a440def0c8c52057f37359014ccbc9dc1f0827936bcd367c6100 \ - --hash=sha256:f314013e7dcd5cf45ab1945d92e713eec788166262ae8deb2cfacd53def27325 \ - --hash=sha256:f583edb943cf2e09c60441b910d6a20b4d9d626c75a36c8fcac01a6c96c01183 \ - --hash=sha256:fd8536e902db7e365f49e7d9029283403974ccf29b13fc7028b97e2295b33556 \ - --hash=sha256:fe70e325aa68fa4b5edf7d1a4b6f691eb04bbccac0ace68e34820d283b5f80d4 - # via google-resumable-media -google-resumable-media==2.4.0 \ - --hash=sha256:2aa004c16d295c8f6c33b2b4788ba59d366677c0a25ae7382436cb30f776deaa \ - --hash=sha256:8d5518502f92b9ecc84ac46779bd4f09694ecb3ba38a3e7ca737a86d15cbca1f - # via google-cloud-storage -googleapis-common-protos==1.57.0 \ - --hash=sha256:27a849d6205838fb6cc3c1c21cb9800707a661bb21c6ce7fb13e99eb1f8a0c46 \ - --hash=sha256:a9f4a1d7f6d9809657b7f1316a1aa527f6664891531bcfcc13b6696e685f443c - # via google-api-core -idna==3.4 \ - --hash=sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4 \ - --hash=sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2 - # via requests -importlib-metadata==5.0.0 \ - --hash=sha256:da31db32b304314d044d3c12c79bd59e307889b287ad12ff387b3500835fc2ab \ - --hash=sha256:ddb0e35065e8938f867ed4928d0ae5bf2a53b7773871bfe6bcc7e4fcdc7dea43 - # via - # -r requirements.in - # keyring - # twine -jaraco-classes==3.2.3 \ - --hash=sha256:2353de3288bc6b82120752201c6b1c1a14b058267fa424ed5ce5984e3b922158 \ - --hash=sha256:89559fa5c1d3c34eff6f631ad80bb21f378dbcbb35dd161fd2c6b93f5be2f98a - # via keyring -jeepney==0.8.0 \ - --hash=sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806 \ - --hash=sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755 - # via - # keyring - # secretstorage -jinja2==3.1.2 \ - --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ - --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 - # via gcp-releasetool -keyring==23.11.0 \ - --hash=sha256:3dd30011d555f1345dec2c262f0153f2f0ca6bca041fb1dc4588349bb4c0ac1e \ - --hash=sha256:ad192263e2cdd5f12875dedc2da13534359a7e760e77f8d04b50968a821c2361 - # via - # gcp-releasetool - # twine -markupsafe==2.1.1 \ - --hash=sha256:0212a68688482dc52b2d45013df70d169f542b7394fc744c02a57374a4207003 \ - --hash=sha256:089cf3dbf0cd6c100f02945abeb18484bd1ee57a079aefd52cffd17fba910b88 \ - --hash=sha256:10c1bfff05d95783da83491be968e8fe789263689c02724e0c691933c52994f5 \ - --hash=sha256:33b74d289bd2f5e527beadcaa3f401e0df0a89927c1559c8566c066fa4248ab7 \ - --hash=sha256:3799351e2336dc91ea70b034983ee71cf2f9533cdff7c14c90ea126bfd95d65a \ - --hash=sha256:3ce11ee3f23f79dbd06fb3d63e2f6af7b12db1d46932fe7bd8afa259a5996603 \ - --hash=sha256:421be9fbf0ffe9ffd7a378aafebbf6f4602d564d34be190fc19a193232fd12b1 \ - --hash=sha256:43093fb83d8343aac0b1baa75516da6092f58f41200907ef92448ecab8825135 \ - --hash=sha256:46d00d6cfecdde84d40e572d63735ef81423ad31184100411e6e3388d405e247 \ - --hash=sha256:4a33dea2b688b3190ee12bd7cfa29d39c9ed176bda40bfa11099a3ce5d3a7ac6 \ - --hash=sha256:4b9fe39a2ccc108a4accc2676e77da025ce383c108593d65cc909add5c3bd601 \ - --hash=sha256:56442863ed2b06d19c37f94d999035e15ee982988920e12a5b4ba29b62ad1f77 \ - --hash=sha256:671cd1187ed5e62818414afe79ed29da836dde67166a9fac6d435873c44fdd02 \ - --hash=sha256:694deca8d702d5db21ec83983ce0bb4b26a578e71fbdbd4fdcd387daa90e4d5e \ - --hash=sha256:6a074d34ee7a5ce3effbc526b7083ec9731bb3cbf921bbe1d3005d4d2bdb3a63 \ - --hash=sha256:6d0072fea50feec76a4c418096652f2c3238eaa014b2f94aeb1d56a66b41403f \ - --hash=sha256:6fbf47b5d3728c6aea2abb0589b5d30459e369baa772e0f37a0320185e87c980 \ - --hash=sha256:7f91197cc9e48f989d12e4e6fbc46495c446636dfc81b9ccf50bb0ec74b91d4b \ - --hash=sha256:86b1f75c4e7c2ac2ccdaec2b9022845dbb81880ca318bb7a0a01fbf7813e3812 \ - --hash=sha256:8dc1c72a69aa7e082593c4a203dcf94ddb74bb5c8a731e4e1eb68d031e8498ff \ - --hash=sha256:8e3dcf21f367459434c18e71b2a9532d96547aef8a871872a5bd69a715c15f96 \ - --hash=sha256:8e576a51ad59e4bfaac456023a78f6b5e6e7651dcd383bcc3e18d06f9b55d6d1 \ - --hash=sha256:96e37a3dc86e80bf81758c152fe66dbf60ed5eca3d26305edf01892257049925 \ - --hash=sha256:97a68e6ada378df82bc9f16b800ab77cbf4b2fada0081794318520138c088e4a \ - --hash=sha256:99a2a507ed3ac881b975a2976d59f38c19386d128e7a9a18b7df6fff1fd4c1d6 \ - --hash=sha256:a49907dd8420c5685cfa064a1335b6754b74541bbb3706c259c02ed65b644b3e \ - --hash=sha256:b09bf97215625a311f669476f44b8b318b075847b49316d3e28c08e41a7a573f \ - --hash=sha256:b7bd98b796e2b6553da7225aeb61f447f80a1ca64f41d83612e6139ca5213aa4 \ - --hash=sha256:b87db4360013327109564f0e591bd2a3b318547bcef31b468a92ee504d07ae4f \ - --hash=sha256:bcb3ed405ed3222f9904899563d6fc492ff75cce56cba05e32eff40e6acbeaa3 \ - --hash=sha256:d4306c36ca495956b6d568d276ac11fdd9c30a36f1b6eb928070dc5360b22e1c \ - --hash=sha256:d5ee4f386140395a2c818d149221149c54849dfcfcb9f1debfe07a8b8bd63f9a \ - --hash=sha256:dda30ba7e87fbbb7eab1ec9f58678558fd9a6b8b853530e176eabd064da81417 \ - --hash=sha256:e04e26803c9c3851c931eac40c695602c6295b8d432cbe78609649ad9bd2da8a \ - --hash=sha256:e1c0b87e09fa55a220f058d1d49d3fb8df88fbfab58558f1198e08c1e1de842a \ - --hash=sha256:e72591e9ecd94d7feb70c1cbd7be7b3ebea3f548870aa91e2732960fa4d57a37 \ - --hash=sha256:e8c843bbcda3a2f1e3c2ab25913c80a3c5376cd00c6e8c4a86a89a28c8dc5452 \ - --hash=sha256:efc1913fd2ca4f334418481c7e595c00aad186563bbc1ec76067848c7ca0a933 \ - --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \ - --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7 - # via jinja2 -more-itertools==9.0.0 \ - --hash=sha256:250e83d7e81d0c87ca6bd942e6aeab8cc9daa6096d12c5308f3f92fa5e5c1f41 \ - --hash=sha256:5a6257e40878ef0520b1803990e3e22303a41b5714006c32a3fd8304b26ea1ab - # via jaraco-classes -nox==2022.11.21 \ - --hash=sha256:0e41a990e290e274cb205a976c4c97ee3c5234441a8132c8c3fd9ea3c22149eb \ - --hash=sha256:e21c31de0711d1274ca585a2c5fde36b1aa962005ba8e9322bf5eeed16dcd684 - # via -r requirements.in -packaging==21.3 \ - --hash=sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb \ - --hash=sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522 - # via - # gcp-releasetool - # nox -pkginfo==1.8.3 \ - --hash=sha256:848865108ec99d4901b2f7e84058b6e7660aae8ae10164e015a6dcf5b242a594 \ - --hash=sha256:a84da4318dd86f870a9447a8c98340aa06216bfc6f2b7bdc4b8766984ae1867c - # via twine -platformdirs==2.5.4 \ - --hash=sha256:1006647646d80f16130f052404c6b901e80ee4ed6bef6792e1f238a8969106f7 \ - --hash=sha256:af0276409f9a02373d540bf8480021a048711d572745aef4b7842dad245eba10 - # via virtualenv -protobuf==3.20.3 \ - --hash=sha256:03038ac1cfbc41aa21f6afcbcd357281d7521b4157926f30ebecc8d4ea59dcb7 \ - --hash=sha256:28545383d61f55b57cf4df63eebd9827754fd2dc25f80c5253f9184235db242c \ - --hash=sha256:2e3427429c9cffebf259491be0af70189607f365c2f41c7c3764af6f337105f2 \ - --hash=sha256:398a9e0c3eaceb34ec1aee71894ca3299605fa8e761544934378bbc6c97de23b \ - --hash=sha256:44246bab5dd4b7fbd3c0c80b6f16686808fab0e4aca819ade6e8d294a29c7050 \ - --hash=sha256:447d43819997825d4e71bf5769d869b968ce96848b6479397e29fc24c4a5dfe9 \ - --hash=sha256:67a3598f0a2dcbc58d02dd1928544e7d88f764b47d4a286202913f0b2801c2e7 \ - --hash=sha256:74480f79a023f90dc6e18febbf7b8bac7508420f2006fabd512013c0c238f454 \ - --hash=sha256:819559cafa1a373b7096a482b504ae8a857c89593cf3a25af743ac9ecbd23480 \ - --hash=sha256:899dc660cd599d7352d6f10d83c95df430a38b410c1b66b407a6b29265d66469 \ - --hash=sha256:8c0c984a1b8fef4086329ff8dd19ac77576b384079247c770f29cc8ce3afa06c \ - --hash=sha256:9aae4406ea63d825636cc11ffb34ad3379335803216ee3a856787bcf5ccc751e \ - --hash=sha256:a7ca6d488aa8ff7f329d4c545b2dbad8ac31464f1d8b1c87ad1346717731e4db \ - --hash=sha256:b6cc7ba72a8850621bfec987cb72623e703b7fe2b9127a161ce61e61558ad905 \ - --hash=sha256:bf01b5720be110540be4286e791db73f84a2b721072a3711efff6c324cdf074b \ - --hash=sha256:c02ce36ec760252242a33967d51c289fd0e1c0e6e5cc9397e2279177716add86 \ - --hash=sha256:d9e4432ff660d67d775c66ac42a67cf2453c27cb4d738fc22cb53b5d84c135d4 \ - --hash=sha256:daa564862dd0d39c00f8086f88700fdbe8bc717e993a21e90711acfed02f2402 \ - --hash=sha256:de78575669dddf6099a8a0f46a27e82a1783c557ccc38ee620ed8cc96d3be7d7 \ - --hash=sha256:e64857f395505ebf3d2569935506ae0dfc4a15cb80dc25261176c784662cdcc4 \ - --hash=sha256:f4bd856d702e5b0d96a00ec6b307b0f51c1982c2bf9c0052cf9019e9a544ba99 \ - --hash=sha256:f4c42102bc82a51108e449cbb32b19b180022941c727bac0cfd50170341f16ee - # via - # gcp-docuploader - # gcp-releasetool - # google-api-core -pyasn1==0.4.8 \ - --hash=sha256:39c7e2ec30515947ff4e87fb6f456dfc6e84857d34be479c9d4a4ba4bf46aa5d \ - --hash=sha256:aef77c9fb94a3ac588e87841208bdec464471d9871bd5050a287cc9a475cd0ba - # via - # pyasn1-modules - # rsa -pyasn1-modules==0.2.8 \ - --hash=sha256:905f84c712230b2c592c19470d3ca8d552de726050d1d1716282a1f6146be65e \ - --hash=sha256:a50b808ffeb97cb3601dd25981f6b016cbb3d31fbf57a8b8a87428e6158d0c74 - # via google-auth -pycparser==2.21 \ - --hash=sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9 \ - --hash=sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206 - # via cffi -pygments==2.13.0 \ - --hash=sha256:56a8508ae95f98e2b9bdf93a6be5ae3f7d8af858b43e02c5a2ff083726be40c1 \ - --hash=sha256:f643f331ab57ba3c9d89212ee4a2dabc6e94f117cf4eefde99a0574720d14c42 - # via - # readme-renderer - # rich -pyjwt==2.6.0 \ - --hash=sha256:69285c7e31fc44f68a1feb309e948e0df53259d579295e6cfe2b1792329f05fd \ - --hash=sha256:d83c3d892a77bbb74d3e1a2cfa90afaadb60945205d1095d9221f04466f64c14 - # via gcp-releasetool -pyparsing==3.0.9 \ - --hash=sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb \ - --hash=sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc - # via packaging -pyperclip==1.8.2 \ - --hash=sha256:105254a8b04934f0bc84e9c24eb360a591aaf6535c9def5f29d92af107a9bf57 - # via gcp-releasetool -python-dateutil==2.8.2 \ - --hash=sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86 \ - --hash=sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9 - # via gcp-releasetool -readme-renderer==37.3 \ - --hash=sha256:cd653186dfc73055656f090f227f5cb22a046d7f71a841dfa305f55c9a513273 \ - --hash=sha256:f67a16caedfa71eef48a31b39708637a6f4664c4394801a7b0d6432d13907343 - # via twine -requests==2.31.0 \ - --hash=sha256:58cd2187c01e70e6e26505bca751777aa9f2ee0b7f4300988b709f44e013003f \ - --hash=sha256:942c5a758f98d790eaed1a29cb6eefc7ffb0d1cf7af05c3d2791656dbd6ad1e1 - # via - # gcp-releasetool - # google-api-core - # google-cloud-storage - # requests-toolbelt - # twine -requests-toolbelt==0.10.1 \ - --hash=sha256:18565aa58116d9951ac39baa288d3adb5b3ff975c4f25eee78555d89e8f247f7 \ - --hash=sha256:62e09f7ff5ccbda92772a29f394a49c3ad6cb181d568b1337626b2abb628a63d - # via twine -rfc3986==2.0.0 \ - --hash=sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd \ - --hash=sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c - # via twine -rich==12.6.0 \ - --hash=sha256:a4eb26484f2c82589bd9a17c73d32a010b1e29d89f1604cd9bf3a2097b81bb5e \ - --hash=sha256:ba3a3775974105c221d31141f2c116f4fd65c5ceb0698657a11e9f295ec93fd0 - # via twine -rsa==4.9 \ - --hash=sha256:90260d9058e514786967344d0ef75fa8727eed8a7d2e43ce9f4bcf1b536174f7 \ - --hash=sha256:e38464a49c6c85d7f1351b0126661487a7e0a14a50f1675ec50eb34d4f20ef21 - # via google-auth -secretstorage==3.3.3 \ - --hash=sha256:2403533ef369eca6d2ba81718576c5e0f564d5cca1b58f73a8b23e7d4eeebd77 \ - --hash=sha256:f356e6628222568e3af06f2eba8df495efa13b3b63081dafd4f7d9a7b7bc9f99 - # via keyring -six==1.16.0 \ - --hash=sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926 \ - --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254 - # via - # bleach - # gcp-docuploader - # google-auth - # python-dateutil -twine==4.0.1 \ - --hash=sha256:42026c18e394eac3e06693ee52010baa5313e4811d5a11050e7d48436cf41b9e \ - --hash=sha256:96b1cf12f7ae611a4a40b6ae8e9570215daff0611828f5fe1f37a16255ab24a0 - # via -r requirements.in -typing-extensions==4.4.0 \ - --hash=sha256:1511434bb92bf8dd198c12b1cc812e800d4181cfcb867674e0f8279cc93087aa \ - --hash=sha256:16fa4864408f655d35ec496218b85f79b3437c829e93320c7c9215ccfd92489e - # via -r requirements.in -urllib3==1.26.12 \ - --hash=sha256:3fa96cf423e6987997fc326ae8df396db2a8b7c667747d47ddd8ecba91f4a74e \ - --hash=sha256:b930dd878d5a8afb066a637fbb35144fe7901e3b209d1cd4f524bd0e9deee997 - # via - # requests - # twine -virtualenv==20.16.7 \ - --hash=sha256:8691e3ff9387f743e00f6bb20f70121f5e4f596cae754531f2b3b3a1b1ac696e \ - --hash=sha256:efd66b00386fdb7dbe4822d172303f40cd05e50e01740b19ea42425cbe653e29 - # via nox -webencodings==0.5.1 \ - --hash=sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78 \ - --hash=sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923 - # via bleach -wheel==0.38.4 \ - --hash=sha256:965f5259b566725405b05e7cf774052044b1ed30119b5d586b2703aafe8719ac \ - --hash=sha256:b60533f3f5d530e971d6737ca6d58681ee434818fab630c83a734bb10c083ce8 - # via -r requirements.in -zipp==3.10.0 \ - --hash=sha256:4fcb6f278987a6605757302a6e40e896257570d11c51628968ccb2a47e80c6c1 \ - --hash=sha256:7a7262fd930bd3e36c50b9a64897aec3fafff3dfdeec9623ae22b40e93f99bb8 - # via importlib-metadata - -# The following packages are considered to be unsafe in a requirements file: -setuptools==65.5.1 \ - --hash=sha256:d0b9a8433464d5800cbe05094acf5c6d52a91bfac9b52bcfc4d41382be5d5d31 \ - --hash=sha256:e197a19aa8ec9722928f2206f8de752def0e4c9fc6953527360d1c36d94ddb2f - # via -r requirements.in diff --git a/.kokoro/samples/lint/common.cfg b/.kokoro/samples/lint/common.cfg deleted file mode 100644 index a9caf408..00000000 --- a/.kokoro/samples/lint/common.cfg +++ /dev/null @@ -1,34 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Specify which tests to run -env_vars: { - key: "RUN_TESTS_SESSION" - value: "lint" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples.sh" -} - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" -} - -# Download secrets for samples -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/lint/continuous.cfg b/.kokoro/samples/lint/continuous.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/lint/continuous.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/lint/periodic.cfg b/.kokoro/samples/lint/periodic.cfg deleted file mode 100644 index 50fec964..00000000 --- a/.kokoro/samples/lint/periodic.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "False" -} \ No newline at end of file diff --git a/.kokoro/samples/lint/presubmit.cfg b/.kokoro/samples/lint/presubmit.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/lint/presubmit.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.10/common.cfg b/.kokoro/samples/python3.10/common.cfg deleted file mode 100644 index 27547f0a..00000000 --- a/.kokoro/samples/python3.10/common.cfg +++ /dev/null @@ -1,40 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Specify which tests to run -env_vars: { - key: "RUN_TESTS_SESSION" - value: "py-3.10" -} - -# Declare build specific Cloud project. -env_vars: { - key: "BUILD_SPECIFIC_GCLOUD_PROJECT" - value: "python-docs-samples-tests-310" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples.sh" -} - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" -} - -# Download secrets for samples -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.10/continuous.cfg b/.kokoro/samples/python3.10/continuous.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.10/continuous.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.10/periodic-head.cfg b/.kokoro/samples/python3.10/periodic-head.cfg deleted file mode 100644 index 676f8aa8..00000000 --- a/.kokoro/samples/python3.10/periodic-head.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples-against-head.sh" -} diff --git a/.kokoro/samples/python3.10/periodic.cfg b/.kokoro/samples/python3.10/periodic.cfg deleted file mode 100644 index 71cd1e59..00000000 --- a/.kokoro/samples/python3.10/periodic.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "False" -} diff --git a/.kokoro/samples/python3.10/presubmit.cfg b/.kokoro/samples/python3.10/presubmit.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.10/presubmit.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.11/common.cfg b/.kokoro/samples/python3.11/common.cfg deleted file mode 100644 index 568a26d0..00000000 --- a/.kokoro/samples/python3.11/common.cfg +++ /dev/null @@ -1,40 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Specify which tests to run -env_vars: { - key: "RUN_TESTS_SESSION" - value: "py-3.11" -} - -# Declare build specific Cloud project. -env_vars: { - key: "BUILD_SPECIFIC_GCLOUD_PROJECT" - value: "python-docs-samples-tests-311" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples.sh" -} - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" -} - -# Download secrets for samples -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.11/continuous.cfg b/.kokoro/samples/python3.11/continuous.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.11/continuous.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.11/periodic-head.cfg b/.kokoro/samples/python3.11/periodic-head.cfg deleted file mode 100644 index 676f8aa8..00000000 --- a/.kokoro/samples/python3.11/periodic-head.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples-against-head.sh" -} diff --git a/.kokoro/samples/python3.11/periodic.cfg b/.kokoro/samples/python3.11/periodic.cfg deleted file mode 100644 index 71cd1e59..00000000 --- a/.kokoro/samples/python3.11/periodic.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "False" -} diff --git a/.kokoro/samples/python3.11/presubmit.cfg b/.kokoro/samples/python3.11/presubmit.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.11/presubmit.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg deleted file mode 100644 index 71cf69f9..00000000 --- a/.kokoro/samples/python3.7/common.cfg +++ /dev/null @@ -1,40 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Specify which tests to run -env_vars: { - key: "RUN_TESTS_SESSION" - value: "py-3.7" -} - -# Declare build specific Cloud project. -env_vars: { - key: "BUILD_SPECIFIC_GCLOUD_PROJECT" - value: "python-docs-samples-tests-py37" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples.sh" -} - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" -} - -# Download secrets for samples -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.7/continuous.cfg b/.kokoro/samples/python3.7/continuous.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.7/continuous.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.7/periodic-head.cfg b/.kokoro/samples/python3.7/periodic-head.cfg deleted file mode 100644 index 676f8aa8..00000000 --- a/.kokoro/samples/python3.7/periodic-head.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples-against-head.sh" -} diff --git a/.kokoro/samples/python3.7/periodic.cfg b/.kokoro/samples/python3.7/periodic.cfg deleted file mode 100644 index 71cd1e59..00000000 --- a/.kokoro/samples/python3.7/periodic.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "False" -} diff --git a/.kokoro/samples/python3.7/presubmit.cfg b/.kokoro/samples/python3.7/presubmit.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.7/presubmit.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg deleted file mode 100644 index 086547f2..00000000 --- a/.kokoro/samples/python3.8/common.cfg +++ /dev/null @@ -1,40 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Specify which tests to run -env_vars: { - key: "RUN_TESTS_SESSION" - value: "py-3.8" -} - -# Declare build specific Cloud project. -env_vars: { - key: "BUILD_SPECIFIC_GCLOUD_PROJECT" - value: "python-docs-samples-tests-py38" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples.sh" -} - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" -} - -# Download secrets for samples -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.8/continuous.cfg b/.kokoro/samples/python3.8/continuous.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.8/continuous.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.8/periodic-head.cfg b/.kokoro/samples/python3.8/periodic-head.cfg deleted file mode 100644 index 676f8aa8..00000000 --- a/.kokoro/samples/python3.8/periodic-head.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples-against-head.sh" -} diff --git a/.kokoro/samples/python3.8/periodic.cfg b/.kokoro/samples/python3.8/periodic.cfg deleted file mode 100644 index 71cd1e59..00000000 --- a/.kokoro/samples/python3.8/periodic.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "False" -} diff --git a/.kokoro/samples/python3.8/presubmit.cfg b/.kokoro/samples/python3.8/presubmit.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.8/presubmit.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.9/common.cfg b/.kokoro/samples/python3.9/common.cfg deleted file mode 100644 index f1b3c2c0..00000000 --- a/.kokoro/samples/python3.9/common.cfg +++ /dev/null @@ -1,40 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Specify which tests to run -env_vars: { - key: "RUN_TESTS_SESSION" - value: "py-3.9" -} - -# Declare build specific Cloud project. -env_vars: { - key: "BUILD_SPECIFIC_GCLOUD_PROJECT" - value: "python-docs-samples-tests-py39" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples.sh" -} - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" -} - -# Download secrets for samples -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "python-language/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.9/continuous.cfg b/.kokoro/samples/python3.9/continuous.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.9/continuous.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/samples/python3.9/periodic-head.cfg b/.kokoro/samples/python3.9/periodic-head.cfg deleted file mode 100644 index 676f8aa8..00000000 --- a/.kokoro/samples/python3.9/periodic-head.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/python-language/.kokoro/test-samples-against-head.sh" -} diff --git a/.kokoro/samples/python3.9/periodic.cfg b/.kokoro/samples/python3.9/periodic.cfg deleted file mode 100644 index 71cd1e59..00000000 --- a/.kokoro/samples/python3.9/periodic.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "False" -} diff --git a/.kokoro/samples/python3.9/presubmit.cfg b/.kokoro/samples/python3.9/presubmit.cfg deleted file mode 100644 index a1c8d975..00000000 --- a/.kokoro/samples/python3.9/presubmit.cfg +++ /dev/null @@ -1,6 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -env_vars: { - key: "INSTALL_LIBRARY_FROM_SOURCE" - value: "True" -} \ No newline at end of file diff --git a/.kokoro/test-samples-against-head.sh b/.kokoro/test-samples-against-head.sh deleted file mode 100755 index ba3a707b..00000000 --- a/.kokoro/test-samples-against-head.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# A customized test runner for samples. -# -# For periodic builds, you can specify this file for testing against head. - -# `-e` enables the script to automatically fail when a command fails -# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero -set -eo pipefail -# Enables `**` to include files nested inside sub-folders -shopt -s globstar - -exec .kokoro/test-samples-impl.sh diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh deleted file mode 100755 index 2c6500ca..00000000 --- a/.kokoro/test-samples-impl.sh +++ /dev/null @@ -1,102 +0,0 @@ -#!/bin/bash -# 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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -# `-e` enables the script to automatically fail when a command fails -# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero -set -eo pipefail -# Enables `**` to include files nested inside sub-folders -shopt -s globstar - -# Exit early if samples don't exist -if ! find samples -name 'requirements.txt' | grep -q .; then - echo "No tests run. './samples/**/requirements.txt' not found" - exit 0 -fi - -# Disable buffering, so that the logs stream through. -export PYTHONUNBUFFERED=1 - -# Debug: show build environment -env | grep KOKORO - -# Install nox -python3.9 -m pip install --upgrade --quiet nox - -# Use secrets acessor service account to get secrets -if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then - gcloud auth activate-service-account \ - --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \ - --project="cloud-devrel-kokoro-resources" -fi - -# This script will create 3 files: -# - testing/test-env.sh -# - testing/service-account.json -# - testing/client-secrets.json -./scripts/decrypt-secrets.sh - -source ./testing/test-env.sh -export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json - -# For cloud-run session, we activate the service account for gcloud sdk. -gcloud auth activate-service-account \ - --key-file "${GOOGLE_APPLICATION_CREDENTIALS}" - -export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json - -echo -e "\n******************** TESTING PROJECTS ********************" - -# Switch to 'fail at end' to allow all tests to complete before exiting. -set +e -# Use RTN to return a non-zero value if the test fails. -RTN=0 -ROOT=$(pwd) -# Find all requirements.txt in the samples directory (may break on whitespace). -for file in samples/**/requirements.txt; do - cd "$ROOT" - # Navigate to the project folder. - file=$(dirname "$file") - cd "$file" - - echo "------------------------------------------------------------" - echo "- testing $file" - echo "------------------------------------------------------------" - - # Use nox to execute the tests for the project. - python3.9 -m nox -s "$RUN_TESTS_SESSION" - EXIT=$? - - # If this is a periodic build, send the test log to the FlakyBot. - # See https://github.com/googleapis/repo-automation-bots/tree/main/packages/flakybot. - if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then - chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot - $KOKORO_GFILE_DIR/linux_amd64/flakybot - fi - - if [[ $EXIT -ne 0 ]]; then - RTN=1 - echo -e "\n Testing failed: Nox returned a non-zero exit code. \n" - else - echo -e "\n Testing completed.\n" - fi - -done -cd "$ROOT" - -# Workaround for Kokoro permissions issue: delete secrets -rm testing/{test-env.sh,client-secrets.json,service-account.json} - -exit "$RTN" diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh deleted file mode 100755 index 11c042d3..00000000 --- a/.kokoro/test-samples.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# The default test runner for samples. -# -# For periodic builds, we rewinds the repo to the latest release, and -# run test-samples-impl.sh. - -# `-e` enables the script to automatically fail when a command fails -# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero -set -eo pipefail -# Enables `**` to include files nested inside sub-folders -shopt -s globstar - -# Run periodic samples tests at latest release -if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then - # preserving the test runner implementation. - cp .kokoro/test-samples-impl.sh "${TMPDIR}/test-samples-impl.sh" - echo "--- IMPORTANT IMPORTANT IMPORTANT ---" - echo "Now we rewind the repo back to the latest release..." - LATEST_RELEASE=$(git describe --abbrev=0 --tags) - git checkout $LATEST_RELEASE - echo "The current head is: " - echo $(git rev-parse --verify HEAD) - echo "--- IMPORTANT IMPORTANT IMPORTANT ---" - # move back the test runner implementation if there's no file. - if [ ! -f .kokoro/test-samples-impl.sh ]; then - cp "${TMPDIR}/test-samples-impl.sh" .kokoro/test-samples-impl.sh - fi -fi - -exec .kokoro/test-samples-impl.sh diff --git a/.kokoro/trampoline.sh b/.kokoro/trampoline.sh deleted file mode 100755 index f39236e9..00000000 --- a/.kokoro/trampoline.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash -# 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. - -set -eo pipefail - -# Always run the cleanup script, regardless of the success of bouncing into -# the container. -function cleanup() { - chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh - ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh - echo "cleanup"; -} -trap cleanup EXIT - -$(dirname $0)/populate-secrets.sh # Secret Manager secrets. -python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" \ No newline at end of file diff --git a/.kokoro/trampoline_v2.sh b/.kokoro/trampoline_v2.sh deleted file mode 100755 index 4af6cdc2..00000000 --- a/.kokoro/trampoline_v2.sh +++ /dev/null @@ -1,487 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# trampoline_v2.sh -# -# This script does 3 things. -# -# 1. Prepare the Docker image for the test -# 2. Run the Docker with appropriate flags to run the test -# 3. Upload the newly built Docker image -# -# in a way that is somewhat compatible with trampoline_v1. -# -# To run this script, first download few files from gcs to /dev/shm. -# (/dev/shm is passed into the container as KOKORO_GFILE_DIR). -# -# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/secrets_viewer_service_account.json /dev/shm -# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/automl_secrets.txt /dev/shm -# -# Then run the script. -# .kokoro/trampoline_v2.sh -# -# These environment variables are required: -# TRAMPOLINE_IMAGE: The docker image to use. -# TRAMPOLINE_DOCKERFILE: The location of the Dockerfile. -# -# You can optionally change these environment variables: -# TRAMPOLINE_IMAGE_UPLOAD: -# (true|false): Whether to upload the Docker image after the -# successful builds. -# TRAMPOLINE_BUILD_FILE: The script to run in the docker container. -# TRAMPOLINE_WORKSPACE: The workspace path in the docker container. -# Defaults to /workspace. -# Potentially there are some repo specific envvars in .trampolinerc in -# the project root. - - -set -euo pipefail - -TRAMPOLINE_VERSION="2.0.5" - -if command -v tput >/dev/null && [[ -n "${TERM:-}" ]]; then - readonly IO_COLOR_RED="$(tput setaf 1)" - readonly IO_COLOR_GREEN="$(tput setaf 2)" - readonly IO_COLOR_YELLOW="$(tput setaf 3)" - readonly IO_COLOR_RESET="$(tput sgr0)" -else - readonly IO_COLOR_RED="" - readonly IO_COLOR_GREEN="" - readonly IO_COLOR_YELLOW="" - readonly IO_COLOR_RESET="" -fi - -function function_exists { - [ $(LC_ALL=C type -t $1)"" == "function" ] -} - -# Logs a message using the given color. The first argument must be one -# of the IO_COLOR_* variables defined above, such as -# "${IO_COLOR_YELLOW}". The remaining arguments will be logged in the -# given color. The log message will also have an RFC-3339 timestamp -# prepended (in UTC). You can disable the color output by setting -# TERM=vt100. -function log_impl() { - local color="$1" - shift - local timestamp="$(date -u "+%Y-%m-%dT%H:%M:%SZ")" - echo "================================================================" - echo "${color}${timestamp}:" "$@" "${IO_COLOR_RESET}" - echo "================================================================" -} - -# Logs the given message with normal coloring and a timestamp. -function log() { - log_impl "${IO_COLOR_RESET}" "$@" -} - -# Logs the given message in green with a timestamp. -function log_green() { - log_impl "${IO_COLOR_GREEN}" "$@" -} - -# Logs the given message in yellow with a timestamp. -function log_yellow() { - log_impl "${IO_COLOR_YELLOW}" "$@" -} - -# Logs the given message in red with a timestamp. -function log_red() { - log_impl "${IO_COLOR_RED}" "$@" -} - -readonly tmpdir=$(mktemp -d -t ci-XXXXXXXX) -readonly tmphome="${tmpdir}/h" -mkdir -p "${tmphome}" - -function cleanup() { - rm -rf "${tmpdir}" -} -trap cleanup EXIT - -RUNNING_IN_CI="${RUNNING_IN_CI:-false}" - -# The workspace in the container, defaults to /workspace. -TRAMPOLINE_WORKSPACE="${TRAMPOLINE_WORKSPACE:-/workspace}" - -pass_down_envvars=( - # TRAMPOLINE_V2 variables. - # Tells scripts whether they are running as part of CI or not. - "RUNNING_IN_CI" - # Indicates which CI system we're in. - "TRAMPOLINE_CI" - # Indicates the version of the script. - "TRAMPOLINE_VERSION" -) - -log_yellow "Building with Trampoline ${TRAMPOLINE_VERSION}" - -# Detect which CI systems we're in. If we're in any of the CI systems -# we support, `RUNNING_IN_CI` will be true and `TRAMPOLINE_CI` will be -# the name of the CI system. Both envvars will be passing down to the -# container for telling which CI system we're in. -if [[ -n "${KOKORO_BUILD_ID:-}" ]]; then - # descriptive env var for indicating it's on CI. - RUNNING_IN_CI="true" - TRAMPOLINE_CI="kokoro" - if [[ "${TRAMPOLINE_USE_LEGACY_SERVICE_ACCOUNT:-}" == "true" ]]; then - if [[ ! -f "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" ]]; then - log_red "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json does not exist. Did you forget to mount cloud-devrel-kokoro-resources/trampoline? Aborting." - exit 1 - fi - # This service account will be activated later. - TRAMPOLINE_SERVICE_ACCOUNT="${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" - else - if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then - gcloud auth list - fi - log_yellow "Configuring Container Registry access" - gcloud auth configure-docker --quiet - fi - pass_down_envvars+=( - # KOKORO dynamic variables. - "KOKORO_BUILD_NUMBER" - "KOKORO_BUILD_ID" - "KOKORO_JOB_NAME" - "KOKORO_GIT_COMMIT" - "KOKORO_GITHUB_COMMIT" - "KOKORO_GITHUB_PULL_REQUEST_NUMBER" - "KOKORO_GITHUB_PULL_REQUEST_COMMIT" - # For FlakyBot - "KOKORO_GITHUB_COMMIT_URL" - "KOKORO_GITHUB_PULL_REQUEST_URL" - ) -elif [[ "${TRAVIS:-}" == "true" ]]; then - RUNNING_IN_CI="true" - TRAMPOLINE_CI="travis" - pass_down_envvars+=( - "TRAVIS_BRANCH" - "TRAVIS_BUILD_ID" - "TRAVIS_BUILD_NUMBER" - "TRAVIS_BUILD_WEB_URL" - "TRAVIS_COMMIT" - "TRAVIS_COMMIT_MESSAGE" - "TRAVIS_COMMIT_RANGE" - "TRAVIS_JOB_NAME" - "TRAVIS_JOB_NUMBER" - "TRAVIS_JOB_WEB_URL" - "TRAVIS_PULL_REQUEST" - "TRAVIS_PULL_REQUEST_BRANCH" - "TRAVIS_PULL_REQUEST_SHA" - "TRAVIS_PULL_REQUEST_SLUG" - "TRAVIS_REPO_SLUG" - "TRAVIS_SECURE_ENV_VARS" - "TRAVIS_TAG" - ) -elif [[ -n "${GITHUB_RUN_ID:-}" ]]; then - RUNNING_IN_CI="true" - TRAMPOLINE_CI="github-workflow" - pass_down_envvars+=( - "GITHUB_WORKFLOW" - "GITHUB_RUN_ID" - "GITHUB_RUN_NUMBER" - "GITHUB_ACTION" - "GITHUB_ACTIONS" - "GITHUB_ACTOR" - "GITHUB_REPOSITORY" - "GITHUB_EVENT_NAME" - "GITHUB_EVENT_PATH" - "GITHUB_SHA" - "GITHUB_REF" - "GITHUB_HEAD_REF" - "GITHUB_BASE_REF" - ) -elif [[ "${CIRCLECI:-}" == "true" ]]; then - RUNNING_IN_CI="true" - TRAMPOLINE_CI="circleci" - pass_down_envvars+=( - "CIRCLE_BRANCH" - "CIRCLE_BUILD_NUM" - "CIRCLE_BUILD_URL" - "CIRCLE_COMPARE_URL" - "CIRCLE_JOB" - "CIRCLE_NODE_INDEX" - "CIRCLE_NODE_TOTAL" - "CIRCLE_PREVIOUS_BUILD_NUM" - "CIRCLE_PROJECT_REPONAME" - "CIRCLE_PROJECT_USERNAME" - "CIRCLE_REPOSITORY_URL" - "CIRCLE_SHA1" - "CIRCLE_STAGE" - "CIRCLE_USERNAME" - "CIRCLE_WORKFLOW_ID" - "CIRCLE_WORKFLOW_JOB_ID" - "CIRCLE_WORKFLOW_UPSTREAM_JOB_IDS" - "CIRCLE_WORKFLOW_WORKSPACE_ID" - ) -fi - -# Configure the service account for pulling the docker image. -function repo_root() { - local dir="$1" - while [[ ! -d "${dir}/.git" ]]; do - dir="$(dirname "$dir")" - done - echo "${dir}" -} - -# Detect the project root. In CI builds, we assume the script is in -# the git tree and traverse from there, otherwise, traverse from `pwd` -# to find `.git` directory. -if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then - PROGRAM_PATH="$(realpath "$0")" - PROGRAM_DIR="$(dirname "${PROGRAM_PATH}")" - PROJECT_ROOT="$(repo_root "${PROGRAM_DIR}")" -else - PROJECT_ROOT="$(repo_root $(pwd))" -fi - -log_yellow "Changing to the project root: ${PROJECT_ROOT}." -cd "${PROJECT_ROOT}" - -# To support relative path for `TRAMPOLINE_SERVICE_ACCOUNT`, we need -# to use this environment variable in `PROJECT_ROOT`. -if [[ -n "${TRAMPOLINE_SERVICE_ACCOUNT:-}" ]]; then - - mkdir -p "${tmpdir}/gcloud" - gcloud_config_dir="${tmpdir}/gcloud" - - log_yellow "Using isolated gcloud config: ${gcloud_config_dir}." - export CLOUDSDK_CONFIG="${gcloud_config_dir}" - - log_yellow "Using ${TRAMPOLINE_SERVICE_ACCOUNT} for authentication." - gcloud auth activate-service-account \ - --key-file "${TRAMPOLINE_SERVICE_ACCOUNT}" - log_yellow "Configuring Container Registry access" - gcloud auth configure-docker --quiet -fi - -required_envvars=( - # The basic trampoline configurations. - "TRAMPOLINE_IMAGE" - "TRAMPOLINE_BUILD_FILE" -) - -if [[ -f "${PROJECT_ROOT}/.trampolinerc" ]]; then - source "${PROJECT_ROOT}/.trampolinerc" -fi - -log_yellow "Checking environment variables." -for e in "${required_envvars[@]}" -do - if [[ -z "${!e:-}" ]]; then - log "Missing ${e} env var. Aborting." - exit 1 - fi -done - -# We want to support legacy style TRAMPOLINE_BUILD_FILE used with V1 -# script: e.g. "github/repo-name/.kokoro/run_tests.sh" -TRAMPOLINE_BUILD_FILE="${TRAMPOLINE_BUILD_FILE#github/*/}" -log_yellow "Using TRAMPOLINE_BUILD_FILE: ${TRAMPOLINE_BUILD_FILE}" - -# ignore error on docker operations and test execution -set +e - -log_yellow "Preparing Docker image." -# We only download the docker image in CI builds. -if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then - # Download the docker image specified by `TRAMPOLINE_IMAGE` - - # We may want to add --max-concurrent-downloads flag. - - log_yellow "Start pulling the Docker image: ${TRAMPOLINE_IMAGE}." - if docker pull "${TRAMPOLINE_IMAGE}"; then - log_green "Finished pulling the Docker image: ${TRAMPOLINE_IMAGE}." - has_image="true" - else - log_red "Failed pulling the Docker image: ${TRAMPOLINE_IMAGE}." - has_image="false" - fi -else - # For local run, check if we have the image. - if docker images "${TRAMPOLINE_IMAGE}:latest" | grep "${TRAMPOLINE_IMAGE}"; then - has_image="true" - else - has_image="false" - fi -fi - - -# The default user for a Docker container has uid 0 (root). To avoid -# creating root-owned files in the build directory we tell docker to -# use the current user ID. -user_uid="$(id -u)" -user_gid="$(id -g)" -user_name="$(id -un)" - -# To allow docker in docker, we add the user to the docker group in -# the host os. -docker_gid=$(cut -d: -f3 < <(getent group docker)) - -update_cache="false" -if [[ "${TRAMPOLINE_DOCKERFILE:-none}" != "none" ]]; then - # Build the Docker image from the source. - context_dir=$(dirname "${TRAMPOLINE_DOCKERFILE}") - docker_build_flags=( - "-f" "${TRAMPOLINE_DOCKERFILE}" - "-t" "${TRAMPOLINE_IMAGE}" - "--build-arg" "UID=${user_uid}" - "--build-arg" "USERNAME=${user_name}" - ) - if [[ "${has_image}" == "true" ]]; then - docker_build_flags+=("--cache-from" "${TRAMPOLINE_IMAGE}") - fi - - log_yellow "Start building the docker image." - if [[ "${TRAMPOLINE_VERBOSE:-false}" == "true" ]]; then - echo "docker build" "${docker_build_flags[@]}" "${context_dir}" - fi - - # ON CI systems, we want to suppress docker build logs, only - # output the logs when it fails. - if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then - if docker build "${docker_build_flags[@]}" "${context_dir}" \ - > "${tmpdir}/docker_build.log" 2>&1; then - if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then - cat "${tmpdir}/docker_build.log" - fi - - log_green "Finished building the docker image." - update_cache="true" - else - log_red "Failed to build the Docker image, aborting." - log_yellow "Dumping the build logs:" - cat "${tmpdir}/docker_build.log" - exit 1 - fi - else - if docker build "${docker_build_flags[@]}" "${context_dir}"; then - log_green "Finished building the docker image." - update_cache="true" - else - log_red "Failed to build the Docker image, aborting." - exit 1 - fi - fi -else - if [[ "${has_image}" != "true" ]]; then - log_red "We do not have ${TRAMPOLINE_IMAGE} locally, aborting." - exit 1 - fi -fi - -# We use an array for the flags so they are easier to document. -docker_flags=( - # Remove the container after it exists. - "--rm" - - # Use the host network. - "--network=host" - - # Run in priviledged mode. We are not using docker for sandboxing or - # isolation, just for packaging our dev tools. - "--privileged" - - # Run the docker script with the user id. Because the docker image gets to - # write in ${PWD} you typically want this to be your user id. - # To allow docker in docker, we need to use docker gid on the host. - "--user" "${user_uid}:${docker_gid}" - - # Pass down the USER. - "--env" "USER=${user_name}" - - # Mount the project directory inside the Docker container. - "--volume" "${PROJECT_ROOT}:${TRAMPOLINE_WORKSPACE}" - "--workdir" "${TRAMPOLINE_WORKSPACE}" - "--env" "PROJECT_ROOT=${TRAMPOLINE_WORKSPACE}" - - # Mount the temporary home directory. - "--volume" "${tmphome}:/h" - "--env" "HOME=/h" - - # Allow docker in docker. - "--volume" "/var/run/docker.sock:/var/run/docker.sock" - - # Mount the /tmp so that docker in docker can mount the files - # there correctly. - "--volume" "/tmp:/tmp" - # Pass down the KOKORO_GFILE_DIR and KOKORO_KEYSTORE_DIR - # TODO(tmatsuo): This part is not portable. - "--env" "TRAMPOLINE_SECRET_DIR=/secrets" - "--volume" "${KOKORO_GFILE_DIR:-/dev/shm}:/secrets/gfile" - "--env" "KOKORO_GFILE_DIR=/secrets/gfile" - "--volume" "${KOKORO_KEYSTORE_DIR:-/dev/shm}:/secrets/keystore" - "--env" "KOKORO_KEYSTORE_DIR=/secrets/keystore" -) - -# Add an option for nicer output if the build gets a tty. -if [[ -t 0 ]]; then - docker_flags+=("-it") -fi - -# Passing down env vars -for e in "${pass_down_envvars[@]}" -do - if [[ -n "${!e:-}" ]]; then - docker_flags+=("--env" "${e}=${!e}") - fi -done - -# If arguments are given, all arguments will become the commands run -# in the container, otherwise run TRAMPOLINE_BUILD_FILE. -if [[ $# -ge 1 ]]; then - log_yellow "Running the given commands '" "${@:1}" "' in the container." - readonly commands=("${@:1}") - if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then - echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" - fi - docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" -else - log_yellow "Running the tests in a Docker container." - docker_flags+=("--entrypoint=${TRAMPOLINE_BUILD_FILE}") - if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then - echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" - fi - docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" -fi - - -test_retval=$? - -if [[ ${test_retval} -eq 0 ]]; then - log_green "Build finished with ${test_retval}" -else - log_red "Build finished with ${test_retval}" -fi - -# Only upload it when the test passes. -if [[ "${update_cache}" == "true" ]] && \ - [[ $test_retval == 0 ]] && \ - [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]]; then - log_yellow "Uploading the Docker image." - if docker push "${TRAMPOLINE_IMAGE}"; then - log_green "Finished uploading the Docker image." - else - log_red "Failed uploading the Docker image." - fi - # Call trampoline_after_upload_hook if it's defined. - if function_exists trampoline_after_upload_hook; then - trampoline_after_upload_hook - fi - -fi - -exit "${test_retval}" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 5405cc8f..00000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,31 +0,0 @@ -# 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. -# -# See https://pre-commit.com for more information -# See https://pre-commit.com/hooks.html for more hooks -repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.0.1 - hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml -- repo: https://github.com/psf/black - rev: 22.3.0 - hooks: - - id: black -- repo: https://github.com/pycqa/flake8 - rev: 3.9.2 - hooks: - - id: flake8 diff --git a/.release-please-manifest.json b/.release-please-manifest.json deleted file mode 100644 index 4186d431..00000000 --- a/.release-please-manifest.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - ".": "2.10.1" -} diff --git a/.trampolinerc b/.trampolinerc deleted file mode 100644 index 0eee72ab..00000000 --- a/.trampolinerc +++ /dev/null @@ -1,63 +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. - -# Template for .trampolinerc - -# Add required env vars here. -required_envvars+=( -) - -# Add env vars which are passed down into the container here. -pass_down_envvars+=( - "NOX_SESSION" - ############### - # Docs builds - ############### - "STAGING_BUCKET" - "V2_STAGING_BUCKET" - ################## - # Samples builds - ################## - "INSTALL_LIBRARY_FROM_SOURCE" - "RUN_TESTS_SESSION" - "BUILD_SPECIFIC_GCLOUD_PROJECT" - # Target directories. - "RUN_TESTS_DIRS" - # The nox session to run. - "RUN_TESTS_SESSION" -) - -# Prevent unintentional override on the default image. -if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \ - [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then - echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image." - exit 1 -fi - -# Define the default value if it makes sense. -if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then - TRAMPOLINE_IMAGE_UPLOAD="" -fi - -if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then - TRAMPOLINE_IMAGE="" -fi - -if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then - TRAMPOLINE_DOCKERFILE="" -fi - -if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then - TRAMPOLINE_BUILD_FILE="" -fi diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 4ac2bc15..00000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,460 +0,0 @@ -# Changelog - -[PyPI History][1] - -[1]: https://pypi.org/project/google-cloud-language/#history - -## [2.10.1](https://github.com/googleapis/python-language/compare/v2.10.0...v2.10.1) (2023-07-04) - - -### Bug Fixes - -* Add async context manager return types ([#440](https://github.com/googleapis/python-language/issues/440)) ([f6322f4](https://github.com/googleapis/python-language/commit/f6322f471be25c7f8f5c1392d78ebfcb4f498785)) - -## [2.10.0](https://github.com/googleapis/python-language/compare/v2.9.1...v2.10.0) (2023-05-25) - - -### Features - -* Add support for ModerateText ([#433](https://github.com/googleapis/python-language/issues/433)) ([033a20b](https://github.com/googleapis/python-language/commit/033a20bf9aee96b2cbadd15a36d520b4ec40c7ab)) - -## [2.9.1](https://github.com/googleapis/python-language/compare/v2.9.0...v2.9.1) (2023-03-23) - - -### Documentation - -* Fix formatting of request arg in docstring ([#429](https://github.com/googleapis/python-language/issues/429)) ([475e787](https://github.com/googleapis/python-language/commit/475e787aa7c2cd6a6268c2656d6d9e3cd3a76735)) - -## [2.9.0](https://github.com/googleapis/python-language/compare/v2.8.1...v2.9.0) (2023-02-16) - - -### Features - -* Enable "rest" transport in Python for services supporting numeric enums ([#423](https://github.com/googleapis/python-language/issues/423)) ([21c09b8](https://github.com/googleapis/python-language/commit/21c09b8e009a560c77d96f8fa92c5e91cfdad29f)) - -## [2.8.1](https://github.com/googleapis/python-language/compare/v2.8.0...v2.8.1) (2023-01-20) - - -### Bug Fixes - -* Add context manager return types ([a26c418](https://github.com/googleapis/python-language/commit/a26c418a54cb26825c9c539282ed37cb9d9eac0c)) - - -### Documentation - -* Add documentation for enums ([a26c418](https://github.com/googleapis/python-language/commit/a26c418a54cb26825c9c539282ed37cb9d9eac0c)) - -## [2.8.0](https://github.com/googleapis/python-language/compare/v2.7.0...v2.8.0) (2023-01-10) - - -### Features - -* Add support for python 3.11 ([#413](https://github.com/googleapis/python-language/issues/413)) ([c156e1e](https://github.com/googleapis/python-language/commit/c156e1e67a3430d55664e3abad27951d4af07daf)) - -## [2.7.0](https://github.com/googleapis/python-language/compare/v2.6.1...v2.7.0) (2022-12-14) - - -### Features - -* Add support for `google.cloud.language.__version__` ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) -* Add typing to proto.Message based class attributes ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) - - -### Bug Fixes - -* Add dict typing for client_options ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) -* **deps:** Require google-api-core >=1.34.0, >=2.11.0 ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) -* Drop usage of pkg_resources ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) -* Fix timeout default values ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) - - -### Miscellaneous Chores - -* Release-please updates snippet metadata ([cb52907](https://github.com/googleapis/python-language/commit/cb5290723a1f13d6ea3929cdf2fce103ee464910)) - - -### Documentation - -* **samples:** Snippetgen handling of repeated enum field ([3ff2900](https://github.com/googleapis/python-language/commit/3ff2900b0d4c00d408dc9743d80bb034677be978)) -* **samples:** Snippetgen should call await on the operation coroutine before calling result ([fa4547f](https://github.com/googleapis/python-language/commit/fa4547f61179b9e8a4065bdd0a2bd7760b033985)) -* Specify client library version requirement in samples/v1/language_classify_text.py ([#388](https://github.com/googleapis/python-language/issues/388)) ([bff4a65](https://github.com/googleapis/python-language/commit/bff4a65b6a3bb28bf205cdc2fcf5ad914665c453)) - -## [2.6.1](https://github.com/googleapis/python-language/compare/v2.6.0...v2.6.1) (2022-10-10) - - -### Bug Fixes - -* **deps:** Allow protobuf 3.19.5 ([#385](https://github.com/googleapis/python-language/issues/385)) ([99e1907](https://github.com/googleapis/python-language/commit/99e1907440c08894c213e7d7c9a29618a4b3d0d8)) - -## [2.6.0](https://github.com/googleapis/python-language/compare/v2.5.2...v2.6.0) (2022-09-29) - - -### Features - -* Add support for V1 and V2 classification models ([#376](https://github.com/googleapis/python-language/issues/376)) ([3ba5c56](https://github.com/googleapis/python-language/commit/3ba5c568179b04326ef9cc9874f2d18da99e51d6)) - - -### Bug Fixes - -* **deps:** Require protobuf >= 3.20.2 ([#381](https://github.com/googleapis/python-language/issues/381)) ([06f74b0](https://github.com/googleapis/python-language/commit/06f74b0cba8d3a5191caf5bee814c15bd0371813)) - - -### Documentation - -* Update classification sample to use v2 model ([#378](https://github.com/googleapis/python-language/issues/378)) ([73670e2](https://github.com/googleapis/python-language/commit/73670e27e2c2056f4a53d1225bb99399e8cbd05e)) - -## [2.5.2](https://github.com/googleapis/python-language/compare/v2.5.1...v2.5.2) (2022-08-11) - - -### Bug Fixes - -* **deps:** allow protobuf < 5.0.0 ([#349](https://github.com/googleapis/python-language/issues/349)) ([a9c90c3](https://github.com/googleapis/python-language/commit/a9c90c3706a0108db1b0f7924d02d54c507efaf4)) -* **deps:** require proto-plus >= 1.22.0 ([a9c90c3](https://github.com/googleapis/python-language/commit/a9c90c3706a0108db1b0f7924d02d54c507efaf4)) - -## [2.5.1](https://github.com/googleapis/python-language/compare/v2.5.0...v2.5.1) (2022-07-13) - - -### Bug Fixes - -* **deps:** require google-api-core>=1.32.0,>=2.8.0 ([#339](https://github.com/googleapis/python-language/issues/339)) ([b971d59](https://github.com/googleapis/python-language/commit/b971d5995aad01f97ddde1caf2039ea64ae45c31)) - -## [2.5.0](https://github.com/googleapis/python-language/compare/v2.4.3...v2.5.0) (2022-07-07) - - -### Features - -* add audience parameter ([592e7f8](https://github.com/googleapis/python-language/commit/592e7f85503f40373263b4d36118d6e4542f48cf)) - - -### Bug Fixes - -* **deps:** require google-api-core >= 2.8.0 ([#334](https://github.com/googleapis/python-language/issues/334)) ([592e7f8](https://github.com/googleapis/python-language/commit/592e7f85503f40373263b4d36118d6e4542f48cf)) -* require python 3.7+ ([#336](https://github.com/googleapis/python-language/issues/336)) ([b36b40f](https://github.com/googleapis/python-language/commit/b36b40f1ea7a32ccc3b99c7bb815c89cdd75ff53)) - -## [2.4.3](https://github.com/googleapis/python-language/compare/v2.4.2...v2.4.3) (2022-06-06) - - -### Bug Fixes - -* **deps:** require protobuf <4.0.0dev ([#325](https://github.com/googleapis/python-language/issues/325)) ([1048350](https://github.com/googleapis/python-language/commit/1048350a2b4cf175b445c52bd52142166d104fc6)) - - -### Documentation - -* fix changelog header to consistent size ([#324](https://github.com/googleapis/python-language/issues/324)) ([11aa986](https://github.com/googleapis/python-language/commit/11aa9864db65556a3a27c1a7a99bf96ea60ad434)) - -## [2.4.2](https://github.com/googleapis/python-language/compare/v2.4.1...v2.4.2) (2022-05-17) - - -### Documentation - -* fix type in docstring for map fields ([41c28cd](https://github.com/googleapis/python-language/commit/41c28cd35b91adcbe3221a898419c323875b5cfd)) - -## [2.4.1](https://github.com/googleapis/python-language/compare/v2.4.0...v2.4.1) (2022-03-05) - - -### Bug Fixes - -* **deps:** require google-api-core>=1.31.5, >=2.3.2 ([#273](https://github.com/googleapis/python-language/issues/273)) ([94b2ae4](https://github.com/googleapis/python-language/commit/94b2ae43c46cd6d56e0ee407a44011b42d8e77b1)) -* **deps:** require proto-plus>=1.15.0 ([94b2ae4](https://github.com/googleapis/python-language/commit/94b2ae43c46cd6d56e0ee407a44011b42d8e77b1)) - -## [2.4.0](https://github.com/googleapis/python-language/compare/v2.3.2...v2.4.0) (2022-02-28) - - -### Features - -* add api key support ([#256](https://github.com/googleapis/python-language/issues/256)) ([593ec8a](https://github.com/googleapis/python-language/commit/593ec8a998c612b3a87b4b9a53bd166c0b2c10f6)) - - -### Bug Fixes - -* resolve DuplicateCredentialArgs error when using credentials_file ([3e7c964](https://github.com/googleapis/python-language/commit/3e7c96410914d9080ecd0325c61bdc624adf08e1)) - -## [2.3.2](https://github.com/googleapis/python-language/compare/v2.3.1...v2.3.2) (2022-01-20) - - -### Documentation - -* **samples:** Document -> types.Document ([#227](https://github.com/googleapis/python-language/issues/227)) ([01367d7](https://github.com/googleapis/python-language/commit/01367d7b1e0ddba6e6b920f125730aa97d51ada0)) - -## [2.3.1](https://www.github.com/googleapis/python-language/compare/v2.3.0...v2.3.1) (2021-11-01) - - -### Bug Fixes - -* **deps:** drop packaging dependency ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) -* **deps:** require google-api-core >= 1.28.0 ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) - - -### Documentation - -* list oneofs in docstring ([6374e7f](https://www.github.com/googleapis/python-language/commit/6374e7fc497897fc44c02cd86f57759874c29e82)) - -## [2.3.0](https://www.github.com/googleapis/python-language/compare/v2.2.2...v2.3.0) (2021-10-09) - - -### Features - -* add context manager support in client ([#203](https://www.github.com/googleapis/python-language/issues/203)) ([91d48a8](https://www.github.com/googleapis/python-language/commit/91d48a8fee63b8279b235b70921d018206084b50)) - -## [2.2.2](https://www.github.com/googleapis/python-language/compare/v2.2.1...v2.2.2) (2021-07-28) - - -### Bug Fixes - -* enable self signed jwt for grpc ([#168](https://www.github.com/googleapis/python-language/issues/168)) ([4249607](https://www.github.com/googleapis/python-language/commit/4249607b20905b54b14e84d313838e46727bad54)) - - -### Documentation - -* add Samples section to CONTRIBUTING.rst ([#161](https://www.github.com/googleapis/python-language/issues/161)) ([5c28a16](https://www.github.com/googleapis/python-language/commit/5c28a169c9723fec23fac8bb5e2aa9e0dd420c66)) - - -### Miscellaneous Chores - -* release as 2.2.2 ([#170](https://www.github.com/googleapis/python-language/issues/170)) ([4d40053](https://www.github.com/googleapis/python-language/commit/4d400539508ec81cbc76e3f6166e3ec86054ed65)) - -## [2.2.1](https://www.github.com/googleapis/python-language/compare/v2.2.0...v2.2.1) (2021-07-20) - - -### Bug Fixes - -* **deps:** pin 'google-{api,cloud}-core', 'google-auth' to allow 2.x versions ([#160](https://www.github.com/googleapis/python-language/issues/160)) ([f8f9092](https://www.github.com/googleapis/python-language/commit/f8f90924ca4332016d5bbd9ed131cc82f07c7f9f)) - -## [2.2.0](https://www.github.com/googleapis/python-language/compare/v2.1.0...v2.2.0) (2021-07-01) - - -### Features - -* add always_use_jwt_access ([#138](https://www.github.com/googleapis/python-language/issues/138)) ([242aa5e](https://www.github.com/googleapis/python-language/commit/242aa5e997161104b760f554f69f2eecd86cd560)) - - -### Bug Fixes - -* disable always_use_jwt_access ([#143](https://www.github.com/googleapis/python-language/issues/143)) ([21c9d6e](https://www.github.com/googleapis/python-language/commit/21c9d6e1a96707007bdcf23ce667f02b42c8a207)) - - -### Documentation - -* omit mention of Python 2.7 in 'CONTRIBUTING.rst' ([#1127](https://www.github.com/googleapis/python-language/issues/1127)) ([#132](https://www.github.com/googleapis/python-language/issues/132)) ([bc5f89e](https://www.github.com/googleapis/python-language/commit/bc5f89e3d21bccd2d78ae3f2f4038b19db54871d)) - -## [2.1.0](https://www.github.com/googleapis/python-language/compare/v1.4.0...v2.1.0) (2021-06-16) - - -### Features - -* add 'from_service_account_info' factory to clients ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) -* add common resource helper methods; expose client transport ([#55](https://www.github.com/googleapis/python-language/issues/55)) ([8dde55c](https://www.github.com/googleapis/python-language/commit/8dde55cdd0e956c333039c0b74e49a06dd6ad33b)) -* add from_service_account_info factory and fix sphinx identifiers ([#66](https://www.github.com/googleapis/python-language/issues/66)) ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) -* support self-signed JWT flow for service accounts ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) - - -### Bug Fixes - -* add async client to %name_%version/init.py ([0dcb15e](https://www.github.com/googleapis/python-language/commit/0dcb15eb46b60bd816a6919464be1331c2c8de41)) -* adds underscore to "type" to NL API samples ([#49](https://www.github.com/googleapis/python-language/issues/49)) ([36aa320](https://www.github.com/googleapis/python-language/commit/36aa320bf3e0018d66a7d0c91ce4733f20e9acc0)) -* **deps:** add packaging requirement ([#113](https://www.github.com/googleapis/python-language/issues/113)) ([7e711ac](https://www.github.com/googleapis/python-language/commit/7e711ac63c95c1018d24c7c4db3bc02c191efcfc)) -* fix sphinx identifiers ([cc8a180](https://www.github.com/googleapis/python-language/commit/cc8a18032af7c8d8bf45130898eeae7efb17a91e)) -* remove client recv msg limit fix: add enums to `types/__init__.py` ([#62](https://www.github.com/googleapis/python-language/issues/62)) ([3476c0f](https://www.github.com/googleapis/python-language/commit/3476c0f72529cbcbe61ea5c7e6a22291777bed7e)) -* use correct retry deadlines ([#83](https://www.github.com/googleapis/python-language/issues/83)) ([e2be2d8](https://www.github.com/googleapis/python-language/commit/e2be2d8ecf849940f2ea066655fda3bee68d8a74)) - - -### Documentation - -* fix typos ([#125](https://www.github.com/googleapis/python-language/issues/125)) ([788176f](https://www.github.com/googleapis/python-language/commit/788176feff5fb541e0d16f236b10b765d04ecb98)) - - -### Miscellaneous Chores - -* release as 2.1.0 ([#126](https://www.github.com/googleapis/python-language/issues/126)) ([92fa7f9](https://www.github.com/googleapis/python-language/commit/92fa7f995013c302f3bd3eb6bec53d92d8d9990c)) - -## [2.0.0](https://www.github.com/googleapis/python-language/compare/v1.3.0...v2.0.0) (2020-10-16) - - -### Features - -* Migrate API to use python micro-generator ([#41](https://www.github.com/googleapis/python-language/issues/41)) ([b408b14](https://www.github.com/googleapis/python-language/commit/b408b1431194d8e1373b5d986d476add639f7e87)) - - -### Documentation - -* add multiprocessing note ([#26](https://www.github.com/googleapis/python-language/issues/26)) ([a489102](https://www.github.com/googleapis/python-language/commit/a489102ca0f5ab302ec8974728a52065f2ea8857)) -* add spacing for readability ([#22](https://www.github.com/googleapis/python-language/issues/22)) ([7dff809](https://www.github.com/googleapis/python-language/commit/7dff809b94b5a1d001aeb1e7763dbbe624865600)) -* fix small typo ([#5](https://www.github.com/googleapis/python-language/issues/5)) ([7a9d4dd](https://www.github.com/googleapis/python-language/commit/7a9d4ddf676f2a77e1bd83e02b8d7987a72c6525)) -* **language:** change docstring formatting; bump copyright year to 2020 (via synth) ([#10234](https://www.github.com/googleapis/python-language/issues/10234)) ([b68b216](https://www.github.com/googleapis/python-language/commit/b68b2166d8e4d81a7e51e701f8facdfd7fb82a26)) -* **language:** edit hyphenation of "part-of-speech" (via synth) ([#9954](https://www.github.com/googleapis/python-language/issues/9954)) ([6246ef9](https://www.github.com/googleapis/python-language/commit/6246ef904871405334c0b3bd6c2490b79ffe56fa)) -* **language:** fixes typo in Natural Language samples ([#10134](https://www.github.com/googleapis/python-language/issues/10134)) ([223d614](https://www.github.com/googleapis/python-language/commit/223d6140145dcf5c48af206212db58a062a7937b)) -* add python 2 sunset banner to documentation ([#9036](https://www.github.com/googleapis/python-language/issues/9036)) ([1fe4105](https://www.github.com/googleapis/python-language/commit/1fe4105e078f84f1d4ea713550c26bdf91096d4a)) -* fix intersphinx reference to requests ([#9294](https://www.github.com/googleapis/python-language/issues/9294)) ([e97a0ae](https://www.github.com/googleapis/python-language/commit/e97a0ae6c2e3a26afc9b3af7d91118ac3c0aa1f7)) -* Remove CI for gh-pages, use googleapis.dev for api_core refs. ([#9085](https://www.github.com/googleapis/python-language/issues/9085)) ([6b15df6](https://www.github.com/googleapis/python-language/commit/6b15df6091378ed444642fc813d49d8bbbb6365d)) - -## 1.3.0 - -07-24-2019 16:44 PDT - - -### Implementation Changes -- Allow kwargs to be passed to create_channel ([#8396](https://github.com/googleapis/google-cloud-python/pull/8396)) - -### New Features -- Add 'client_options' support (via synth). ([#8515](https://github.com/googleapis/google-cloud-python/pull/8515)) - -### Dependencies -- Bump minimum version for google-api-core to 1.14.0. ([#8709](https://github.com/googleapis/google-cloud-python/pull/8709)) - -### Documentation -- Link to googleapis.dev documentation in READMEs. ([#8705](https://github.com/googleapis/google-cloud-python/pull/8705)) -- Add compatibility check badges to READMEs. ([#8288](https://github.com/googleapis/google-cloud-python/pull/8288)) -- Add google.api proto annotations, update docstrings (via synth). ([#7659](https://github.com/googleapis/google-cloud-python/pull/7659)) - -### Internal / Testing Changes -- Pin black version (via synth). ([#8588](https://github.com/googleapis/google-cloud-python/pull/8588)) -- Add docs job to publish to googleapis.dev. ([#8464](https://github.com/googleapis/google-cloud-python/pull/8464)) -- Declare encoding as utf-8 in pb2 files (via synth). ([#8357](https://github.com/googleapis/google-cloud-python/pull/8357)) -- Add disclaimer to auto-generated template files (via synth). ([#8319](https://github.com/googleapis/google-cloud-python/pull/8319)) -- Suppress checking 'cov-fail-under' in nox default session (via synth). ([#8246](https://github.com/googleapis/google-cloud-python/pull/8246)) -- Blacken 'noxfile.py' / 'setup.py' (via synth). ([#8158](https://github.com/googleapis/google-cloud-python/pull/8158)) -- Add empty lines (via synth). ([#8063](https://github.com/googleapis/google-cloud-python/pull/8063)) -- Add nox session `docs` (via synth). ([#7776](https://github.com/googleapis/google-cloud-python/pull/7776)) - -## 1.2.0 - -03-29-2019 09:53 PDT - - -### Implementation Changes -- Remove classifier for Python 3.4 for end-of-life. ([#7535](https://github.com/googleapis/google-cloud-python/pull/7535)) -- Protoc-generated serialization update. ([#7087](https://github.com/googleapis/google-cloud-python/pull/7087)) - -### New Features -- Add new entity types (via synth). ([#7510](https://github.com/googleapis/google-cloud-python/pull/7510)) - -### Documentation -- Update client library documentation URLs. ([#7307](https://github.com/googleapis/google-cloud-python/pull/7307)) -- Update copyright headers -- Pick up stub docstring fix in GAPIC generator. ([#6975](https://github.com/googleapis/google-cloud-python/pull/6975)) - -### Internal / Testing Changes -- Copy lintified proto files (via synth). ([#7468](https://github.com/googleapis/google-cloud-python/pull/7468)) -- Add clarifying comment to blacken nox target. ([#7397](https://github.com/googleapis/google-cloud-python/pull/7397)) -- Copy in correct proto versions via synth. [#7257](https://github.com/googleapis/google-cloud-python/pull/7257)) -- Add protos as an artifact to library ([#7205](https://github.com/googleapis/google-cloud-python/pull/7205)) - -## 1.1.1 - -12-18-2018 09:34 PST - - -### Implementation Changes -- Import `iam.policy` from `google.api_core`. ([#6741](https://github.com/googleapis/google-cloud-python/pull/6741)) -- Pick up fixes to GAPIC generator. ([#6521](https://github.com/googleapis/google-cloud-python/pull/6521)) -- Fix `client_info` bug, update docstrings. ([#6415](https://github.com/googleapis/google-cloud-python/pull/6415)) - -### Dependencies -- Bump minimum `api_core` version for all GAPIC libs to 1.4.1. ([#6391](https://github.com/googleapis/google-cloud-python/pull/6391)) - -### Documentation -- Document Python 2 deprecation ([#6910](https://github.com/googleapis/google-cloud-python/pull/6910)) -- Normalize use of support level badges ([#6159](https://github.com/googleapis/google-cloud-python/pull/6159)) -- Fix usage docs example for entity extraction ([#6193](https://github.com/googleapis/google-cloud-python/pull/6193)) - -### Internal / Testing Changes -- Update noxfile. -- Blacken all gen'd libs ([#6792](https://github.com/googleapis/google-cloud-python/pull/6792)) -- Omit local deps ([#6701](https://github.com/googleapis/google-cloud-python/pull/6701)) -- Run black at end of synth.py ([#6698](https://github.com/googleapis/google-cloud-python/pull/6698)) -- Run Black on Generated libraries ([#6666](https://github.com/googleapis/google-cloud-python/pull/6666)) -- Add templates for flake8, coveragerc, noxfile, and black. ([#6642](https://github.com/googleapis/google-cloud-python/pull/6642)) -- Add synth metadata. ([#6570](https://github.com/googleapis/google-cloud-python/pull/6570)) -- Use new Nox ([#6175](https://github.com/googleapis/google-cloud-python/pull/6175)) - -## 1.1.0 - -10-05-2018 13:52 PDT - -### Implementation Changes - -- The library has been regenerated to pick up changes in the underlying API. -- Add Test runs for Python 3.7 and remove 3.4 ([#5295](https://github.com/googleapis/google-cloud-python/pull/5295)) - -### Documentation - -- Translate / Logging / Language: restore detailed usage docs. ([#5999](https://github.com/googleapis/google-cloud-python/pull/5999)) -- Redirect renamed 'usage.html'/'client.html' -> 'index.html'. ([#5996](https://github.com/googleapis/google-cloud-python/pull/5996)) -- Prep language docs for repo split. ([#5932](https://github.com/googleapis/google-cloud-python/pull/5932)) - -### Internal / Testing Changes - -- Language: add 'synth.py'. ([#6080](https://github.com/googleapis/google-cloud-python/pull/6080)) -- Nox: use inplace installs ([#5865](https://github.com/googleapis/google-cloud-python/pull/5865)) -- Avoid overwriting '__module__' of messages from shared modules. ([#5364](https://github.com/googleapis/google-cloud-python/pull/5364)) -- Modify system tests to use prerelease versions of grpcio ([#5304](https://github.com/googleapis/google-cloud-python/pull/5304)) - -## 1.0.2 - -### Packaging -- Update setuptools before packaging (#5265) -- Update setup.py to use recommended method for python-verson specific dependencies (#5266) -- Fix bad trove classifier - -## 1.0.1 - -### Dependencies - -- Update dependency range for api-core to include v1.0.0 releases (#4944) - -### Testing and internal changes - -- Install local dependencies when running lint (#4936) -- Re-enable lint for tests, remove usage of pylint (#4921) -- Normalize all setup.py files (#4909) -- Fix coveragerc to correctly omit generated files (#4843) - -## 1.0.0 - -[![release level](https://img.shields.io/badge/release%20level-general%20availability%20%28GA%29-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) - -### Features - -##### General Availability - -The `google-cloud-language` package is now supported at the **general availability** quality level. This means it is stable; the code and API surface will not change in backwards-incompatible ways unless absolutely necessary (e.g. because of critical security issues) or with an extensive deprecation period. - -One exception to this: We will remove beta endpoints (as a semver-minor update) at whatever point the underlying endpoints go away. - -## 0.31.0 - -### Release Candidate - - * This update is considered a final "release candidate", and - the `google-cloud-language` package is preparing for a GA release - in the near future. - -### :warning: Breaking Changes! - - * Some rarely-used arguments to the `LanguageServiceClient` constructor - have been removed (in favor of a subclass or a custom gRPC channel). - It is unlikely that you used these, but if you did, then this update - will represent a breaking change. - * The removed arguments are: `client_config`, `lib_name`, `lib_version` - `metrics_headers`, `ssl_credentials`, and `scopes`. - -### Features - - * Added the `classify_text` method on the primary (`v1`) endpoint. (#4283) - -## 0.30.0 - -### Documentation - -- Added link to "Python Development Environment Setup Guide" in - project README (#4187, h/t to @michaelawyu) - -### Dependencies - -- Upgrading to `google-cloud-core >= 0.28.0` and adding dependency - on `google-api-core` (#4221, #4280) -- Deferring to `google-api-core` for `grpcio` and - `googleapis-common-protos`dependencies (#4096, #4098) - -PyPI: https://pypi.org/project/google-cloud-language/0.30.0/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 039f4368..00000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,95 +0,0 @@ -<!-- # Generated by synthtool. DO NOT EDIT! !--> -# Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of -experience, education, socio-economic status, nationality, personal appearance, -race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, or to ban temporarily or permanently any -contributor for other behaviors that they deem inappropriate, threatening, -offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -This Code of Conduct also applies outside the project spaces when the Project -Steward has a reasonable belief that an individual's behavior may have a -negative impact on the project or its community. - -## Conflict Resolution - -We do not believe that all conflict is bad; healthy debate and disagreement -often yield positive results. However, it is never okay to be disrespectful or -to engage in behavior that violates the project’s code of conduct. - -If you see someone violating the code of conduct, you are encouraged to address -the behavior directly with those involved. Many issues can be resolved quickly -and easily, and this gives people more control over the outcome of their -dispute. If you are unable to resolve the matter for any reason, or if the -behavior is threatening or harassing, report it. We are dedicated to providing -an environment where participants feel welcome and safe. - - -Reports should be directed to *googleapis-stewards@google.com*, the -Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to -receive and address reported violations of the code of conduct. They will then -work with a committee consisting of representatives from the Open Source -Programs Office and the Google Open Source Strategy team. If for any reason you -are uncomfortable reaching out to the Project Steward, please email -opensource@google.com. - -We will investigate every complaint, but you may not receive a direct response. -We will use our discretion in determining when and how to follow up on reported -incidents, which may range from not taking action to permanent expulsion from -the project and project-sponsored spaces. We will notify the accused of the -report and provide them an opportunity to discuss it before any action is taken. -The identity of the reporter will be omitted from the details of the report -supplied to the accused. In potentially harmful situations, such as ongoing -harassment or threats to anyone's safety, we may take action without notice. - -## Attribution - -This Code of Conduct is adapted from the Contributor Covenant, version 1.4, -available at -https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst deleted file mode 100644 index 15e49507..00000000 --- a/CONTRIBUTING.rst +++ /dev/null @@ -1,281 +0,0 @@ -.. Generated by synthtool. DO NOT EDIT! -############ -Contributing -############ - -#. **Please sign one of the contributor license agreements below.** -#. Fork the repo, develop and test your code changes, add docs. -#. Make sure that your commit messages clearly describe the changes. -#. Send a pull request. (Please Read: `Faster Pull Request Reviews`_) - -.. _Faster Pull Request Reviews: https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews - -.. contents:: Here are some guidelines for hacking on the Google Cloud Client libraries. - -*************** -Adding Features -*************** - -In order to add a feature: - -- The feature must be documented in both the API and narrative - documentation. - -- The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9, 3.10 and 3.11 on both UNIX and Windows. - -- The feature must not add unnecessary dependencies (where - "unnecessary" is of course subjective, but new dependencies should - be discussed). - -**************************** -Using a Development Checkout -**************************** - -You'll have to create a development environment using a Git checkout: - -- While logged into your GitHub account, navigate to the - ``python-language`` `repo`_ on GitHub. - -- Fork and clone the ``python-language`` repository to your GitHub account by - clicking the "Fork" button. - -- Clone your fork of ``python-language`` from your GitHub account to your local - computer, substituting your account username and specifying the destination - as ``hack-on-python-language``. E.g.:: - - $ cd ${HOME} - $ git clone git@github.com:USERNAME/python-language.git hack-on-python-language - $ cd hack-on-python-language - # Configure remotes such that you can pull changes from the googleapis/python-language - # repository into your local repository. - $ git remote add upstream git@github.com:googleapis/python-language.git - # fetch and merge changes from upstream into main - $ git fetch upstream - $ git merge upstream/main - -Now your local repo is set up such that you will push changes to your GitHub -repo, from which you can submit a pull request. - -To work on the codebase and run the tests, we recommend using ``nox``, -but you can also use a ``virtualenv`` of your own creation. - -.. _repo: https://github.com/googleapis/python-language - -Using ``nox`` -============= - -We use `nox <https://nox.readthedocs.io/en/latest/>`__ to instrument our tests. - -- To test your changes, run unit tests with ``nox``:: - $ nox -s unit - -- To run a single unit test:: - - $ nox -s unit-3.11 -- -k <name of test> - - - .. note:: - - The unit tests and system tests are described in the - ``noxfile.py`` files in each directory. - -.. nox: https://pypi.org/project/nox/ - -***************************************** -I'm getting weird errors... Can you help? -***************************************** - -If the error mentions ``Python.h`` not being found, -install ``python-dev`` and try again. -On Debian/Ubuntu:: - - $ sudo apt-get install python-dev - -************ -Coding Style -************ -- We use the automatic code formatter ``black``. You can run it using - the nox session ``blacken``. This will eliminate many lint errors. Run via:: - - $ nox -s blacken - -- PEP8 compliance is required, with exceptions defined in the linter configuration. - If you have ``nox`` installed, you can test that you have not introduced - any non-compliant code via:: - - $ nox -s lint - -- In order to make ``nox -s lint`` run faster, you can set some environment - variables:: - - export GOOGLE_CLOUD_TESTING_REMOTE="upstream" - export GOOGLE_CLOUD_TESTING_BRANCH="main" - - By doing this, you are specifying the location of the most up-to-date - version of ``python-language``. The - remote name ``upstream`` should point to the official ``googleapis`` - checkout and the branch should be the default branch on that remote (``main``). - -- This repository contains configuration for the - `pre-commit <https://pre-commit.com/>`__ tool, which automates checking - our linters during a commit. If you have it installed on your ``$PATH``, - you can enable enforcing those checks via: - -.. code-block:: bash - - $ pre-commit install - pre-commit installed at .git/hooks/pre-commit - -Exceptions to PEP8: - -- Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for - "Function-Under-Test"), which is PEP8-incompliant, but more readable. - Some also use a local variable, ``MUT`` (short for "Module-Under-Test"). - -******************** -Running System Tests -******************** - -- To run system tests, you can execute:: - - # Run all system tests - $ nox -s system - - # Run a single system test - $ nox -s system-3.8 -- -k <name of test> - - - .. note:: - - System tests are only configured to run under Python 3.8. - For expediency, we do not run them in older versions of Python 3. - - This alone will not run the tests. You'll need to change some local - auth settings and change some configuration in your project to - run all the tests. - -- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication <https://cloud.google.com/docs/authentication/best-practices-applications#local_development_and_testing_with_the>`__. Some tests require a service account. For those tests see `Authenticating as a service account <https://cloud.google.com/docs/authentication/production>`__. - -************* -Test Coverage -************* - -- The codebase *must* have 100% test statement coverage after each commit. - You can test coverage via ``nox -s cover``. - -****************************************************** -Documentation Coverage and Building HTML Documentation -****************************************************** - -If you fix a bug, and the bug requires an API or behavior modification, all -documentation in this package which references that API or behavior must be -changed to reflect the bug fix, ideally in the same commit that fixes the bug -or adds the feature. - -Build the docs via: - - $ nox -s docs - -************************* -Samples and code snippets -************************* - -Code samples and snippets live in the `samples/` catalogue. Feel free to -provide more examples, but make sure to write tests for those examples. -Each folder containing example code requires its own `noxfile.py` script -which automates testing. If you decide to create a new folder, you can -base it on the `samples/snippets` folder (providing `noxfile.py` and -the requirements files). - -The tests will run against a real Google Cloud Project, so you should -configure them just like the System Tests. - -- To run sample tests, you can execute:: - - # Run all tests in a folder - $ cd samples/snippets - $ nox -s py-3.8 - - # Run a single sample test - $ cd samples/snippets - $ nox -s py-3.8 -- -k <name of test> - -******************************************** -Note About ``README`` as it pertains to PyPI -******************************************** - -The `description on PyPI`_ for the project comes directly from the -``README``. Due to the reStructuredText (``rst``) parser used by -PyPI, relative links which will work on GitHub (e.g. ``CONTRIBUTING.rst`` -instead of -``https://github.com/googleapis/python-language/blob/main/CONTRIBUTING.rst``) -may cause problems creating links or rendering the description. - -.. _description on PyPI: https://pypi.org/project/google-cloud-language - - -************************* -Supported Python Versions -************************* - -We support: - -- `Python 3.7`_ -- `Python 3.8`_ -- `Python 3.9`_ -- `Python 3.10`_ -- `Python 3.11`_ - -.. _Python 3.7: https://docs.python.org/3.7/ -.. _Python 3.8: https://docs.python.org/3.8/ -.. _Python 3.9: https://docs.python.org/3.9/ -.. _Python 3.10: https://docs.python.org/3.10/ -.. _Python 3.11: https://docs.python.org/3.11/ - - -Supported versions can be found in our ``noxfile.py`` `config`_. - -.. _config: https://github.com/googleapis/python-language/blob/main/noxfile.py - - -We also explicitly decided to support Python 3 beginning with version 3.7. -Reasons for this include: - -- Encouraging use of newest versions of Python 3 -- Taking the lead of `prominent`_ open-source `projects`_ -- `Unicode literal support`_ which allows for a cleaner codebase that - works in both Python 2 and Python 3 - -.. _prominent: https://docs.djangoproject.com/en/1.9/faq/install/#what-python-version-can-i-use-with-django -.. _projects: http://flask.pocoo.org/docs/0.10/python3/ -.. _Unicode literal support: https://www.python.org/dev/peps/pep-0414/ - -********** -Versioning -********** - -This library follows `Semantic Versioning`_. - -.. _Semantic Versioning: http://semver.org/ - -Some packages are currently in major version zero (``0.y.z``), which means that -anything may change at any time and the public API should not be considered -stable. - -****************************** -Contributor License Agreements -****************************** - -Before we can accept your pull requests you'll need to sign a Contributor -License Agreement (CLA): - -- **If you are an individual writing original source code** and **you own the - intellectual property**, then you'll need to sign an - `individual CLA <https://developers.google.com/open-source/cla/individual>`__. -- **If you work for a company that wants to allow you to contribute your work**, - then you'll need to sign a - `corporate CLA <https://developers.google.com/open-source/cla/corporate>`__. - -You can sign these electronically (just scroll to the bottom). After that, -we'll be able to accept your pull requests. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index e783f4c6..00000000 --- a/MANIFEST.in +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -include README.rst LICENSE -recursive-include google *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ - -# Exclude scripts for samples readmegen -prune scripts/readme-gen diff --git a/README.rst b/README.rst index 85553b43..fffdb7ab 100644 --- a/README.rst +++ b/README.rst @@ -1,3 +1,8 @@ +:**NOTE**: **This github repository is archived. The repository contents and history have moved to** `google-cloud-python`_. + +.. _google-cloud-python: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-language + + Python Client for Natural Language API ====================================== diff --git a/UPGRADING.md b/UPGRADING.md deleted file mode 100644 index ea65e2bc..00000000 --- a/UPGRADING.md +++ /dev/null @@ -1,140 +0,0 @@ -# 2.0.0 Migration Guide - -The 2.0 release of the `google-cloud-language` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. - -If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-language/issues). - -## Supported Python Versions - -> **WARNING**: Breaking change -The 2.0.0 release requires Python 3.6+. - -## Method Calls - -> **WARNING**: Breaking change -Methods expect request objects. We provide a script that will convert most common use cases. -* Install the library and `libcst`. - -```py -python3 -m pip install google-cloud-language[libcst] -``` - -* The script `fixup_language_v1_keywords.py` is shipped with the library. It expects -an input directory (with the code to convert) and an empty destination directory. - -```sh -$ fixup_language_v1_keywords.py --input-directory .samples/ --output-directory samples/ -``` - -**Before:** -```py -from google.cloud import language_v1 -language = language_v1.LanguageClient() -return language.analyze_sentiment(document=document).document_sentiment -``` - - -**After:** -```py -from google.cloud import language_v1 -language = language_v1.LanguageServiceClient() -return language.analyze_sentiment(request={'document': document}).document_sentiment -``` - -### More Details - -In `google-cloud-language<2.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. - -**Before:** -```py - def analyze_sentiment( - self, - document, - encoding_type=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): -``` - -In the 2.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. - -Some methods have additional keyword only parameters. The available parameters depend on the `google.api.method_signature` annotation specified by the API producer. - - -**After:** -```py - def analyze_sentiment( - self, - request: language_service.AnalyzeSentimentRequest = None, - *, - document: language_service.Document = None, - encoding_type: language_service.EncodingType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSentimentResponse: -``` - -> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. -> Passing both will result in an error. -Both of these calls are valid: - -```py -response = client.analyze_sentiment( - request={ - "document": document, - "encoding_type": encoding_type - } -) -``` - -```py -response = client.analyze_sentiment( - document=document, - encoding_type=encoding_type - ) # Make an API request. -``` - -This call is invalid because it mixes `request` with a keyword argument `entry_group`. Executing this code -will result in an error. - -```py -response = client.analyze_sentiment( - request={ - "document": document - }, - encoding_type=encoding_type -) -``` - - - -## Enums and Types - - -> **WARNING**: Breaking change -The submodules `enums` and `types` have been removed. -**Before:** -```py -from google.cloud import language_v1 -document = language_v1.types.Document(content=text, type=language_v1.enums.Document.Type.PLAIN_TEXT) -encoding_type = language_v1.enums.EncodingType.UTF8 -``` - - -**After:** -```py -from google.cloud import language_v1 -document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT) -encoding_type = language_v1.EncodingType.UTF8 -``` - -## Project Path Helper Methods - -The project path helper method `project_path` has been removed. Please construct -this path manually. - -```py -project = 'my-project' -project_path = f'projects/{project}' diff --git a/docs/README.rst b/docs/README.rst deleted file mode 120000 index 89a01069..00000000 --- a/docs/README.rst +++ /dev/null @@ -1 +0,0 @@ -../README.rst \ No newline at end of file diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md deleted file mode 120000 index 01097c8c..00000000 --- a/docs/UPGRADING.md +++ /dev/null @@ -1 +0,0 @@ -../UPGRADING.md \ No newline at end of file diff --git a/docs/_static/custom.css b/docs/_static/custom.css deleted file mode 100644 index b0a29546..00000000 --- a/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html deleted file mode 100644 index 6316a537..00000000 --- a/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} - <div class="document"> - {{ sidebar() }} - {%- block document %} - <div class="documentwrapper"> - {%- if render_sidebar %} - <div class="bodywrapper"> - {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - <div class="related top"> -   - {{- rellink_markup () }} - </div> - {%- endif %} - {% endblock %} - - <div class="body" role="main"> - <div class="admonition" id="python2-eol"> - As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit <a href="https://cloud.google.com/python/docs/python2-sunset/">Python 2 support on Google Cloud</a>. - </div> - {% block body %} {% endblock %} - </div> - - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - <div class="related bottom"> -   - {{- rellink_markup () }} - </div> - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} - </div> - {%- endif %} - </div> - {%- endblock %} - <div class="clearer"></div> - </div> -{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/docs/changelog.md b/docs/changelog.md deleted file mode 120000 index 04c99a55..00000000 --- a/docs/changelog.md +++ /dev/null @@ -1 +0,0 @@ -../CHANGELOG.md \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 0c13ee09..00000000 --- a/docs/conf.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# 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. -# -# google-cloud-language documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import os -import shlex -import sys - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.5.5" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = "google-cloud-language" -copyright = "2019, Google" -author = "Google APIs" - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [ - "_build", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for google-cloud-language", - "github_user": "googleapis", - "github_repo": "python-language", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# "<project> v<release> documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a <link> tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-language-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - #'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - #'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - #'preamble': '', - # Latex figure (float) alignment - #'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-language.tex", - "google-cloud-language Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-language", - "google-cloud-language Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-language", - "google-cloud-language Documentation", - author, - "google-cloud-language", - "google-cloud-language Library", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "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), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index 524632b7..00000000 --- a/docs/index.rst +++ /dev/null @@ -1,45 +0,0 @@ -.. include:: README.rst - -.. include:: multiprocessing.rst - -This package includes clients for multiple versions of Natural Language. -By default, you will get version ``language_v1``. - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - language_v1/services - language_v1/types - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - language_v1beta2/services - language_v1beta2/types - - -Migration Guide ---------------- - -See the guide below for instructions on migrating to the latest version. - -.. toctree:: - :maxdepth: 2 - -  UPGRADING - - -Changelog ---------- - -For a list of all ``google-cloud-language`` releases: - -.. toctree:: - :maxdepth: 2 - - changelog diff --git a/docs/language_v1/language_service.rst b/docs/language_v1/language_service.rst deleted file mode 100644 index 96e8755a..00000000 --- a/docs/language_v1/language_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -LanguageService ---------------------------------- - -.. automodule:: google.cloud.language_v1.services.language_service - :members: - :inherited-members: diff --git a/docs/language_v1/services.rst b/docs/language_v1/services.rst deleted file mode 100644 index 26f74fe9..00000000 --- a/docs/language_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Language v1 API -========================================= -.. toctree:: - :maxdepth: 2 - - language_service diff --git a/docs/language_v1/types.rst b/docs/language_v1/types.rst deleted file mode 100644 index 5dd3769e..00000000 --- a/docs/language_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Language v1 API -====================================== - -.. automodule:: google.cloud.language_v1.types - :members: - :show-inheritance: diff --git a/docs/language_v1beta2/language_service.rst b/docs/language_v1beta2/language_service.rst deleted file mode 100644 index 799a7892..00000000 --- a/docs/language_v1beta2/language_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -LanguageService ---------------------------------- - -.. automodule:: google.cloud.language_v1beta2.services.language_service - :members: - :inherited-members: diff --git a/docs/language_v1beta2/services.rst b/docs/language_v1beta2/services.rst deleted file mode 100644 index 40ead585..00000000 --- a/docs/language_v1beta2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Language v1beta2 API -============================================== -.. toctree:: - :maxdepth: 2 - - language_service diff --git a/docs/language_v1beta2/types.rst b/docs/language_v1beta2/types.rst deleted file mode 100644 index 2e834e61..00000000 --- a/docs/language_v1beta2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Language v1beta2 API -=========================================== - -.. automodule:: google.cloud.language_v1beta2.types - :members: - :show-inheritance: diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2..00000000 --- a/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - 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.Pool` or - :class:`multiprocessing.Process`. diff --git a/google/cloud/language/__init__.py b/google/cloud/language/__init__.py deleted file mode 100644 index a6faa72d..00000000 --- a/google/cloud/language/__init__.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.language import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.language_v1.services.language_service.async_client import ( - LanguageServiceAsyncClient, -) -from google.cloud.language_v1.services.language_service.client import ( - LanguageServiceClient, -) -from google.cloud.language_v1.types.language_service import ( - AnalyzeEntitiesRequest, - AnalyzeEntitiesResponse, - AnalyzeEntitySentimentRequest, - AnalyzeEntitySentimentResponse, - AnalyzeSentimentRequest, - AnalyzeSentimentResponse, - AnalyzeSyntaxRequest, - AnalyzeSyntaxResponse, - AnnotateTextRequest, - AnnotateTextResponse, - ClassificationCategory, - ClassificationModelOptions, - ClassifyTextRequest, - ClassifyTextResponse, - DependencyEdge, - Document, - EncodingType, - Entity, - EntityMention, - ModerateTextRequest, - ModerateTextResponse, - PartOfSpeech, - Sentence, - Sentiment, - TextSpan, - Token, -) - -__all__ = ( - "LanguageServiceClient", - "LanguageServiceAsyncClient", - "AnalyzeEntitiesRequest", - "AnalyzeEntitiesResponse", - "AnalyzeEntitySentimentRequest", - "AnalyzeEntitySentimentResponse", - "AnalyzeSentimentRequest", - "AnalyzeSentimentResponse", - "AnalyzeSyntaxRequest", - "AnalyzeSyntaxResponse", - "AnnotateTextRequest", - "AnnotateTextResponse", - "ClassificationCategory", - "ClassificationModelOptions", - "ClassifyTextRequest", - "ClassifyTextResponse", - "DependencyEdge", - "Document", - "Entity", - "EntityMention", - "ModerateTextRequest", - "ModerateTextResponse", - "PartOfSpeech", - "Sentence", - "Sentiment", - "TextSpan", - "Token", - "EncodingType", -) diff --git a/google/cloud/language/gapic_version.py b/google/cloud/language/gapic_version.py deleted file mode 100644 index 3dded207..00000000 --- a/google/cloud/language/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "2.10.1" # {x-release-please-version} diff --git a/google/cloud/language/py.typed b/google/cloud/language/py.typed deleted file mode 100644 index c0acc99a..00000000 --- a/google/cloud/language/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-language package uses inline types. diff --git a/google/cloud/language_v1/__init__.py b/google/cloud/language_v1/__init__.py deleted file mode 100644 index 166ac220..00000000 --- a/google/cloud/language_v1/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.language_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.language_service import LanguageServiceAsyncClient, LanguageServiceClient -from .types.language_service import ( - AnalyzeEntitiesRequest, - AnalyzeEntitiesResponse, - AnalyzeEntitySentimentRequest, - AnalyzeEntitySentimentResponse, - AnalyzeSentimentRequest, - AnalyzeSentimentResponse, - AnalyzeSyntaxRequest, - AnalyzeSyntaxResponse, - AnnotateTextRequest, - AnnotateTextResponse, - ClassificationCategory, - ClassificationModelOptions, - ClassifyTextRequest, - ClassifyTextResponse, - DependencyEdge, - Document, - EncodingType, - Entity, - EntityMention, - ModerateTextRequest, - ModerateTextResponse, - PartOfSpeech, - Sentence, - Sentiment, - TextSpan, - Token, -) - -__all__ = ( - "LanguageServiceAsyncClient", - "AnalyzeEntitiesRequest", - "AnalyzeEntitiesResponse", - "AnalyzeEntitySentimentRequest", - "AnalyzeEntitySentimentResponse", - "AnalyzeSentimentRequest", - "AnalyzeSentimentResponse", - "AnalyzeSyntaxRequest", - "AnalyzeSyntaxResponse", - "AnnotateTextRequest", - "AnnotateTextResponse", - "ClassificationCategory", - "ClassificationModelOptions", - "ClassifyTextRequest", - "ClassifyTextResponse", - "DependencyEdge", - "Document", - "EncodingType", - "Entity", - "EntityMention", - "LanguageServiceClient", - "ModerateTextRequest", - "ModerateTextResponse", - "PartOfSpeech", - "Sentence", - "Sentiment", - "TextSpan", - "Token", -) diff --git a/google/cloud/language_v1/gapic_metadata.json b/google/cloud/language_v1/gapic_metadata.json deleted file mode 100644 index fa2c065a..00000000 --- a/google/cloud/language_v1/gapic_metadata.json +++ /dev/null @@ -1,133 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.language_v1", - "protoPackage": "google.cloud.language.v1", - "schema": "1.0", - "services": { - "LanguageService": { - "clients": { - "grpc": { - "libraryClient": "LanguageServiceClient", - "rpcs": { - "AnalyzeEntities": { - "methods": [ - "analyze_entities" - ] - }, - "AnalyzeEntitySentiment": { - "methods": [ - "analyze_entity_sentiment" - ] - }, - "AnalyzeSentiment": { - "methods": [ - "analyze_sentiment" - ] - }, - "AnalyzeSyntax": { - "methods": [ - "analyze_syntax" - ] - }, - "AnnotateText": { - "methods": [ - "annotate_text" - ] - }, - "ClassifyText": { - "methods": [ - "classify_text" - ] - }, - "ModerateText": { - "methods": [ - "moderate_text" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LanguageServiceAsyncClient", - "rpcs": { - "AnalyzeEntities": { - "methods": [ - "analyze_entities" - ] - }, - "AnalyzeEntitySentiment": { - "methods": [ - "analyze_entity_sentiment" - ] - }, - "AnalyzeSentiment": { - "methods": [ - "analyze_sentiment" - ] - }, - "AnalyzeSyntax": { - "methods": [ - "analyze_syntax" - ] - }, - "AnnotateText": { - "methods": [ - "annotate_text" - ] - }, - "ClassifyText": { - "methods": [ - "classify_text" - ] - }, - "ModerateText": { - "methods": [ - "moderate_text" - ] - } - } - }, - "rest": { - "libraryClient": "LanguageServiceClient", - "rpcs": { - "AnalyzeEntities": { - "methods": [ - "analyze_entities" - ] - }, - "AnalyzeEntitySentiment": { - "methods": [ - "analyze_entity_sentiment" - ] - }, - "AnalyzeSentiment": { - "methods": [ - "analyze_sentiment" - ] - }, - "AnalyzeSyntax": { - "methods": [ - "analyze_syntax" - ] - }, - "AnnotateText": { - "methods": [ - "annotate_text" - ] - }, - "ClassifyText": { - "methods": [ - "classify_text" - ] - }, - "ModerateText": { - "methods": [ - "moderate_text" - ] - } - } - } - } - } - } -} diff --git a/google/cloud/language_v1/gapic_version.py b/google/cloud/language_v1/gapic_version.py deleted file mode 100644 index 3dded207..00000000 --- a/google/cloud/language_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "2.10.1" # {x-release-please-version} diff --git a/google/cloud/language_v1/py.typed b/google/cloud/language_v1/py.typed deleted file mode 100644 index c0acc99a..00000000 --- a/google/cloud/language_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-language package uses inline types. diff --git a/google/cloud/language_v1/services/__init__.py b/google/cloud/language_v1/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/google/cloud/language_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/google/cloud/language_v1/services/language_service/__init__.py b/google/cloud/language_v1/services/language_service/__init__.py deleted file mode 100644 index 6a15301c..00000000 --- a/google/cloud/language_v1/services/language_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .async_client import LanguageServiceAsyncClient -from .client import LanguageServiceClient - -__all__ = ( - "LanguageServiceClient", - "LanguageServiceAsyncClient", -) diff --git a/google/cloud/language_v1/services/language_service/async_client.py b/google/cloud/language_v1/services/language_service/async_client.py deleted file mode 100644 index fd09c872..00000000 --- a/google/cloud/language_v1/services/language_service/async_client.py +++ /dev/null @@ -1,1034 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import ( - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) - -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.language_v1 import gapic_version as package_version - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.language_v1.types import language_service - -from .client import LanguageServiceClient -from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport -from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport - - -class LanguageServiceAsyncClient: - """Provides text analysis operations such as sentiment analysis - and entity recognition. - """ - - _client: LanguageServiceClient - - DEFAULT_ENDPOINT = LanguageServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LanguageServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod( - LanguageServiceClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - LanguageServiceClient.parse_common_billing_account_path - ) - common_folder_path = staticmethod(LanguageServiceClient.common_folder_path) - parse_common_folder_path = staticmethod( - LanguageServiceClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - LanguageServiceClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - LanguageServiceClient.parse_common_organization_path - ) - common_project_path = staticmethod(LanguageServiceClient.common_project_path) - parse_common_project_path = staticmethod( - LanguageServiceClient.parse_common_project_path - ) - common_location_path = staticmethod(LanguageServiceClient.common_location_path) - parse_common_location_path = staticmethod( - LanguageServiceClient.parse_common_location_path - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceAsyncClient: The constructed client. - """ - return LanguageServiceClient.from_service_account_info.__func__(LanguageServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceAsyncClient: The constructed client. - """ - return LanguageServiceClient.from_service_account_file.__func__(LanguageServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return LanguageServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LanguageServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LanguageServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial( - type(LanguageServiceClient).get_transport_class, type(LanguageServiceClient) - ) - - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, LanguageServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the language service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.LanguageServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = LanguageServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - ) - - async def analyze_sentiment( - self, - request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSentimentResponse: - r"""Analyzes the sentiment of the provided text. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - async def sample_analyze_sentiment(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]]): - The request object. The sentiment analysis request - message. - document (:class:`google.cloud.language_v1.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1.types.EncodingType`): - The encoding type used by the API to - calculate sentence offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeSentimentResponse: - The sentiment analysis response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeSentimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_entities( - self, - request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitiesResponse: - r"""Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - async def sample_analyze_entities(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entities(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]]): - The request object. The entity analysis request message. - document (:class:`google.cloud.language_v1.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeEntitiesResponse: - The entity analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeEntitiesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_entities, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_entity_sentiment( - self, - request: Optional[ - Union[language_service.AnalyzeEntitySentimentRequest, dict] - ] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitySentimentResponse: - r"""Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - async def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]]): - The request object. The entity-level sentiment analysis - request message. - document (:class:`google.cloud.language_v1.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeEntitySentimentResponse: - The entity-level sentiment analysis - response message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeEntitySentimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_entity_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_syntax( - self, - request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSyntaxResponse: - r"""Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - async def sample_analyze_syntax(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = await client.analyze_syntax(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]]): - The request object. The syntax analysis request message. - document (:class:`google.cloud.language_v1.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeSyntaxResponse: - The syntax analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeSyntaxRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_syntax, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def classify_text( - self, - request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ClassifyTextResponse: - r"""Classifies a document into categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - async def sample_classify_text(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = await client.classify_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]]): - The request object. The document classification request - message. - document (:class:`google.cloud.language_v1.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.ClassifyTextResponse: - The document classification response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.ClassifyTextRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.classify_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def moderate_text( - self, - request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ModerateTextResponse: - r"""Moderates a document for harmful and sensitive - categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - async def sample_moderate_text(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ModerateTextRequest( - document=document, - ) - - # Make the request - response = await client.moderate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1.types.ModerateTextRequest, dict]]): - The request object. The document moderation request - message. - document (:class:`google.cloud.language_v1.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.ModerateTextResponse: - The document moderation response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.ModerateTextRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.moderate_text, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def annotate_text( - self, - request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - features: Optional[language_service.AnnotateTextRequest.Features] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnnotateTextResponse: - r"""A convenience method that provides all the features - that analyzeSentiment, analyzeEntities, and - analyzeSyntax provide in one call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - async def sample_annotate_text(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = await client.annotate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]]): - The request object. The request message for the text - annotation API, which can perform - multiple analysis types (sentiment, - entities, and syntax) in one call. - document (:class:`google.cloud.language_v1.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (:class:`google.cloud.language_v1.types.AnnotateTextRequest.Features`): - Required. The enabled features. - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnnotateTextResponse: - The text annotations response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, features, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnnotateTextRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if features is not None: - request.features = features - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.annotate_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "LanguageServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -__all__ = ("LanguageServiceAsyncClient",) diff --git a/google/cloud/language_v1/services/language_service/client.py b/google/cloud/language_v1/services/language_service/client.py deleted file mode 100644 index e9b4ccec..00000000 --- a/google/cloud/language_v1/services/language_service/client.py +++ /dev/null @@ -1,1190 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import ( - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.language_v1 import gapic_version as package_version - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.language_v1.types import language_service - -from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport -from .transports.grpc import LanguageServiceGrpcTransport -from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport -from .transports.rest import LanguageServiceRestTransport - - -class LanguageServiceClientMeta(type): - """Metaclass for the LanguageService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - - _transport_registry = ( - OrderedDict() - ) # type: Dict[str, Type[LanguageServiceTransport]] - _transport_registry["grpc"] = LanguageServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LanguageServiceRestTransport - - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[LanguageServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class LanguageServiceClient(metaclass=LanguageServiceClientMeta): - """Provides text analysis operations such as sentiment analysis - and entity recognition. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_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: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "language.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> LanguageServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LanguageServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path( - folder: str, - ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P<folder>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path( - organization: str, - ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P<organization>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path( - project: str, - ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P<project>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LanguageServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the language service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, LanguageServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( - client_options - ) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, LanguageServiceTransport): - # transport is a LanguageServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def analyze_sentiment( - self, - request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSentimentResponse: - r"""Analyzes the sentiment of the provided text. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - def sample_analyze_sentiment(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1.types.AnalyzeSentimentRequest, dict]): - The request object. The sentiment analysis request - message. - document (google.cloud.language_v1.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate sentence offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeSentimentResponse: - The sentiment analysis response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeSentimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeSentimentRequest): - request = language_service.AnalyzeSentimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_sentiment] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_entities( - self, - request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitiesResponse: - r"""Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - def sample_analyze_entities(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = client.analyze_entities(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1.types.AnalyzeEntitiesRequest, dict]): - The request object. The entity analysis request message. - document (google.cloud.language_v1.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeEntitiesResponse: - The entity analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeEntitiesRequest): - request = language_service.AnalyzeEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_entities] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_entity_sentiment( - self, - request: Optional[ - Union[language_service.AnalyzeEntitySentimentRequest, dict] - ] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitySentimentResponse: - r"""Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1.types.AnalyzeEntitySentimentRequest, dict]): - The request object. The entity-level sentiment analysis - request message. - document (google.cloud.language_v1.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeEntitySentimentResponse: - The entity-level sentiment analysis - response message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeEntitySentimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeEntitySentimentRequest): - request = language_service.AnalyzeEntitySentimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_entity_sentiment] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_syntax( - self, - request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSyntaxResponse: - r"""Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - def sample_analyze_syntax(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = client.analyze_syntax(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1.types.AnalyzeSyntaxRequest, dict]): - The request object. The syntax analysis request message. - document (google.cloud.language_v1.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnalyzeSyntaxResponse: - The syntax analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeSyntaxRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeSyntaxRequest): - request = language_service.AnalyzeSyntaxRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_syntax] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def classify_text( - self, - request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ClassifyTextResponse: - r"""Classifies a document into categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - def sample_classify_text(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = client.classify_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1.types.ClassifyTextRequest, dict]): - The request object. The document classification request - message. - document (google.cloud.language_v1.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.ClassifyTextResponse: - The document classification response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.ClassifyTextRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.ClassifyTextRequest): - request = language_service.ClassifyTextRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.classify_text] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def moderate_text( - self, - request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ModerateTextResponse: - r"""Moderates a document for harmful and sensitive - categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - def sample_moderate_text(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ModerateTextRequest( - document=document, - ) - - # Make the request - response = client.moderate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1.types.ModerateTextRequest, dict]): - The request object. The document moderation request - message. - document (google.cloud.language_v1.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.ModerateTextResponse: - The document moderation response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.ModerateTextRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.ModerateTextRequest): - request = language_service.ModerateTextRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.moderate_text] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def annotate_text( - self, - request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - features: Optional[language_service.AnnotateTextRequest.Features] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnnotateTextResponse: - r"""A convenience method that provides all the features - that analyzeSentiment, analyzeEntities, and - analyzeSyntax provide in one call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1 - - def sample_annotate_text(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = client.annotate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1.types.AnnotateTextRequest, dict]): - The request object. The request message for the text - annotation API, which can perform - multiple analysis types (sentiment, - entities, and syntax) in one call. - document (google.cloud.language_v1.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (google.cloud.language_v1.types.AnnotateTextRequest.Features): - Required. The enabled features. - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1.types.AnnotateTextResponse: - The text annotations response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, features, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnnotateTextRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnnotateTextRequest): - request = language_service.AnnotateTextRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if features is not None: - request.features = features - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.annotate_text] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "LanguageServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -__all__ = ("LanguageServiceClient",) diff --git a/google/cloud/language_v1/services/language_service/transports/__init__.py b/google/cloud/language_v1/services/language_service/transports/__init__.py deleted file mode 100644 index 12a453a7..00000000 --- a/google/cloud/language_v1/services/language_service/transports/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import LanguageServiceTransport -from .grpc import LanguageServiceGrpcTransport -from .grpc_asyncio import LanguageServiceGrpcAsyncIOTransport -from .rest import LanguageServiceRestInterceptor, LanguageServiceRestTransport - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LanguageServiceTransport]] -_transport_registry["grpc"] = LanguageServiceGrpcTransport -_transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport -_transport_registry["rest"] = LanguageServiceRestTransport - -__all__ = ( - "LanguageServiceTransport", - "LanguageServiceGrpcTransport", - "LanguageServiceGrpcAsyncIOTransport", - "LanguageServiceRestTransport", - "LanguageServiceRestInterceptor", -) diff --git a/google/cloud/language_v1/services/language_service/transports/base.py b/google/cloud/language_v1/services/language_service/transports/base.py deleted file mode 100644 index c900f0af..00000000 --- a/google/cloud/language_v1/services/language_service/transports/base.py +++ /dev/null @@ -1,323 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.language_v1 import gapic_version as package_version -from google.cloud.language_v1.types import language_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -class LanguageServiceTransport(abc.ABC): - """Abstract transport class for LanguageService.""" - - AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ) - - DEFAULT_HOST: str = "language.googleapis.com" - - def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[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, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - 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): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.analyze_sentiment: gapic_v1.method.wrap_method( - self.analyze_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.analyze_entities: gapic_v1.method.wrap_method( - self.analyze_entities, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.analyze_entity_sentiment: gapic_v1.method.wrap_method( - self.analyze_entity_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.analyze_syntax: gapic_v1.method.wrap_method( - self.analyze_syntax, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.classify_text: gapic_v1.method.wrap_method( - self.classify_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.moderate_text: gapic_v1.method.wrap_method( - self.moderate_text, - default_timeout=None, - client_info=client_info, - ), - self.annotate_text: gapic_v1.method.wrap_method( - self.annotate_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - Union[ - language_service.AnalyzeSentimentResponse, - Awaitable[language_service.AnalyzeSentimentResponse], - ], - ]: - raise NotImplementedError() - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - Union[ - language_service.AnalyzeEntitiesResponse, - Awaitable[language_service.AnalyzeEntitiesResponse], - ], - ]: - raise NotImplementedError() - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - Union[ - language_service.AnalyzeEntitySentimentResponse, - Awaitable[language_service.AnalyzeEntitySentimentResponse], - ], - ]: - raise NotImplementedError() - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], - Union[ - language_service.AnalyzeSyntaxResponse, - Awaitable[language_service.AnalyzeSyntaxResponse], - ], - ]: - raise NotImplementedError() - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], - Union[ - language_service.ClassifyTextResponse, - Awaitable[language_service.ClassifyTextResponse], - ], - ]: - raise NotImplementedError() - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], - Union[ - language_service.ModerateTextResponse, - Awaitable[language_service.ModerateTextResponse], - ], - ]: - raise NotImplementedError() - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], - Union[ - language_service.AnnotateTextResponse, - Awaitable[language_service.AnnotateTextResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ("LanguageServiceTransport",) diff --git a/google/cloud/language_v1/services/language_service/transports/grpc.py b/google/cloud/language_v1/services/language_service/transports/grpc.py deleted file mode 100644 index dd9abdb0..00000000 --- a/google/cloud/language_v1/services/language_service/transports/grpc.py +++ /dev/null @@ -1,450 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Callable, Dict, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import gapic_v1, grpc_helpers -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.language_v1.types import language_service - -from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport - - -class LanguageServiceGrpcTransport(LanguageServiceTransport): - """gRPC backend transport for LanguageService. - - Provides text analysis operations such as sentiment analysis - and entity recognition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _stubs: Dict[str, Callable] - - def __init__( - self, - *, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # 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 - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel( - cls, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs, - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" - return self._grpc_channel - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - language_service.AnalyzeSentimentResponse, - ]: - r"""Return a callable for the analyze sentiment method over gRPC. - - Analyzes the sentiment of the provided text. - - Returns: - Callable[[~.AnalyzeSentimentRequest], - ~.AnalyzeSentimentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_sentiment" not in self._stubs: - self._stubs["analyze_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeSentiment", - request_serializer=language_service.AnalyzeSentimentRequest.serialize, - response_deserializer=language_service.AnalyzeSentimentResponse.deserialize, - ) - return self._stubs["analyze_sentiment"] - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - language_service.AnalyzeEntitiesResponse, - ]: - r"""Return a callable for the analyze entities method over gRPC. - - Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - Returns: - Callable[[~.AnalyzeEntitiesRequest], - ~.AnalyzeEntitiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entities" not in self._stubs: - self._stubs["analyze_entities"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeEntities", - request_serializer=language_service.AnalyzeEntitiesRequest.serialize, - response_deserializer=language_service.AnalyzeEntitiesResponse.deserialize, - ) - return self._stubs["analyze_entities"] - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - language_service.AnalyzeEntitySentimentResponse, - ]: - r"""Return a callable for the analyze entity sentiment method over gRPC. - - Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - Returns: - Callable[[~.AnalyzeEntitySentimentRequest], - ~.AnalyzeEntitySentimentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entity_sentiment" not in self._stubs: - self._stubs["analyze_entity_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeEntitySentiment", - request_serializer=language_service.AnalyzeEntitySentimentRequest.serialize, - response_deserializer=language_service.AnalyzeEntitySentimentResponse.deserialize, - ) - return self._stubs["analyze_entity_sentiment"] - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], language_service.AnalyzeSyntaxResponse - ]: - r"""Return a callable for the analyze syntax method over gRPC. - - Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - Returns: - Callable[[~.AnalyzeSyntaxRequest], - ~.AnalyzeSyntaxResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_syntax" not in self._stubs: - self._stubs["analyze_syntax"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeSyntax", - request_serializer=language_service.AnalyzeSyntaxRequest.serialize, - response_deserializer=language_service.AnalyzeSyntaxResponse.deserialize, - ) - return self._stubs["analyze_syntax"] - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], language_service.ClassifyTextResponse - ]: - r"""Return a callable for the classify text method over gRPC. - - Classifies a document into categories. - - Returns: - Callable[[~.ClassifyTextRequest], - ~.ClassifyTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "classify_text" not in self._stubs: - self._stubs["classify_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/ClassifyText", - request_serializer=language_service.ClassifyTextRequest.serialize, - response_deserializer=language_service.ClassifyTextResponse.deserialize, - ) - return self._stubs["classify_text"] - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], language_service.ModerateTextResponse - ]: - r"""Return a callable for the moderate text method over gRPC. - - Moderates a document for harmful and sensitive - categories. - - Returns: - Callable[[~.ModerateTextRequest], - ~.ModerateTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "moderate_text" not in self._stubs: - self._stubs["moderate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/ModerateText", - request_serializer=language_service.ModerateTextRequest.serialize, - response_deserializer=language_service.ModerateTextResponse.deserialize, - ) - return self._stubs["moderate_text"] - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], language_service.AnnotateTextResponse - ]: - r"""Return a callable for the annotate text method over gRPC. - - A convenience method that provides all the features - that analyzeSentiment, analyzeEntities, and - analyzeSyntax provide in one call. - - Returns: - Callable[[~.AnnotateTextRequest], - ~.AnnotateTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "annotate_text" not in self._stubs: - self._stubs["annotate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnnotateText", - request_serializer=language_service.AnnotateTextRequest.serialize, - response_deserializer=language_service.AnnotateTextResponse.deserialize, - ) - return self._stubs["annotate_text"] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ("LanguageServiceGrpcTransport",) diff --git a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py deleted file mode 100644 index 00e1ea21..00000000 --- a/google/cloud/language_v1/services/language_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import gapic_v1, grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.language_v1.types import language_service - -from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport -from .grpc import LanguageServiceGrpcTransport - - -class LanguageServiceGrpcAsyncIOTransport(LanguageServiceTransport): - """gRPC AsyncIO backend transport for LanguageService. - - Provides text analysis operations such as sentiment analysis - and entity recognition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel( - cls, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # 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 - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - Awaitable[language_service.AnalyzeSentimentResponse], - ]: - r"""Return a callable for the analyze sentiment method over gRPC. - - Analyzes the sentiment of the provided text. - - Returns: - Callable[[~.AnalyzeSentimentRequest], - Awaitable[~.AnalyzeSentimentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_sentiment" not in self._stubs: - self._stubs["analyze_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeSentiment", - request_serializer=language_service.AnalyzeSentimentRequest.serialize, - response_deserializer=language_service.AnalyzeSentimentResponse.deserialize, - ) - return self._stubs["analyze_sentiment"] - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - Awaitable[language_service.AnalyzeEntitiesResponse], - ]: - r"""Return a callable for the analyze entities method over gRPC. - - Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - Returns: - Callable[[~.AnalyzeEntitiesRequest], - Awaitable[~.AnalyzeEntitiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entities" not in self._stubs: - self._stubs["analyze_entities"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeEntities", - request_serializer=language_service.AnalyzeEntitiesRequest.serialize, - response_deserializer=language_service.AnalyzeEntitiesResponse.deserialize, - ) - return self._stubs["analyze_entities"] - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - Awaitable[language_service.AnalyzeEntitySentimentResponse], - ]: - r"""Return a callable for the analyze entity sentiment method over gRPC. - - Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - Returns: - Callable[[~.AnalyzeEntitySentimentRequest], - Awaitable[~.AnalyzeEntitySentimentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entity_sentiment" not in self._stubs: - self._stubs["analyze_entity_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeEntitySentiment", - request_serializer=language_service.AnalyzeEntitySentimentRequest.serialize, - response_deserializer=language_service.AnalyzeEntitySentimentResponse.deserialize, - ) - return self._stubs["analyze_entity_sentiment"] - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], - Awaitable[language_service.AnalyzeSyntaxResponse], - ]: - r"""Return a callable for the analyze syntax method over gRPC. - - Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - Returns: - Callable[[~.AnalyzeSyntaxRequest], - Awaitable[~.AnalyzeSyntaxResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_syntax" not in self._stubs: - self._stubs["analyze_syntax"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnalyzeSyntax", - request_serializer=language_service.AnalyzeSyntaxRequest.serialize, - response_deserializer=language_service.AnalyzeSyntaxResponse.deserialize, - ) - return self._stubs["analyze_syntax"] - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], - Awaitable[language_service.ClassifyTextResponse], - ]: - r"""Return a callable for the classify text method over gRPC. - - Classifies a document into categories. - - Returns: - Callable[[~.ClassifyTextRequest], - Awaitable[~.ClassifyTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "classify_text" not in self._stubs: - self._stubs["classify_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/ClassifyText", - request_serializer=language_service.ClassifyTextRequest.serialize, - response_deserializer=language_service.ClassifyTextResponse.deserialize, - ) - return self._stubs["classify_text"] - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], - Awaitable[language_service.ModerateTextResponse], - ]: - r"""Return a callable for the moderate text method over gRPC. - - Moderates a document for harmful and sensitive - categories. - - Returns: - Callable[[~.ModerateTextRequest], - Awaitable[~.ModerateTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "moderate_text" not in self._stubs: - self._stubs["moderate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/ModerateText", - request_serializer=language_service.ModerateTextRequest.serialize, - response_deserializer=language_service.ModerateTextResponse.deserialize, - ) - return self._stubs["moderate_text"] - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], - Awaitable[language_service.AnnotateTextResponse], - ]: - r"""Return a callable for the annotate text method over gRPC. - - A convenience method that provides all the features - that analyzeSentiment, analyzeEntities, and - analyzeSyntax provide in one call. - - Returns: - Callable[[~.AnnotateTextRequest], - Awaitable[~.AnnotateTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "annotate_text" not in self._stubs: - self._stubs["annotate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1.LanguageService/AnnotateText", - request_serializer=language_service.AnnotateTextRequest.serialize, - response_deserializer=language_service.AnnotateTextResponse.deserialize, - ) - return self._stubs["annotate_text"] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ("LanguageServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/language_v1/services/language_service/transports/rest.py b/google/cloud/language_v1/services/language_service/transports/rest.py deleted file mode 100644 index 990da259..00000000 --- a/google/cloud/language_v1/services/language_service/transports/rest.py +++ /dev/null @@ -1,1158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import dataclasses -import json # type: ignore -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.protobuf import json_format -import grpc # type: ignore -from requests import __version__ as requests_version - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.language_v1.types import language_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import LanguageServiceTransport - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class LanguageServiceRestInterceptor: - """Interceptor for LanguageService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the LanguageServiceRestTransport. - - .. code-block:: python - class MyCustomLanguageServiceInterceptor(LanguageServiceRestInterceptor): - def pre_analyze_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_entity_sentiment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_entity_sentiment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_sentiment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_sentiment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_syntax(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_syntax(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_annotate_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_annotate_text(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_classify_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_classify_text(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_moderate_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_moderate_text(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LanguageServiceRestTransport(interceptor=MyCustomLanguageServiceInterceptor()) - client = LanguageServiceClient(transport=transport) - - - """ - - def pre_analyze_entities( - self, - request: language_service.AnalyzeEntitiesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnalyzeEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_entities( - self, response: language_service.AnalyzeEntitiesResponse - ) -> language_service.AnalyzeEntitiesResponse: - """Post-rpc interceptor for analyze_entities - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_analyze_entity_sentiment( - self, - request: language_service.AnalyzeEntitySentimentRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[ - language_service.AnalyzeEntitySentimentRequest, Sequence[Tuple[str, str]] - ]: - """Pre-rpc interceptor for analyze_entity_sentiment - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_entity_sentiment( - self, response: language_service.AnalyzeEntitySentimentResponse - ) -> language_service.AnalyzeEntitySentimentResponse: - """Post-rpc interceptor for analyze_entity_sentiment - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_analyze_sentiment( - self, - request: language_service.AnalyzeSentimentRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnalyzeSentimentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_sentiment - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_sentiment( - self, response: language_service.AnalyzeSentimentResponse - ) -> language_service.AnalyzeSentimentResponse: - """Post-rpc interceptor for analyze_sentiment - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_analyze_syntax( - self, - request: language_service.AnalyzeSyntaxRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnalyzeSyntaxRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_syntax - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_syntax( - self, response: language_service.AnalyzeSyntaxResponse - ) -> language_service.AnalyzeSyntaxResponse: - """Post-rpc interceptor for analyze_syntax - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_annotate_text( - self, - request: language_service.AnnotateTextRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnnotateTextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for annotate_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_annotate_text( - self, response: language_service.AnnotateTextResponse - ) -> language_service.AnnotateTextResponse: - """Post-rpc interceptor for annotate_text - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_classify_text( - self, - request: language_service.ClassifyTextRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.ClassifyTextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for classify_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_classify_text( - self, response: language_service.ClassifyTextResponse - ) -> language_service.ClassifyTextResponse: - """Post-rpc interceptor for classify_text - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_moderate_text( - self, - request: language_service.ModerateTextRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.ModerateTextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for moderate_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_moderate_text( - self, response: language_service.ModerateTextResponse - ) -> language_service.ModerateTextResponse: - """Post-rpc interceptor for moderate_text - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class LanguageServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LanguageServiceRestInterceptor - - -class LanguageServiceRestTransport(LanguageServiceTransport): - """REST backend transport for LanguageService. - - Provides text analysis operations such as sentiment analysis - and entity recognition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__( - self, - *, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[LanguageServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host) - if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or LanguageServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AnalyzeEntities(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeEntitiesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitiesResponse: - r"""Call the analyze entities method over HTTP. - - Args: - request (~.language_service.AnalyzeEntitiesRequest): - The request object. The entity analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeEntitiesResponse: - The entity analysis response message. - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/documents:analyzeEntities", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_entities( - request, metadata - ) - pb_request = language_service.AnalyzeEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeEntitiesResponse() - pb_resp = language_service.AnalyzeEntitiesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_entities(resp) - return resp - - class _AnalyzeEntitySentiment(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeEntitySentiment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeEntitySentimentRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitySentimentResponse: - r"""Call the analyze entity sentiment method over HTTP. - - Args: - request (~.language_service.AnalyzeEntitySentimentRequest): - The request object. The entity-level sentiment analysis - request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeEntitySentimentResponse: - The entity-level sentiment analysis - response message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/documents:analyzeEntitySentiment", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_entity_sentiment( - request, metadata - ) - pb_request = language_service.AnalyzeEntitySentimentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeEntitySentimentResponse() - pb_resp = language_service.AnalyzeEntitySentimentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_entity_sentiment(resp) - return resp - - class _AnalyzeSentiment(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeSentiment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeSentimentRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSentimentResponse: - r"""Call the analyze sentiment method over HTTP. - - Args: - request (~.language_service.AnalyzeSentimentRequest): - The request object. The sentiment analysis request - message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeSentimentResponse: - The sentiment analysis response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/documents:analyzeSentiment", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_sentiment( - request, metadata - ) - pb_request = language_service.AnalyzeSentimentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeSentimentResponse() - pb_resp = language_service.AnalyzeSentimentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_sentiment(resp) - return resp - - class _AnalyzeSyntax(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeSyntax") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeSyntaxRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSyntaxResponse: - r"""Call the analyze syntax method over HTTP. - - Args: - request (~.language_service.AnalyzeSyntaxRequest): - The request object. The syntax analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeSyntaxResponse: - The syntax analysis response message. - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/documents:analyzeSyntax", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_syntax(request, metadata) - pb_request = language_service.AnalyzeSyntaxRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeSyntaxResponse() - pb_resp = language_service.AnalyzeSyntaxResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_syntax(resp) - return resp - - class _AnnotateText(LanguageServiceRestStub): - def __hash__(self): - return hash("AnnotateText") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnnotateTextRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnnotateTextResponse: - r"""Call the annotate text method over HTTP. - - Args: - request (~.language_service.AnnotateTextRequest): - The request object. The request message for the text - annotation API, which can perform - multiple analysis types (sentiment, - entities, and syntax) in one call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnnotateTextResponse: - The text annotations response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/documents:annotateText", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_annotate_text(request, metadata) - pb_request = language_service.AnnotateTextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnnotateTextResponse() - pb_resp = language_service.AnnotateTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_annotate_text(resp) - return resp - - class _ClassifyText(LanguageServiceRestStub): - def __hash__(self): - return hash("ClassifyText") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.ClassifyTextRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ClassifyTextResponse: - r"""Call the classify text method over HTTP. - - Args: - request (~.language_service.ClassifyTextRequest): - The request object. The document classification request - message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.ClassifyTextResponse: - The document classification response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/documents:classifyText", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_classify_text(request, metadata) - pb_request = language_service.ClassifyTextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.ClassifyTextResponse() - pb_resp = language_service.ClassifyTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_classify_text(resp) - return resp - - class _ModerateText(LanguageServiceRestStub): - def __hash__(self): - return hash("ModerateText") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.ModerateTextRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ModerateTextResponse: - r"""Call the moderate text method over HTTP. - - Args: - request (~.language_service.ModerateTextRequest): - The request object. The document moderation request - message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.ModerateTextResponse: - The document moderation response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/documents:moderateText", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_moderate_text(request, metadata) - pb_request = language_service.ModerateTextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.ModerateTextResponse() - pb_resp = language_service.ModerateTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_moderate_text(resp) - return resp - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - language_service.AnalyzeEntitiesResponse, - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - language_service.AnalyzeEntitySentimentResponse, - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeEntitySentiment(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - language_service.AnalyzeSentimentResponse, - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeSentiment(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], language_service.AnalyzeSyntaxResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeSyntax(self._session, self._host, self._interceptor) # type: ignore - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], language_service.AnnotateTextResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnnotateText(self._session, self._host, self._interceptor) # type: ignore - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], language_service.ClassifyTextResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ClassifyText(self._session, self._host, self._interceptor) # type: ignore - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], language_service.ModerateTextResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ModerateText(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__ = ("LanguageServiceRestTransport",) diff --git a/google/cloud/language_v1/types/__init__.py b/google/cloud/language_v1/types/__init__.py deleted file mode 100644 index 4f98d4d3..00000000 --- a/google/cloud/language_v1/types/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .language_service import ( - AnalyzeEntitiesRequest, - AnalyzeEntitiesResponse, - AnalyzeEntitySentimentRequest, - AnalyzeEntitySentimentResponse, - AnalyzeSentimentRequest, - AnalyzeSentimentResponse, - AnalyzeSyntaxRequest, - AnalyzeSyntaxResponse, - AnnotateTextRequest, - AnnotateTextResponse, - ClassificationCategory, - ClassificationModelOptions, - ClassifyTextRequest, - ClassifyTextResponse, - DependencyEdge, - Document, - EncodingType, - Entity, - EntityMention, - ModerateTextRequest, - ModerateTextResponse, - PartOfSpeech, - Sentence, - Sentiment, - TextSpan, - Token, -) - -__all__ = ( - "AnalyzeEntitiesRequest", - "AnalyzeEntitiesResponse", - "AnalyzeEntitySentimentRequest", - "AnalyzeEntitySentimentResponse", - "AnalyzeSentimentRequest", - "AnalyzeSentimentResponse", - "AnalyzeSyntaxRequest", - "AnalyzeSyntaxResponse", - "AnnotateTextRequest", - "AnnotateTextResponse", - "ClassificationCategory", - "ClassificationModelOptions", - "ClassifyTextRequest", - "ClassifyTextResponse", - "DependencyEdge", - "Document", - "Entity", - "EntityMention", - "ModerateTextRequest", - "ModerateTextResponse", - "PartOfSpeech", - "Sentence", - "Sentiment", - "TextSpan", - "Token", - "EncodingType", -) diff --git a/google/cloud/language_v1/types/language_service.py b/google/cloud/language_v1/types/language_service.py deleted file mode 100644 index da423978..00000000 --- a/google/cloud/language_v1/types/language_service.py +++ /dev/null @@ -1,1732 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -__protobuf__ = proto.module( - package="google.cloud.language.v1", - manifest={ - "EncodingType", - "Document", - "Sentence", - "Entity", - "Token", - "Sentiment", - "PartOfSpeech", - "DependencyEdge", - "EntityMention", - "TextSpan", - "ClassificationCategory", - "ClassificationModelOptions", - "AnalyzeSentimentRequest", - "AnalyzeSentimentResponse", - "AnalyzeEntitySentimentRequest", - "AnalyzeEntitySentimentResponse", - "AnalyzeEntitiesRequest", - "AnalyzeEntitiesResponse", - "AnalyzeSyntaxRequest", - "AnalyzeSyntaxResponse", - "ClassifyTextRequest", - "ClassifyTextResponse", - "ModerateTextRequest", - "ModerateTextResponse", - "AnnotateTextRequest", - "AnnotateTextResponse", - }, -) - - -class EncodingType(proto.Enum): - r"""Represents the text encoding that the caller uses to process the - output. Providing an ``EncodingType`` is recommended because the API - provides the beginning offsets for various outputs, such as tokens - and mentions, and languages that natively use different text - encodings may access offsets differently. - - Values: - NONE (0): - If ``EncodingType`` is not specified, encoding-dependent - information (such as ``begin_offset``) will be set at - ``-1``. - UTF8 (1): - Encoding-dependent information (such as ``begin_offset``) is - calculated based on the UTF-8 encoding of the input. C++ and - Go are examples of languages that use this encoding - natively. - UTF16 (2): - Encoding-dependent information (such as ``begin_offset``) is - calculated based on the UTF-16 encoding of the input. Java - and JavaScript are examples of languages that use this - encoding natively. - UTF32 (3): - Encoding-dependent information (such as ``begin_offset``) is - calculated based on the UTF-32 encoding of the input. Python - is an example of a language that uses this encoding - natively. - """ - NONE = 0 - UTF8 = 1 - UTF16 = 2 - UTF32 = 3 - - -class Document(proto.Message): - r"""Represents the input to API methods. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (google.cloud.language_v1.types.Document.Type): - Required. If the type is not set or is ``TYPE_UNSPECIFIED``, - returns an ``INVALID_ARGUMENT`` error. - content (str): - The content of the input in string format. - Cloud audit logging exempt since it is based on - user data. - - This field is a member of `oneof`_ ``source``. - gcs_content_uri (str): - The Google Cloud Storage URI where the file content is - located. This URI must be of the form: - gs://bucket_name/object_name. For more details, see - https://cloud.google.com/storage/docs/reference-uris. NOTE: - Cloud Storage object versioning is not supported. - - This field is a member of `oneof`_ ``source``. - language (str): - The language of the document (if not specified, the language - is automatically detected). Both ISO and BCP-47 language - codes are accepted. `Language - Support <https://cloud.google.com/natural-language/docs/languages>`__ - lists currently supported languages for each API method. If - the language (either specified by the caller or - automatically detected) is not supported by the called API - method, an ``INVALID_ARGUMENT`` error is returned. - """ - - class Type(proto.Enum): - r"""The document types enum. - - Values: - TYPE_UNSPECIFIED (0): - The content type is not specified. - PLAIN_TEXT (1): - Plain text - HTML (2): - HTML - """ - TYPE_UNSPECIFIED = 0 - PLAIN_TEXT = 1 - HTML = 2 - - type_: Type = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - content: str = proto.Field( - proto.STRING, - number=2, - oneof="source", - ) - gcs_content_uri: str = proto.Field( - proto.STRING, - number=3, - oneof="source", - ) - language: str = proto.Field( - proto.STRING, - number=4, - ) - - -class Sentence(proto.Message): - r"""Represents a sentence in the input document. - - Attributes: - text (google.cloud.language_v1.types.TextSpan): - The sentence text. - sentiment (google.cloud.language_v1.types.Sentiment): - For calls to [AnalyzeSentiment][] or if - [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment] - is set to true, this field will contain the sentiment for - the sentence. - """ - - text: "TextSpan" = proto.Field( - proto.MESSAGE, - number=1, - message="TextSpan", - ) - sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=2, - message="Sentiment", - ) - - -class Entity(proto.Message): - r"""Represents a phrase in the text that is a known entity, such - as a person, an organization, or location. The API associates - information, such as salience and mentions, with entities. - - Attributes: - name (str): - The representative name for the entity. - type_ (google.cloud.language_v1.types.Entity.Type): - The entity type. - metadata (MutableMapping[str, str]): - Metadata associated with the entity. - - For most entity types, the metadata is a Wikipedia URL - (``wikipedia_url``) and Knowledge Graph MID (``mid``), if - they are available. For the metadata associated with other - entity types, see the Type table below. - salience (float): - The salience score associated with the entity in the [0, - 1.0] range. - - The salience score for an entity provides information about - the importance or centrality of that entity to the entire - document text. Scores closer to 0 are less salient, while - scores closer to 1.0 are highly salient. - mentions (MutableSequence[google.cloud.language_v1.types.EntityMention]): - The mentions of this entity in the input - document. The API currently supports proper noun - mentions. - sentiment (google.cloud.language_v1.types.Sentiment): - For calls to [AnalyzeEntitySentiment][] or if - [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_entity_sentiment] - is set to true, this field will contain the aggregate - sentiment expressed for this entity in the provided - document. - """ - - class Type(proto.Enum): - r"""The type of the entity. For most entity types, the associated - metadata is a Wikipedia URL (``wikipedia_url``) and Knowledge Graph - MID (``mid``). The table below lists the associated fields for - entities that have different metadata. - - Values: - UNKNOWN (0): - Unknown - PERSON (1): - Person - LOCATION (2): - Location - ORGANIZATION (3): - Organization - EVENT (4): - Event - WORK_OF_ART (5): - Artwork - CONSUMER_GOOD (6): - Consumer product - OTHER (7): - Other types of entities - PHONE_NUMBER (9): - Phone number - - The metadata lists the phone number, formatted according to - local convention, plus whichever additional elements appear - in the text: - - - ``number`` - the actual number, broken down into sections - as per local convention - - ``national_prefix`` - country code, if detected - - ``area_code`` - region or area code, if detected - - ``extension`` - phone extension (to be dialed after - connection), if detected - ADDRESS (10): - Address - - The metadata identifies the street number and locality plus - whichever additional elements appear in the text: - - - ``street_number`` - street number - - ``locality`` - city or town - - ``street_name`` - street/route name, if detected - - ``postal_code`` - postal code, if detected - - ``country`` - country, if detected< - - ``broad_region`` - administrative area, such as the - state, if detected - - ``narrow_region`` - smaller administrative area, such as - county, if detected - - ``sublocality`` - used in Asian addresses to demark a - district within a city, if detected - DATE (11): - Date - - The metadata identifies the components of the date: - - - ``year`` - four digit year, if detected - - ``month`` - two digit month number, if detected - - ``day`` - two digit day number, if detected - NUMBER (12): - Number - The metadata is the number itself. - PRICE (13): - Price - - The metadata identifies the ``value`` and ``currency``. - """ - UNKNOWN = 0 - PERSON = 1 - LOCATION = 2 - ORGANIZATION = 3 - EVENT = 4 - WORK_OF_ART = 5 - CONSUMER_GOOD = 6 - OTHER = 7 - PHONE_NUMBER = 9 - ADDRESS = 10 - DATE = 11 - NUMBER = 12 - PRICE = 13 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - salience: float = proto.Field( - proto.FLOAT, - number=4, - ) - mentions: MutableSequence["EntityMention"] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message="EntityMention", - ) - sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=6, - message="Sentiment", - ) - - -class Token(proto.Message): - r"""Represents the smallest syntactic building block of the text. - - Attributes: - text (google.cloud.language_v1.types.TextSpan): - The token text. - part_of_speech (google.cloud.language_v1.types.PartOfSpeech): - Parts of speech tag for this token. - dependency_edge (google.cloud.language_v1.types.DependencyEdge): - Dependency tree parse for this token. - lemma (str): - `Lemma <https://en.wikipedia.org/wiki/Lemma_%28morphology%29>`__ - of the token. - """ - - text: "TextSpan" = proto.Field( - proto.MESSAGE, - number=1, - message="TextSpan", - ) - part_of_speech: "PartOfSpeech" = proto.Field( - proto.MESSAGE, - number=2, - message="PartOfSpeech", - ) - dependency_edge: "DependencyEdge" = proto.Field( - proto.MESSAGE, - number=3, - message="DependencyEdge", - ) - lemma: str = proto.Field( - proto.STRING, - number=4, - ) - - -class Sentiment(proto.Message): - r"""Represents the feeling associated with the entire text or - entities in the text. - - Attributes: - magnitude (float): - A non-negative number in the [0, +inf) range, which - represents the absolute magnitude of sentiment regardless of - score (positive or negative). - score (float): - Sentiment score between -1.0 (negative - sentiment) and 1.0 (positive sentiment). - """ - - magnitude: float = proto.Field( - proto.FLOAT, - number=2, - ) - score: float = proto.Field( - proto.FLOAT, - number=3, - ) - - -class PartOfSpeech(proto.Message): - r"""Represents part of speech information for a token. Parts of speech - are as defined in - http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf - - Attributes: - tag (google.cloud.language_v1.types.PartOfSpeech.Tag): - The part of speech tag. - aspect (google.cloud.language_v1.types.PartOfSpeech.Aspect): - The grammatical aspect. - case (google.cloud.language_v1.types.PartOfSpeech.Case): - The grammatical case. - form (google.cloud.language_v1.types.PartOfSpeech.Form): - The grammatical form. - gender (google.cloud.language_v1.types.PartOfSpeech.Gender): - The grammatical gender. - mood (google.cloud.language_v1.types.PartOfSpeech.Mood): - The grammatical mood. - number (google.cloud.language_v1.types.PartOfSpeech.Number): - The grammatical number. - person (google.cloud.language_v1.types.PartOfSpeech.Person): - The grammatical person. - proper (google.cloud.language_v1.types.PartOfSpeech.Proper): - The grammatical properness. - reciprocity (google.cloud.language_v1.types.PartOfSpeech.Reciprocity): - The grammatical reciprocity. - tense (google.cloud.language_v1.types.PartOfSpeech.Tense): - The grammatical tense. - voice (google.cloud.language_v1.types.PartOfSpeech.Voice): - The grammatical voice. - """ - - class Tag(proto.Enum): - r"""The part of speech tags enum. - - Values: - UNKNOWN (0): - Unknown - ADJ (1): - Adjective - ADP (2): - Adposition (preposition and postposition) - ADV (3): - Adverb - CONJ (4): - Conjunction - DET (5): - Determiner - NOUN (6): - Noun (common and proper) - NUM (7): - Cardinal number - PRON (8): - Pronoun - PRT (9): - Particle or other function word - PUNCT (10): - Punctuation - VERB (11): - Verb (all tenses and modes) - X (12): - Other: foreign words, typos, abbreviations - AFFIX (13): - Affix - """ - UNKNOWN = 0 - ADJ = 1 - ADP = 2 - ADV = 3 - CONJ = 4 - DET = 5 - NOUN = 6 - NUM = 7 - PRON = 8 - PRT = 9 - PUNCT = 10 - VERB = 11 - X = 12 - AFFIX = 13 - - class Aspect(proto.Enum): - r"""The characteristic of a verb that expresses time flow during - an event. - - Values: - ASPECT_UNKNOWN (0): - Aspect is not applicable in the analyzed - language or is not predicted. - PERFECTIVE (1): - Perfective - IMPERFECTIVE (2): - Imperfective - PROGRESSIVE (3): - Progressive - """ - ASPECT_UNKNOWN = 0 - PERFECTIVE = 1 - IMPERFECTIVE = 2 - PROGRESSIVE = 3 - - class Case(proto.Enum): - r"""The grammatical function performed by a noun or pronoun in a - phrase, clause, or sentence. In some languages, other parts of - speech, such as adjective and determiner, take case inflection - in agreement with the noun. - - Values: - CASE_UNKNOWN (0): - Case is not applicable in the analyzed - language or is not predicted. - ACCUSATIVE (1): - Accusative - ADVERBIAL (2): - Adverbial - COMPLEMENTIVE (3): - Complementive - DATIVE (4): - Dative - GENITIVE (5): - Genitive - INSTRUMENTAL (6): - Instrumental - LOCATIVE (7): - Locative - NOMINATIVE (8): - Nominative - OBLIQUE (9): - Oblique - PARTITIVE (10): - Partitive - PREPOSITIONAL (11): - Prepositional - REFLEXIVE_CASE (12): - Reflexive - RELATIVE_CASE (13): - Relative - VOCATIVE (14): - Vocative - """ - CASE_UNKNOWN = 0 - ACCUSATIVE = 1 - ADVERBIAL = 2 - COMPLEMENTIVE = 3 - DATIVE = 4 - GENITIVE = 5 - INSTRUMENTAL = 6 - LOCATIVE = 7 - NOMINATIVE = 8 - OBLIQUE = 9 - PARTITIVE = 10 - PREPOSITIONAL = 11 - REFLEXIVE_CASE = 12 - RELATIVE_CASE = 13 - VOCATIVE = 14 - - class Form(proto.Enum): - r"""Depending on the language, Form can be categorizing different - forms of verbs, adjectives, adverbs, etc. For example, - categorizing inflected endings of verbs and adjectives or - distinguishing between short and long forms of adjectives and - participles - - Values: - FORM_UNKNOWN (0): - Form is not applicable in the analyzed - language or is not predicted. - ADNOMIAL (1): - Adnomial - AUXILIARY (2): - Auxiliary - COMPLEMENTIZER (3): - Complementizer - FINAL_ENDING (4): - Final ending - GERUND (5): - Gerund - REALIS (6): - Realis - IRREALIS (7): - Irrealis - SHORT (8): - Short form - LONG (9): - Long form - ORDER (10): - Order form - SPECIFIC (11): - Specific form - """ - FORM_UNKNOWN = 0 - ADNOMIAL = 1 - AUXILIARY = 2 - COMPLEMENTIZER = 3 - FINAL_ENDING = 4 - GERUND = 5 - REALIS = 6 - IRREALIS = 7 - SHORT = 8 - LONG = 9 - ORDER = 10 - SPECIFIC = 11 - - class Gender(proto.Enum): - r"""Gender classes of nouns reflected in the behaviour of - associated words. - - Values: - GENDER_UNKNOWN (0): - Gender is not applicable in the analyzed - language or is not predicted. - FEMININE (1): - Feminine - MASCULINE (2): - Masculine - NEUTER (3): - Neuter - """ - GENDER_UNKNOWN = 0 - FEMININE = 1 - MASCULINE = 2 - NEUTER = 3 - - class Mood(proto.Enum): - r"""The grammatical feature of verbs, used for showing modality - and attitude. - - Values: - MOOD_UNKNOWN (0): - Mood is not applicable in the analyzed - language or is not predicted. - CONDITIONAL_MOOD (1): - Conditional - IMPERATIVE (2): - Imperative - INDICATIVE (3): - Indicative - INTERROGATIVE (4): - Interrogative - JUSSIVE (5): - Jussive - SUBJUNCTIVE (6): - Subjunctive - """ - MOOD_UNKNOWN = 0 - CONDITIONAL_MOOD = 1 - IMPERATIVE = 2 - INDICATIVE = 3 - INTERROGATIVE = 4 - JUSSIVE = 5 - SUBJUNCTIVE = 6 - - class Number(proto.Enum): - r"""Count distinctions. - - Values: - NUMBER_UNKNOWN (0): - Number is not applicable in the analyzed - language or is not predicted. - SINGULAR (1): - Singular - PLURAL (2): - Plural - DUAL (3): - Dual - """ - NUMBER_UNKNOWN = 0 - SINGULAR = 1 - PLURAL = 2 - DUAL = 3 - - class Person(proto.Enum): - r"""The distinction between the speaker, second person, third - person, etc. - - Values: - PERSON_UNKNOWN (0): - Person is not applicable in the analyzed - language or is not predicted. - FIRST (1): - First - SECOND (2): - Second - THIRD (3): - Third - REFLEXIVE_PERSON (4): - Reflexive - """ - PERSON_UNKNOWN = 0 - FIRST = 1 - SECOND = 2 - THIRD = 3 - REFLEXIVE_PERSON = 4 - - class Proper(proto.Enum): - r"""This category shows if the token is part of a proper name. - - Values: - PROPER_UNKNOWN (0): - Proper is not applicable in the analyzed - language or is not predicted. - PROPER (1): - Proper - NOT_PROPER (2): - Not proper - """ - PROPER_UNKNOWN = 0 - PROPER = 1 - NOT_PROPER = 2 - - class Reciprocity(proto.Enum): - r"""Reciprocal features of a pronoun. - - Values: - RECIPROCITY_UNKNOWN (0): - Reciprocity is not applicable in the analyzed - language or is not predicted. - RECIPROCAL (1): - Reciprocal - NON_RECIPROCAL (2): - Non-reciprocal - """ - RECIPROCITY_UNKNOWN = 0 - RECIPROCAL = 1 - NON_RECIPROCAL = 2 - - class Tense(proto.Enum): - r"""Time reference. - - Values: - TENSE_UNKNOWN (0): - Tense is not applicable in the analyzed - language or is not predicted. - CONDITIONAL_TENSE (1): - Conditional - FUTURE (2): - Future - PAST (3): - Past - PRESENT (4): - Present - IMPERFECT (5): - Imperfect - PLUPERFECT (6): - Pluperfect - """ - TENSE_UNKNOWN = 0 - CONDITIONAL_TENSE = 1 - FUTURE = 2 - PAST = 3 - PRESENT = 4 - IMPERFECT = 5 - PLUPERFECT = 6 - - class Voice(proto.Enum): - r"""The relationship between the action that a verb expresses and - the participants identified by its arguments. - - Values: - VOICE_UNKNOWN (0): - Voice is not applicable in the analyzed - language or is not predicted. - ACTIVE (1): - Active - CAUSATIVE (2): - Causative - PASSIVE (3): - Passive - """ - VOICE_UNKNOWN = 0 - ACTIVE = 1 - CAUSATIVE = 2 - PASSIVE = 3 - - tag: Tag = proto.Field( - proto.ENUM, - number=1, - enum=Tag, - ) - aspect: Aspect = proto.Field( - proto.ENUM, - number=2, - enum=Aspect, - ) - case: Case = proto.Field( - proto.ENUM, - number=3, - enum=Case, - ) - form: Form = proto.Field( - proto.ENUM, - number=4, - enum=Form, - ) - gender: Gender = proto.Field( - proto.ENUM, - number=5, - enum=Gender, - ) - mood: Mood = proto.Field( - proto.ENUM, - number=6, - enum=Mood, - ) - number: Number = proto.Field( - proto.ENUM, - number=7, - enum=Number, - ) - person: Person = proto.Field( - proto.ENUM, - number=8, - enum=Person, - ) - proper: Proper = proto.Field( - proto.ENUM, - number=9, - enum=Proper, - ) - reciprocity: Reciprocity = proto.Field( - proto.ENUM, - number=10, - enum=Reciprocity, - ) - tense: Tense = proto.Field( - proto.ENUM, - number=11, - enum=Tense, - ) - voice: Voice = proto.Field( - proto.ENUM, - number=12, - enum=Voice, - ) - - -class DependencyEdge(proto.Message): - r"""Represents dependency parse tree information for a token. - (For more information on dependency labels, see - http://www.aclweb.org/anthology/P13-2017 - - Attributes: - head_token_index (int): - Represents the head of this token in the dependency tree. - This is the index of the token which has an arc going to - this token. The index is the position of the token in the - array of tokens returned by the API method. If this token is - a root token, then the ``head_token_index`` is its own - index. - label (google.cloud.language_v1.types.DependencyEdge.Label): - The parse label for the token. - """ - - class Label(proto.Enum): - r"""The parse label enum for the token. - - Values: - UNKNOWN (0): - Unknown - ABBREV (1): - Abbreviation modifier - ACOMP (2): - Adjectival complement - ADVCL (3): - Adverbial clause modifier - ADVMOD (4): - Adverbial modifier - AMOD (5): - Adjectival modifier of an NP - APPOS (6): - Appositional modifier of an NP - ATTR (7): - Attribute dependent of a copular verb - AUX (8): - Auxiliary (non-main) verb - AUXPASS (9): - Passive auxiliary - CC (10): - Coordinating conjunction - CCOMP (11): - Clausal complement of a verb or adjective - CONJ (12): - Conjunct - CSUBJ (13): - Clausal subject - CSUBJPASS (14): - Clausal passive subject - DEP (15): - Dependency (unable to determine) - DET (16): - Determiner - DISCOURSE (17): - Discourse - DOBJ (18): - Direct object - EXPL (19): - Expletive - GOESWITH (20): - Goes with (part of a word in a text not well - edited) - IOBJ (21): - Indirect object - MARK (22): - Marker (word introducing a subordinate - clause) - MWE (23): - Multi-word expression - MWV (24): - Multi-word verbal expression - NEG (25): - Negation modifier - NN (26): - Noun compound modifier - NPADVMOD (27): - Noun phrase used as an adverbial modifier - NSUBJ (28): - Nominal subject - NSUBJPASS (29): - Passive nominal subject - NUM (30): - Numeric modifier of a noun - NUMBER (31): - Element of compound number - P (32): - Punctuation mark - PARATAXIS (33): - Parataxis relation - PARTMOD (34): - Participial modifier - PCOMP (35): - The complement of a preposition is a clause - POBJ (36): - Object of a preposition - POSS (37): - Possession modifier - POSTNEG (38): - Postverbal negative particle - PRECOMP (39): - Predicate complement - PRECONJ (40): - Preconjunt - PREDET (41): - Predeterminer - PREF (42): - Prefix - PREP (43): - Prepositional modifier - PRONL (44): - The relationship between a verb and verbal - morpheme - PRT (45): - Particle - PS (46): - Associative or possessive marker - QUANTMOD (47): - Quantifier phrase modifier - RCMOD (48): - Relative clause modifier - RCMODREL (49): - Complementizer in relative clause - RDROP (50): - Ellipsis without a preceding predicate - REF (51): - Referent - REMNANT (52): - Remnant - REPARANDUM (53): - Reparandum - ROOT (54): - Root - SNUM (55): - Suffix specifying a unit of number - SUFF (56): - Suffix - TMOD (57): - Temporal modifier - TOPIC (58): - Topic marker - VMOD (59): - Clause headed by an infinite form of the verb - that modifies a noun - VOCATIVE (60): - Vocative - XCOMP (61): - Open clausal complement - SUFFIX (62): - Name suffix - TITLE (63): - Name title - ADVPHMOD (64): - Adverbial phrase modifier - AUXCAUS (65): - Causative auxiliary - AUXVV (66): - Helper auxiliary - DTMOD (67): - Rentaishi (Prenominal modifier) - FOREIGN (68): - Foreign words - KW (69): - Keyword - LIST (70): - List for chains of comparable items - NOMC (71): - Nominalized clause - NOMCSUBJ (72): - Nominalized clausal subject - NOMCSUBJPASS (73): - Nominalized clausal passive - NUMC (74): - Compound of numeric modifier - COP (75): - Copula - DISLOCATED (76): - Dislocated relation (for fronted/topicalized - elements) - ASP (77): - Aspect marker - GMOD (78): - Genitive modifier - GOBJ (79): - Genitive object - INFMOD (80): - Infinitival modifier - MES (81): - Measure - NCOMP (82): - Nominal complement of a noun - """ - UNKNOWN = 0 - ABBREV = 1 - ACOMP = 2 - ADVCL = 3 - ADVMOD = 4 - AMOD = 5 - APPOS = 6 - ATTR = 7 - AUX = 8 - AUXPASS = 9 - CC = 10 - CCOMP = 11 - CONJ = 12 - CSUBJ = 13 - CSUBJPASS = 14 - DEP = 15 - DET = 16 - DISCOURSE = 17 - DOBJ = 18 - EXPL = 19 - GOESWITH = 20 - IOBJ = 21 - MARK = 22 - MWE = 23 - MWV = 24 - NEG = 25 - NN = 26 - NPADVMOD = 27 - NSUBJ = 28 - NSUBJPASS = 29 - NUM = 30 - NUMBER = 31 - P = 32 - PARATAXIS = 33 - PARTMOD = 34 - PCOMP = 35 - POBJ = 36 - POSS = 37 - POSTNEG = 38 - PRECOMP = 39 - PRECONJ = 40 - PREDET = 41 - PREF = 42 - PREP = 43 - PRONL = 44 - PRT = 45 - PS = 46 - QUANTMOD = 47 - RCMOD = 48 - RCMODREL = 49 - RDROP = 50 - REF = 51 - REMNANT = 52 - REPARANDUM = 53 - ROOT = 54 - SNUM = 55 - SUFF = 56 - TMOD = 57 - TOPIC = 58 - VMOD = 59 - VOCATIVE = 60 - XCOMP = 61 - SUFFIX = 62 - TITLE = 63 - ADVPHMOD = 64 - AUXCAUS = 65 - AUXVV = 66 - DTMOD = 67 - FOREIGN = 68 - KW = 69 - LIST = 70 - NOMC = 71 - NOMCSUBJ = 72 - NOMCSUBJPASS = 73 - NUMC = 74 - COP = 75 - DISLOCATED = 76 - ASP = 77 - GMOD = 78 - GOBJ = 79 - INFMOD = 80 - MES = 81 - NCOMP = 82 - - head_token_index: int = proto.Field( - proto.INT32, - number=1, - ) - label: Label = proto.Field( - proto.ENUM, - number=2, - enum=Label, - ) - - -class EntityMention(proto.Message): - r"""Represents a mention for an entity in the text. Currently, - proper noun mentions are supported. - - Attributes: - text (google.cloud.language_v1.types.TextSpan): - The mention text. - type_ (google.cloud.language_v1.types.EntityMention.Type): - The type of the entity mention. - sentiment (google.cloud.language_v1.types.Sentiment): - For calls to [AnalyzeEntitySentiment][] or if - [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_entity_sentiment] - is set to true, this field will contain the sentiment - expressed for this mention of the entity in the provided - document. - """ - - class Type(proto.Enum): - r"""The supported types of mentions. - - Values: - TYPE_UNKNOWN (0): - Unknown - PROPER (1): - Proper name - COMMON (2): - Common noun (or noun compound) - """ - TYPE_UNKNOWN = 0 - PROPER = 1 - COMMON = 2 - - text: "TextSpan" = proto.Field( - proto.MESSAGE, - number=1, - message="TextSpan", - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=3, - message="Sentiment", - ) - - -class TextSpan(proto.Message): - r"""Represents an output piece of text. - - Attributes: - content (str): - The content of the output text. - begin_offset (int): - The API calculates the beginning offset of the content in - the original document according to the - [EncodingType][google.cloud.language.v1.EncodingType] - specified in the API request. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - begin_offset: int = proto.Field( - proto.INT32, - number=2, - ) - - -class ClassificationCategory(proto.Message): - r"""Represents a category returned from the text classifier. - - Attributes: - name (str): - The name of the category representing the - document. - confidence (float): - The classifier's confidence of the category. - Number represents how certain the classifier is - that this category represents the given text. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class ClassificationModelOptions(proto.Message): - r"""Model options available for classification requests. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - v1_model (google.cloud.language_v1.types.ClassificationModelOptions.V1Model): - Setting this field will use the V1 model and - V1 content categories version. The V1 model is a - legacy model; support for this will be - discontinued in the future. - - This field is a member of `oneof`_ ``model_type``. - v2_model (google.cloud.language_v1.types.ClassificationModelOptions.V2Model): - Setting this field will use the V2 model with - the appropriate content categories version. The - V2 model is a better performing model. - - This field is a member of `oneof`_ ``model_type``. - """ - - class V1Model(proto.Message): - r"""Options for the V1 model.""" - - class V2Model(proto.Message): - r"""Options for the V2 model. - - Attributes: - content_categories_version (google.cloud.language_v1.types.ClassificationModelOptions.V2Model.ContentCategoriesVersion): - The content categories used for - classification. - """ - - class ContentCategoriesVersion(proto.Enum): - r"""The content categories used for classification. - - Values: - CONTENT_CATEGORIES_VERSION_UNSPECIFIED (0): - If ``ContentCategoriesVersion`` is not specified, this - option will default to ``V1``. - V1 (1): - Legacy content categories of our initial - launch in 2017. - V2 (2): - Updated content categories in 2022. - """ - CONTENT_CATEGORIES_VERSION_UNSPECIFIED = 0 - V1 = 1 - V2 = 2 - - content_categories_version: "ClassificationModelOptions.V2Model.ContentCategoriesVersion" = proto.Field( - proto.ENUM, - number=1, - enum="ClassificationModelOptions.V2Model.ContentCategoriesVersion", - ) - - v1_model: V1Model = proto.Field( - proto.MESSAGE, - number=1, - oneof="model_type", - message=V1Model, - ) - v2_model: V2Model = proto.Field( - proto.MESSAGE, - number=2, - oneof="model_type", - message=V2Model, - ) - - -class AnalyzeSentimentRequest(proto.Message): - r"""The sentiment analysis request message. - - Attributes: - document (google.cloud.language_v1.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate sentence offsets. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeSentimentResponse(proto.Message): - r"""The sentiment analysis response message. - - Attributes: - document_sentiment (google.cloud.language_v1.types.Sentiment): - The overall sentiment of the input document. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1.Document.language] - field for more details. - sentences (MutableSequence[google.cloud.language_v1.types.Sentence]): - The sentiment for all the sentences in the - document. - """ - - document_sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=1, - message="Sentiment", - ) - language: str = proto.Field( - proto.STRING, - number=2, - ) - sentences: MutableSequence["Sentence"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="Sentence", - ) - - -class AnalyzeEntitySentimentRequest(proto.Message): - r"""The entity-level sentiment analysis request message. - - Attributes: - document (google.cloud.language_v1.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeEntitySentimentResponse(proto.Message): - r"""The entity-level sentiment analysis response message. - - Attributes: - entities (MutableSequence[google.cloud.language_v1.types.Entity]): - The recognized entities in the input document - with associated sentiments. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1.Document.language] - field for more details. - """ - - entities: MutableSequence["Entity"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Entity", - ) - language: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AnalyzeEntitiesRequest(proto.Message): - r"""The entity analysis request message. - - Attributes: - document (google.cloud.language_v1.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeEntitiesResponse(proto.Message): - r"""The entity analysis response message. - - Attributes: - entities (MutableSequence[google.cloud.language_v1.types.Entity]): - The recognized entities in the input - document. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1.Document.language] - field for more details. - """ - - entities: MutableSequence["Entity"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Entity", - ) - language: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AnalyzeSyntaxRequest(proto.Message): - r"""The syntax analysis request message. - - Attributes: - document (google.cloud.language_v1.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeSyntaxResponse(proto.Message): - r"""The syntax analysis response message. - - Attributes: - sentences (MutableSequence[google.cloud.language_v1.types.Sentence]): - Sentences in the input document. - tokens (MutableSequence[google.cloud.language_v1.types.Token]): - Tokens, along with their syntactic - information, in the input document. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1.Document.language] - field for more details. - """ - - sentences: MutableSequence["Sentence"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Sentence", - ) - tokens: MutableSequence["Token"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Token", - ) - language: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ClassifyTextRequest(proto.Message): - r"""The document classification request message. - - Attributes: - document (google.cloud.language_v1.types.Document): - Required. Input document. - classification_model_options (google.cloud.language_v1.types.ClassificationModelOptions): - Model options to use for classification. - Defaults to v1 options if not specified. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - classification_model_options: "ClassificationModelOptions" = proto.Field( - proto.MESSAGE, - number=3, - message="ClassificationModelOptions", - ) - - -class ClassifyTextResponse(proto.Message): - r"""The document classification response message. - - Attributes: - categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): - Categories representing the input document. - """ - - categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="ClassificationCategory", - ) - - -class ModerateTextRequest(proto.Message): - r"""The document moderation request message. - - Attributes: - document (google.cloud.language_v1.types.Document): - Required. Input document. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - - -class ModerateTextResponse(proto.Message): - r"""The document moderation response message. - - Attributes: - moderation_categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): - Harmful and sensitive categories representing - the input document. - """ - - moderation_categories: MutableSequence[ - "ClassificationCategory" - ] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="ClassificationCategory", - ) - - -class AnnotateTextRequest(proto.Message): - r"""The request message for the text annotation API, which can - perform multiple analysis types (sentiment, entities, and - syntax) in one call. - - Attributes: - document (google.cloud.language_v1.types.Document): - Required. Input document. - features (google.cloud.language_v1.types.AnnotateTextRequest.Features): - Required. The enabled features. - encoding_type (google.cloud.language_v1.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - class Features(proto.Message): - r"""All available features for sentiment, syntax, and semantic - analysis. Setting each one to true will enable that specific - analysis for the input. - - Attributes: - extract_syntax (bool): - Extract syntax information. - extract_entities (bool): - Extract entities. - extract_document_sentiment (bool): - Extract document-level sentiment. - extract_entity_sentiment (bool): - Extract entities and their associated - sentiment. - classify_text (bool): - Classify the full document into categories. - moderate_text (bool): - Moderate the document for harmful and - sensitive categories. - classification_model_options (google.cloud.language_v1.types.ClassificationModelOptions): - The model options to use for classification. Defaults to v1 - options if not specified. Only used if ``classify_text`` is - set to true. - """ - - extract_syntax: bool = proto.Field( - proto.BOOL, - number=1, - ) - extract_entities: bool = proto.Field( - proto.BOOL, - number=2, - ) - extract_document_sentiment: bool = proto.Field( - proto.BOOL, - number=3, - ) - extract_entity_sentiment: bool = proto.Field( - proto.BOOL, - number=4, - ) - classify_text: bool = proto.Field( - proto.BOOL, - number=6, - ) - moderate_text: bool = proto.Field( - proto.BOOL, - number=11, - ) - classification_model_options: "ClassificationModelOptions" = proto.Field( - proto.MESSAGE, - number=10, - message="ClassificationModelOptions", - ) - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - features: Features = proto.Field( - proto.MESSAGE, - number=2, - message=Features, - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=3, - enum="EncodingType", - ) - - -class AnnotateTextResponse(proto.Message): - r"""The text annotations response message. - - Attributes: - sentences (MutableSequence[google.cloud.language_v1.types.Sentence]): - Sentences in the input document. Populated if the user - enables - [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1.AnnotateTextRequest.Features.extract_syntax]. - tokens (MutableSequence[google.cloud.language_v1.types.Token]): - Tokens, along with their syntactic information, in the input - document. Populated if the user enables - [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1.AnnotateTextRequest.Features.extract_syntax]. - entities (MutableSequence[google.cloud.language_v1.types.Entity]): - Entities, along with their semantic information, in the - input document. Populated if the user enables - [AnnotateTextRequest.Features.extract_entities][google.cloud.language.v1.AnnotateTextRequest.Features.extract_entities]. - document_sentiment (google.cloud.language_v1.types.Sentiment): - The overall sentiment for the document. Populated if the - user enables - [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1.AnnotateTextRequest.Features.extract_document_sentiment]. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1.Document.language] - field for more details. - categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): - Categories identified in the input document. - moderation_categories (MutableSequence[google.cloud.language_v1.types.ClassificationCategory]): - Harmful and sensitive categories identified - in the input document. - """ - - sentences: MutableSequence["Sentence"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Sentence", - ) - tokens: MutableSequence["Token"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Token", - ) - entities: MutableSequence["Entity"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="Entity", - ) - document_sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=4, - message="Sentiment", - ) - language: str = proto.Field( - proto.STRING, - number=5, - ) - categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message="ClassificationCategory", - ) - moderation_categories: MutableSequence[ - "ClassificationCategory" - ] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message="ClassificationCategory", - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/language_v1beta2/__init__.py b/google/cloud/language_v1beta2/__init__.py deleted file mode 100644 index d8e5de1b..00000000 --- a/google/cloud/language_v1beta2/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.language_v1beta2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.language_service import LanguageServiceAsyncClient, LanguageServiceClient -from .types.language_service import ( - AnalyzeEntitiesRequest, - AnalyzeEntitiesResponse, - AnalyzeEntitySentimentRequest, - AnalyzeEntitySentimentResponse, - AnalyzeSentimentRequest, - AnalyzeSentimentResponse, - AnalyzeSyntaxRequest, - AnalyzeSyntaxResponse, - AnnotateTextRequest, - AnnotateTextResponse, - ClassificationCategory, - ClassificationModelOptions, - ClassifyTextRequest, - ClassifyTextResponse, - DependencyEdge, - Document, - EncodingType, - Entity, - EntityMention, - ModerateTextRequest, - ModerateTextResponse, - PartOfSpeech, - Sentence, - Sentiment, - TextSpan, - Token, -) - -__all__ = ( - "LanguageServiceAsyncClient", - "AnalyzeEntitiesRequest", - "AnalyzeEntitiesResponse", - "AnalyzeEntitySentimentRequest", - "AnalyzeEntitySentimentResponse", - "AnalyzeSentimentRequest", - "AnalyzeSentimentResponse", - "AnalyzeSyntaxRequest", - "AnalyzeSyntaxResponse", - "AnnotateTextRequest", - "AnnotateTextResponse", - "ClassificationCategory", - "ClassificationModelOptions", - "ClassifyTextRequest", - "ClassifyTextResponse", - "DependencyEdge", - "Document", - "EncodingType", - "Entity", - "EntityMention", - "LanguageServiceClient", - "ModerateTextRequest", - "ModerateTextResponse", - "PartOfSpeech", - "Sentence", - "Sentiment", - "TextSpan", - "Token", -) diff --git a/google/cloud/language_v1beta2/gapic_metadata.json b/google/cloud/language_v1beta2/gapic_metadata.json deleted file mode 100644 index 85a901f9..00000000 --- a/google/cloud/language_v1beta2/gapic_metadata.json +++ /dev/null @@ -1,133 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.language_v1beta2", - "protoPackage": "google.cloud.language.v1beta2", - "schema": "1.0", - "services": { - "LanguageService": { - "clients": { - "grpc": { - "libraryClient": "LanguageServiceClient", - "rpcs": { - "AnalyzeEntities": { - "methods": [ - "analyze_entities" - ] - }, - "AnalyzeEntitySentiment": { - "methods": [ - "analyze_entity_sentiment" - ] - }, - "AnalyzeSentiment": { - "methods": [ - "analyze_sentiment" - ] - }, - "AnalyzeSyntax": { - "methods": [ - "analyze_syntax" - ] - }, - "AnnotateText": { - "methods": [ - "annotate_text" - ] - }, - "ClassifyText": { - "methods": [ - "classify_text" - ] - }, - "ModerateText": { - "methods": [ - "moderate_text" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LanguageServiceAsyncClient", - "rpcs": { - "AnalyzeEntities": { - "methods": [ - "analyze_entities" - ] - }, - "AnalyzeEntitySentiment": { - "methods": [ - "analyze_entity_sentiment" - ] - }, - "AnalyzeSentiment": { - "methods": [ - "analyze_sentiment" - ] - }, - "AnalyzeSyntax": { - "methods": [ - "analyze_syntax" - ] - }, - "AnnotateText": { - "methods": [ - "annotate_text" - ] - }, - "ClassifyText": { - "methods": [ - "classify_text" - ] - }, - "ModerateText": { - "methods": [ - "moderate_text" - ] - } - } - }, - "rest": { - "libraryClient": "LanguageServiceClient", - "rpcs": { - "AnalyzeEntities": { - "methods": [ - "analyze_entities" - ] - }, - "AnalyzeEntitySentiment": { - "methods": [ - "analyze_entity_sentiment" - ] - }, - "AnalyzeSentiment": { - "methods": [ - "analyze_sentiment" - ] - }, - "AnalyzeSyntax": { - "methods": [ - "analyze_syntax" - ] - }, - "AnnotateText": { - "methods": [ - "annotate_text" - ] - }, - "ClassifyText": { - "methods": [ - "classify_text" - ] - }, - "ModerateText": { - "methods": [ - "moderate_text" - ] - } - } - } - } - } - } -} diff --git a/google/cloud/language_v1beta2/gapic_version.py b/google/cloud/language_v1beta2/gapic_version.py deleted file mode 100644 index 3dded207..00000000 --- a/google/cloud/language_v1beta2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "2.10.1" # {x-release-please-version} diff --git a/google/cloud/language_v1beta2/py.typed b/google/cloud/language_v1beta2/py.typed deleted file mode 100644 index c0acc99a..00000000 --- a/google/cloud/language_v1beta2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-language package uses inline types. diff --git a/google/cloud/language_v1beta2/services/__init__.py b/google/cloud/language_v1beta2/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/google/cloud/language_v1beta2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/google/cloud/language_v1beta2/services/language_service/__init__.py b/google/cloud/language_v1beta2/services/language_service/__init__.py deleted file mode 100644 index 6a15301c..00000000 --- a/google/cloud/language_v1beta2/services/language_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .async_client import LanguageServiceAsyncClient -from .client import LanguageServiceClient - -__all__ = ( - "LanguageServiceClient", - "LanguageServiceAsyncClient", -) diff --git a/google/cloud/language_v1beta2/services/language_service/async_client.py b/google/cloud/language_v1beta2/services/language_service/async_client.py deleted file mode 100644 index fe13e5fe..00000000 --- a/google/cloud/language_v1beta2/services/language_service/async_client.py +++ /dev/null @@ -1,1035 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import ( - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) - -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.language_v1beta2 import gapic_version as package_version - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.language_v1beta2.types import language_service - -from .client import LanguageServiceClient -from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport -from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport - - -class LanguageServiceAsyncClient: - """Provides text analysis operations such as sentiment analysis - and entity recognition. - """ - - _client: LanguageServiceClient - - DEFAULT_ENDPOINT = LanguageServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LanguageServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod( - LanguageServiceClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - LanguageServiceClient.parse_common_billing_account_path - ) - common_folder_path = staticmethod(LanguageServiceClient.common_folder_path) - parse_common_folder_path = staticmethod( - LanguageServiceClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - LanguageServiceClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - LanguageServiceClient.parse_common_organization_path - ) - common_project_path = staticmethod(LanguageServiceClient.common_project_path) - parse_common_project_path = staticmethod( - LanguageServiceClient.parse_common_project_path - ) - common_location_path = staticmethod(LanguageServiceClient.common_location_path) - parse_common_location_path = staticmethod( - LanguageServiceClient.parse_common_location_path - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceAsyncClient: The constructed client. - """ - return LanguageServiceClient.from_service_account_info.__func__(LanguageServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceAsyncClient: The constructed client. - """ - return LanguageServiceClient.from_service_account_file.__func__(LanguageServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return LanguageServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LanguageServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LanguageServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial( - type(LanguageServiceClient).get_transport_class, type(LanguageServiceClient) - ) - - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, LanguageServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the language service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.LanguageServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = LanguageServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - ) - - async def analyze_sentiment( - self, - request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSentimentResponse: - r"""Analyzes the sentiment of the provided text. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - async def sample_analyze_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]]): - The request object. The sentiment analysis request - message. - document (:class:`google.cloud.language_v1beta2.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1beta2.types.EncodingType`): - The encoding type used by the API to - calculate sentence offsets for the - sentence sentiment. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeSentimentResponse: - The sentiment analysis response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeSentimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_entities( - self, - request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitiesResponse: - r"""Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - async def sample_analyze_entities(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entities(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]]): - The request object. The entity analysis request message. - document (:class:`google.cloud.language_v1beta2.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1beta2.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeEntitiesResponse: - The entity analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeEntitiesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_entities, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_entity_sentiment( - self, - request: Optional[ - Union[language_service.AnalyzeEntitySentimentRequest, dict] - ] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitySentimentResponse: - r"""Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - async def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]]): - The request object. The entity-level sentiment analysis - request message. - document (:class:`google.cloud.language_v1beta2.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1beta2.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeEntitySentimentResponse: - The entity-level sentiment analysis - response message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeEntitySentimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_entity_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_syntax( - self, - request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSyntaxResponse: - r"""Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - async def sample_analyze_syntax(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = await client.analyze_syntax(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]]): - The request object. The syntax analysis request message. - document (:class:`google.cloud.language_v1beta2.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1beta2.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeSyntaxResponse: - The syntax analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnalyzeSyntaxRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_syntax, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def classify_text( - self, - request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ClassifyTextResponse: - r"""Classifies a document into categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - async def sample_classify_text(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = await client.classify_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]]): - The request object. The document classification request - message. - document (:class:`google.cloud.language_v1beta2.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.ClassifyTextResponse: - The document classification response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.ClassifyTextRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.classify_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def moderate_text( - self, - request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ModerateTextResponse: - r"""Moderates a document for harmful and sensitive - categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - async def sample_moderate_text(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ModerateTextRequest( - document=document, - ) - - # Make the request - response = await client.moderate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1beta2.types.ModerateTextRequest, dict]]): - The request object. The document moderation request - message. - document (:class:`google.cloud.language_v1beta2.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.ModerateTextResponse: - The document moderation response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.ModerateTextRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.moderate_text, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def annotate_text( - self, - request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - features: Optional[language_service.AnnotateTextRequest.Features] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnnotateTextResponse: - r"""A convenience method that provides all syntax, - sentiment, entity, and classification features in one - call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - async def sample_annotate_text(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = await client.annotate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]]): - The request object. The request message for the text - annotation API, which can perform - multiple analysis types (sentiment, - entities, and syntax) in one call. - document (:class:`google.cloud.language_v1beta2.types.Document`): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (:class:`google.cloud.language_v1beta2.types.AnnotateTextRequest.Features`): - Required. The enabled features. - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (:class:`google.cloud.language_v1beta2.types.EncodingType`): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnnotateTextResponse: - The text annotations response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, features, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = language_service.AnnotateTextRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if features is not None: - request.features = features - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.annotate_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "LanguageServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -__all__ = ("LanguageServiceAsyncClient",) diff --git a/google/cloud/language_v1beta2/services/language_service/client.py b/google/cloud/language_v1beta2/services/language_service/client.py deleted file mode 100644 index 4888fcfc..00000000 --- a/google/cloud/language_v1beta2/services/language_service/client.py +++ /dev/null @@ -1,1191 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import ( - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.language_v1beta2 import gapic_version as package_version - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.language_v1beta2.types import language_service - -from .transports.base import DEFAULT_CLIENT_INFO, LanguageServiceTransport -from .transports.grpc import LanguageServiceGrpcTransport -from .transports.grpc_asyncio import LanguageServiceGrpcAsyncIOTransport -from .transports.rest import LanguageServiceRestTransport - - -class LanguageServiceClientMeta(type): - """Metaclass for the LanguageService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - - _transport_registry = ( - OrderedDict() - ) # type: Dict[str, Type[LanguageServiceTransport]] - _transport_registry["grpc"] = LanguageServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LanguageServiceRestTransport - - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[LanguageServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class LanguageServiceClient(metaclass=LanguageServiceClientMeta): - """Provides text analysis operations such as sentiment analysis - and entity recognition. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_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: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "language.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - LanguageServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> LanguageServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LanguageServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path( - folder: str, - ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P<folder>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path( - organization: str, - ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P<organization>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path( - project: str, - ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P<project>.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LanguageServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the language service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, LanguageServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( - client_options - ) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, LanguageServiceTransport): - # transport is a LanguageServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def analyze_sentiment( - self, - request: Optional[Union[language_service.AnalyzeSentimentRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSentimentResponse: - r"""Analyzes the sentiment of the provided text. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - def sample_analyze_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeSentimentRequest, dict]): - The request object. The sentiment analysis request - message. - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate sentence offsets for the - sentence sentiment. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeSentimentResponse: - The sentiment analysis response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeSentimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeSentimentRequest): - request = language_service.AnalyzeSentimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_sentiment] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_entities( - self, - request: Optional[Union[language_service.AnalyzeEntitiesRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitiesResponse: - r"""Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - def sample_analyze_entities(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = client.analyze_entities(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest, dict]): - The request object. The entity analysis request message. - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeEntitiesResponse: - The entity analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeEntitiesRequest): - request = language_service.AnalyzeEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_entities] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_entity_sentiment( - self, - request: Optional[ - Union[language_service.AnalyzeEntitySentimentRequest, dict] - ] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitySentimentResponse: - r"""Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest, dict]): - The request object. The entity-level sentiment analysis - request message. - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeEntitySentimentResponse: - The entity-level sentiment analysis - response message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeEntitySentimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeEntitySentimentRequest): - request = language_service.AnalyzeEntitySentimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_entity_sentiment] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_syntax( - self, - request: Optional[Union[language_service.AnalyzeSyntaxRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSyntaxResponse: - r"""Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - def sample_analyze_syntax(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = client.analyze_syntax(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest, dict]): - The request object. The syntax analysis request message. - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnalyzeSyntaxResponse: - The syntax analysis response message. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnalyzeSyntaxRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnalyzeSyntaxRequest): - request = language_service.AnalyzeSyntaxRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_syntax] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def classify_text( - self, - request: Optional[Union[language_service.ClassifyTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ClassifyTextResponse: - r"""Classifies a document into categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - def sample_classify_text(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = client.classify_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1beta2.types.ClassifyTextRequest, dict]): - The request object. The document classification request - message. - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.ClassifyTextResponse: - The document classification response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.ClassifyTextRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.ClassifyTextRequest): - request = language_service.ClassifyTextRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.classify_text] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def moderate_text( - self, - request: Optional[Union[language_service.ModerateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ModerateTextResponse: - r"""Moderates a document for harmful and sensitive - categories. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - def sample_moderate_text(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ModerateTextRequest( - document=document, - ) - - # Make the request - response = client.moderate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1beta2.types.ModerateTextRequest, dict]): - The request object. The document moderation request - message. - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.ModerateTextResponse: - The document moderation response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.ModerateTextRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.ModerateTextRequest): - request = language_service.ModerateTextRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.moderate_text] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def annotate_text( - self, - request: Optional[Union[language_service.AnnotateTextRequest, dict]] = None, - *, - document: Optional[language_service.Document] = None, - features: Optional[language_service.AnnotateTextRequest.Features] = None, - encoding_type: Optional[language_service.EncodingType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnnotateTextResponse: - r"""A convenience method that provides all syntax, - sentiment, entity, and classification features in one - call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import language_v1beta2 - - def sample_annotate_text(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = client.annotate_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.language_v1beta2.types.AnnotateTextRequest, dict]): - The request object. The request message for the text - annotation API, which can perform - multiple analysis types (sentiment, - entities, and syntax) in one call. - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (google.cloud.language_v1beta2.types.AnnotateTextRequest.Features): - Required. The enabled features. - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - - This corresponds to the ``encoding_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.language_v1beta2.types.AnnotateTextResponse: - The text annotations response - message. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, features, encoding_type]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a language_service.AnnotateTextRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, language_service.AnnotateTextRequest): - request = language_service.AnnotateTextRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if document is not None: - request.document = document - if features is not None: - request.features = features - if encoding_type is not None: - request.encoding_type = encoding_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.annotate_text] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "LanguageServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -__all__ = ("LanguageServiceClient",) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py b/google/cloud/language_v1beta2/services/language_service/transports/__init__.py deleted file mode 100644 index 12a453a7..00000000 --- a/google/cloud/language_v1beta2/services/language_service/transports/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import LanguageServiceTransport -from .grpc import LanguageServiceGrpcTransport -from .grpc_asyncio import LanguageServiceGrpcAsyncIOTransport -from .rest import LanguageServiceRestInterceptor, LanguageServiceRestTransport - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LanguageServiceTransport]] -_transport_registry["grpc"] = LanguageServiceGrpcTransport -_transport_registry["grpc_asyncio"] = LanguageServiceGrpcAsyncIOTransport -_transport_registry["rest"] = LanguageServiceRestTransport - -__all__ = ( - "LanguageServiceTransport", - "LanguageServiceGrpcTransport", - "LanguageServiceGrpcAsyncIOTransport", - "LanguageServiceRestTransport", - "LanguageServiceRestInterceptor", -) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/base.py b/google/cloud/language_v1beta2/services/language_service/transports/base.py deleted file mode 100644 index 06cd03ef..00000000 --- a/google/cloud/language_v1beta2/services/language_service/transports/base.py +++ /dev/null @@ -1,323 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.language_v1beta2 import gapic_version as package_version -from google.cloud.language_v1beta2.types import language_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - - -class LanguageServiceTransport(abc.ABC): - """Abstract transport class for LanguageService.""" - - AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ) - - DEFAULT_HOST: str = "language.googleapis.com" - - def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[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, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - 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): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.analyze_sentiment: gapic_v1.method.wrap_method( - self.analyze_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.analyze_entities: gapic_v1.method.wrap_method( - self.analyze_entities, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.analyze_entity_sentiment: gapic_v1.method.wrap_method( - self.analyze_entity_sentiment, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.analyze_syntax: gapic_v1.method.wrap_method( - self.analyze_syntax, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.classify_text: gapic_v1.method.wrap_method( - self.classify_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.moderate_text: gapic_v1.method.wrap_method( - self.moderate_text, - default_timeout=None, - client_info=client_info, - ), - self.annotate_text: gapic_v1.method.wrap_method( - self.annotate_text, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - Union[ - language_service.AnalyzeSentimentResponse, - Awaitable[language_service.AnalyzeSentimentResponse], - ], - ]: - raise NotImplementedError() - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - Union[ - language_service.AnalyzeEntitiesResponse, - Awaitable[language_service.AnalyzeEntitiesResponse], - ], - ]: - raise NotImplementedError() - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - Union[ - language_service.AnalyzeEntitySentimentResponse, - Awaitable[language_service.AnalyzeEntitySentimentResponse], - ], - ]: - raise NotImplementedError() - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], - Union[ - language_service.AnalyzeSyntaxResponse, - Awaitable[language_service.AnalyzeSyntaxResponse], - ], - ]: - raise NotImplementedError() - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], - Union[ - language_service.ClassifyTextResponse, - Awaitable[language_service.ClassifyTextResponse], - ], - ]: - raise NotImplementedError() - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], - Union[ - language_service.ModerateTextResponse, - Awaitable[language_service.ModerateTextResponse], - ], - ]: - raise NotImplementedError() - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], - Union[ - language_service.AnnotateTextResponse, - Awaitable[language_service.AnnotateTextResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ("LanguageServiceTransport",) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc.py deleted file mode 100644 index ec629428..00000000 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc.py +++ /dev/null @@ -1,450 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Callable, Dict, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import gapic_v1, grpc_helpers -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.language_v1beta2.types import language_service - -from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport - - -class LanguageServiceGrpcTransport(LanguageServiceTransport): - """gRPC backend transport for LanguageService. - - Provides text analysis operations such as sentiment analysis - and entity recognition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _stubs: Dict[str, Callable] - - def __init__( - self, - *, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # 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 - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel( - cls, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs, - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" - return self._grpc_channel - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - language_service.AnalyzeSentimentResponse, - ]: - r"""Return a callable for the analyze sentiment method over gRPC. - - Analyzes the sentiment of the provided text. - - Returns: - Callable[[~.AnalyzeSentimentRequest], - ~.AnalyzeSentimentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_sentiment" not in self._stubs: - self._stubs["analyze_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeSentiment", - request_serializer=language_service.AnalyzeSentimentRequest.serialize, - response_deserializer=language_service.AnalyzeSentimentResponse.deserialize, - ) - return self._stubs["analyze_sentiment"] - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - language_service.AnalyzeEntitiesResponse, - ]: - r"""Return a callable for the analyze entities method over gRPC. - - Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - Returns: - Callable[[~.AnalyzeEntitiesRequest], - ~.AnalyzeEntitiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entities" not in self._stubs: - self._stubs["analyze_entities"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeEntities", - request_serializer=language_service.AnalyzeEntitiesRequest.serialize, - response_deserializer=language_service.AnalyzeEntitiesResponse.deserialize, - ) - return self._stubs["analyze_entities"] - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - language_service.AnalyzeEntitySentimentResponse, - ]: - r"""Return a callable for the analyze entity sentiment method over gRPC. - - Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - Returns: - Callable[[~.AnalyzeEntitySentimentRequest], - ~.AnalyzeEntitySentimentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entity_sentiment" not in self._stubs: - self._stubs["analyze_entity_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeEntitySentiment", - request_serializer=language_service.AnalyzeEntitySentimentRequest.serialize, - response_deserializer=language_service.AnalyzeEntitySentimentResponse.deserialize, - ) - return self._stubs["analyze_entity_sentiment"] - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], language_service.AnalyzeSyntaxResponse - ]: - r"""Return a callable for the analyze syntax method over gRPC. - - Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - Returns: - Callable[[~.AnalyzeSyntaxRequest], - ~.AnalyzeSyntaxResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_syntax" not in self._stubs: - self._stubs["analyze_syntax"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeSyntax", - request_serializer=language_service.AnalyzeSyntaxRequest.serialize, - response_deserializer=language_service.AnalyzeSyntaxResponse.deserialize, - ) - return self._stubs["analyze_syntax"] - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], language_service.ClassifyTextResponse - ]: - r"""Return a callable for the classify text method over gRPC. - - Classifies a document into categories. - - Returns: - Callable[[~.ClassifyTextRequest], - ~.ClassifyTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "classify_text" not in self._stubs: - self._stubs["classify_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/ClassifyText", - request_serializer=language_service.ClassifyTextRequest.serialize, - response_deserializer=language_service.ClassifyTextResponse.deserialize, - ) - return self._stubs["classify_text"] - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], language_service.ModerateTextResponse - ]: - r"""Return a callable for the moderate text method over gRPC. - - Moderates a document for harmful and sensitive - categories. - - Returns: - Callable[[~.ModerateTextRequest], - ~.ModerateTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "moderate_text" not in self._stubs: - self._stubs["moderate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/ModerateText", - request_serializer=language_service.ModerateTextRequest.serialize, - response_deserializer=language_service.ModerateTextResponse.deserialize, - ) - return self._stubs["moderate_text"] - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], language_service.AnnotateTextResponse - ]: - r"""Return a callable for the annotate text method over gRPC. - - A convenience method that provides all syntax, - sentiment, entity, and classification features in one - call. - - Returns: - Callable[[~.AnnotateTextRequest], - ~.AnnotateTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "annotate_text" not in self._stubs: - self._stubs["annotate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnnotateText", - request_serializer=language_service.AnnotateTextRequest.serialize, - response_deserializer=language_service.AnnotateTextResponse.deserialize, - ) - return self._stubs["annotate_text"] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ("LanguageServiceGrpcTransport",) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py b/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py deleted file mode 100644 index 4d1a8065..00000000 --- a/google/cloud/language_v1beta2/services/language_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,453 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import gapic_v1, grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.language_v1beta2.types import language_service - -from .base import DEFAULT_CLIENT_INFO, LanguageServiceTransport -from .grpc import LanguageServiceGrpcTransport - - -class LanguageServiceGrpcAsyncIOTransport(LanguageServiceTransport): - """gRPC AsyncIO backend transport for LanguageService. - - Provides text analysis operations such as sentiment analysis - and entity recognition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel( - cls, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # 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 - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - Awaitable[language_service.AnalyzeSentimentResponse], - ]: - r"""Return a callable for the analyze sentiment method over gRPC. - - Analyzes the sentiment of the provided text. - - Returns: - Callable[[~.AnalyzeSentimentRequest], - Awaitable[~.AnalyzeSentimentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_sentiment" not in self._stubs: - self._stubs["analyze_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeSentiment", - request_serializer=language_service.AnalyzeSentimentRequest.serialize, - response_deserializer=language_service.AnalyzeSentimentResponse.deserialize, - ) - return self._stubs["analyze_sentiment"] - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - Awaitable[language_service.AnalyzeEntitiesResponse], - ]: - r"""Return a callable for the analyze entities method over gRPC. - - Finds named entities (currently proper names and - common nouns) in the text along with entity types, - salience, mentions for each entity, and other - properties. - - Returns: - Callable[[~.AnalyzeEntitiesRequest], - Awaitable[~.AnalyzeEntitiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entities" not in self._stubs: - self._stubs["analyze_entities"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeEntities", - request_serializer=language_service.AnalyzeEntitiesRequest.serialize, - response_deserializer=language_service.AnalyzeEntitiesResponse.deserialize, - ) - return self._stubs["analyze_entities"] - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - Awaitable[language_service.AnalyzeEntitySentimentResponse], - ]: - r"""Return a callable for the analyze entity sentiment method over gRPC. - - Finds entities, similar to - [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] - in the text and analyzes sentiment associated with each entity - and its mentions. - - Returns: - Callable[[~.AnalyzeEntitySentimentRequest], - Awaitable[~.AnalyzeEntitySentimentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_entity_sentiment" not in self._stubs: - self._stubs["analyze_entity_sentiment"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeEntitySentiment", - request_serializer=language_service.AnalyzeEntitySentimentRequest.serialize, - response_deserializer=language_service.AnalyzeEntitySentimentResponse.deserialize, - ) - return self._stubs["analyze_entity_sentiment"] - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], - Awaitable[language_service.AnalyzeSyntaxResponse], - ]: - r"""Return a callable for the analyze syntax method over gRPC. - - Analyzes the syntax of the text and provides sentence - boundaries and tokenization along with part of speech - tags, dependency trees, and other properties. - - Returns: - Callable[[~.AnalyzeSyntaxRequest], - Awaitable[~.AnalyzeSyntaxResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "analyze_syntax" not in self._stubs: - self._stubs["analyze_syntax"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnalyzeSyntax", - request_serializer=language_service.AnalyzeSyntaxRequest.serialize, - response_deserializer=language_service.AnalyzeSyntaxResponse.deserialize, - ) - return self._stubs["analyze_syntax"] - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], - Awaitable[language_service.ClassifyTextResponse], - ]: - r"""Return a callable for the classify text method over gRPC. - - Classifies a document into categories. - - Returns: - Callable[[~.ClassifyTextRequest], - Awaitable[~.ClassifyTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "classify_text" not in self._stubs: - self._stubs["classify_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/ClassifyText", - request_serializer=language_service.ClassifyTextRequest.serialize, - response_deserializer=language_service.ClassifyTextResponse.deserialize, - ) - return self._stubs["classify_text"] - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], - Awaitable[language_service.ModerateTextResponse], - ]: - r"""Return a callable for the moderate text method over gRPC. - - Moderates a document for harmful and sensitive - categories. - - Returns: - Callable[[~.ModerateTextRequest], - Awaitable[~.ModerateTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "moderate_text" not in self._stubs: - self._stubs["moderate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/ModerateText", - request_serializer=language_service.ModerateTextRequest.serialize, - response_deserializer=language_service.ModerateTextResponse.deserialize, - ) - return self._stubs["moderate_text"] - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], - Awaitable[language_service.AnnotateTextResponse], - ]: - r"""Return a callable for the annotate text method over gRPC. - - A convenience method that provides all syntax, - sentiment, entity, and classification features in one - call. - - Returns: - Callable[[~.AnnotateTextRequest], - Awaitable[~.AnnotateTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "annotate_text" not in self._stubs: - self._stubs["annotate_text"] = self.grpc_channel.unary_unary( - "/google.cloud.language.v1beta2.LanguageService/AnnotateText", - request_serializer=language_service.AnnotateTextRequest.serialize, - response_deserializer=language_service.AnnotateTextResponse.deserialize, - ) - return self._stubs["annotate_text"] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ("LanguageServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/language_v1beta2/services/language_service/transports/rest.py b/google/cloud/language_v1beta2/services/language_service/transports/rest.py deleted file mode 100644 index 90a221e3..00000000 --- a/google/cloud/language_v1beta2/services/language_service/transports/rest.py +++ /dev/null @@ -1,1158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import dataclasses -import json # type: ignore -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.protobuf import json_format -import grpc # type: ignore -from requests import __version__ as requests_version - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.language_v1beta2.types import language_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import LanguageServiceTransport - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class LanguageServiceRestInterceptor: - """Interceptor for LanguageService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the LanguageServiceRestTransport. - - .. code-block:: python - class MyCustomLanguageServiceInterceptor(LanguageServiceRestInterceptor): - def pre_analyze_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_entity_sentiment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_entity_sentiment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_sentiment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_sentiment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_syntax(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_syntax(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_annotate_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_annotate_text(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_classify_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_classify_text(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_moderate_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_moderate_text(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LanguageServiceRestTransport(interceptor=MyCustomLanguageServiceInterceptor()) - client = LanguageServiceClient(transport=transport) - - - """ - - def pre_analyze_entities( - self, - request: language_service.AnalyzeEntitiesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnalyzeEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_entities( - self, response: language_service.AnalyzeEntitiesResponse - ) -> language_service.AnalyzeEntitiesResponse: - """Post-rpc interceptor for analyze_entities - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_analyze_entity_sentiment( - self, - request: language_service.AnalyzeEntitySentimentRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[ - language_service.AnalyzeEntitySentimentRequest, Sequence[Tuple[str, str]] - ]: - """Pre-rpc interceptor for analyze_entity_sentiment - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_entity_sentiment( - self, response: language_service.AnalyzeEntitySentimentResponse - ) -> language_service.AnalyzeEntitySentimentResponse: - """Post-rpc interceptor for analyze_entity_sentiment - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_analyze_sentiment( - self, - request: language_service.AnalyzeSentimentRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnalyzeSentimentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_sentiment - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_sentiment( - self, response: language_service.AnalyzeSentimentResponse - ) -> language_service.AnalyzeSentimentResponse: - """Post-rpc interceptor for analyze_sentiment - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_analyze_syntax( - self, - request: language_service.AnalyzeSyntaxRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnalyzeSyntaxRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_syntax - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_analyze_syntax( - self, response: language_service.AnalyzeSyntaxResponse - ) -> language_service.AnalyzeSyntaxResponse: - """Post-rpc interceptor for analyze_syntax - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_annotate_text( - self, - request: language_service.AnnotateTextRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.AnnotateTextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for annotate_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_annotate_text( - self, response: language_service.AnnotateTextResponse - ) -> language_service.AnnotateTextResponse: - """Post-rpc interceptor for annotate_text - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_classify_text( - self, - request: language_service.ClassifyTextRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.ClassifyTextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for classify_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_classify_text( - self, response: language_service.ClassifyTextResponse - ) -> language_service.ClassifyTextResponse: - """Post-rpc interceptor for classify_text - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - def pre_moderate_text( - self, - request: language_service.ModerateTextRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[language_service.ModerateTextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for moderate_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the LanguageService server. - """ - return request, metadata - - def post_moderate_text( - self, response: language_service.ModerateTextResponse - ) -> language_service.ModerateTextResponse: - """Post-rpc interceptor for moderate_text - - Override in a subclass to manipulate the response - after it is returned by the LanguageService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class LanguageServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LanguageServiceRestInterceptor - - -class LanguageServiceRestTransport(LanguageServiceTransport): - """REST backend transport for LanguageService. - - Provides text analysis operations such as sentiment analysis - and entity recognition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__( - self, - *, - host: str = "language.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[LanguageServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host) - if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or LanguageServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AnalyzeEntities(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeEntitiesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitiesResponse: - r"""Call the analyze entities method over HTTP. - - Args: - request (~.language_service.AnalyzeEntitiesRequest): - The request object. The entity analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeEntitiesResponse: - The entity analysis response message. - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta2/documents:analyzeEntities", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_entities( - request, metadata - ) - pb_request = language_service.AnalyzeEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeEntitiesResponse() - pb_resp = language_service.AnalyzeEntitiesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_entities(resp) - return resp - - class _AnalyzeEntitySentiment(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeEntitySentiment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeEntitySentimentRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeEntitySentimentResponse: - r"""Call the analyze entity sentiment method over HTTP. - - Args: - request (~.language_service.AnalyzeEntitySentimentRequest): - The request object. The entity-level sentiment analysis - request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeEntitySentimentResponse: - The entity-level sentiment analysis - response message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta2/documents:analyzeEntitySentiment", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_entity_sentiment( - request, metadata - ) - pb_request = language_service.AnalyzeEntitySentimentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeEntitySentimentResponse() - pb_resp = language_service.AnalyzeEntitySentimentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_entity_sentiment(resp) - return resp - - class _AnalyzeSentiment(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeSentiment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeSentimentRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSentimentResponse: - r"""Call the analyze sentiment method over HTTP. - - Args: - request (~.language_service.AnalyzeSentimentRequest): - The request object. The sentiment analysis request - message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeSentimentResponse: - The sentiment analysis response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta2/documents:analyzeSentiment", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_sentiment( - request, metadata - ) - pb_request = language_service.AnalyzeSentimentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeSentimentResponse() - pb_resp = language_service.AnalyzeSentimentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_sentiment(resp) - return resp - - class _AnalyzeSyntax(LanguageServiceRestStub): - def __hash__(self): - return hash("AnalyzeSyntax") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnalyzeSyntaxRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnalyzeSyntaxResponse: - r"""Call the analyze syntax method over HTTP. - - Args: - request (~.language_service.AnalyzeSyntaxRequest): - The request object. The syntax analysis request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnalyzeSyntaxResponse: - The syntax analysis response message. - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta2/documents:analyzeSyntax", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_analyze_syntax(request, metadata) - pb_request = language_service.AnalyzeSyntaxRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnalyzeSyntaxResponse() - pb_resp = language_service.AnalyzeSyntaxResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_syntax(resp) - return resp - - class _AnnotateText(LanguageServiceRestStub): - def __hash__(self): - return hash("AnnotateText") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.AnnotateTextRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.AnnotateTextResponse: - r"""Call the annotate text method over HTTP. - - Args: - request (~.language_service.AnnotateTextRequest): - The request object. The request message for the text - annotation API, which can perform - multiple analysis types (sentiment, - entities, and syntax) in one call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.AnnotateTextResponse: - The text annotations response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta2/documents:annotateText", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_annotate_text(request, metadata) - pb_request = language_service.AnnotateTextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.AnnotateTextResponse() - pb_resp = language_service.AnnotateTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_annotate_text(resp) - return resp - - class _ClassifyText(LanguageServiceRestStub): - def __hash__(self): - return hash("ClassifyText") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.ClassifyTextRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ClassifyTextResponse: - r"""Call the classify text method over HTTP. - - Args: - request (~.language_service.ClassifyTextRequest): - The request object. The document classification request - message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.ClassifyTextResponse: - The document classification response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta2/documents:classifyText", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_classify_text(request, metadata) - pb_request = language_service.ClassifyTextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.ClassifyTextResponse() - pb_resp = language_service.ClassifyTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_classify_text(resp) - return resp - - class _ModerateText(LanguageServiceRestStub): - def __hash__(self): - return hash("ModerateText") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: language_service.ModerateTextRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> language_service.ModerateTextResponse: - r"""Call the moderate text method over HTTP. - - Args: - request (~.language_service.ModerateTextRequest): - The request object. The document moderation request - message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.language_service.ModerateTextResponse: - The document moderation response - message. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta2/documents:moderateText", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_moderate_text(request, metadata) - pb_request = language_service.ModerateTextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = language_service.ModerateTextResponse() - pb_resp = language_service.ModerateTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_moderate_text(resp) - return resp - - @property - def analyze_entities( - self, - ) -> Callable[ - [language_service.AnalyzeEntitiesRequest], - language_service.AnalyzeEntitiesResponse, - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_entity_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeEntitySentimentRequest], - language_service.AnalyzeEntitySentimentResponse, - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeEntitySentiment(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_sentiment( - self, - ) -> Callable[ - [language_service.AnalyzeSentimentRequest], - language_service.AnalyzeSentimentResponse, - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeSentiment(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_syntax( - self, - ) -> Callable[ - [language_service.AnalyzeSyntaxRequest], language_service.AnalyzeSyntaxResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeSyntax(self._session, self._host, self._interceptor) # type: ignore - - @property - def annotate_text( - self, - ) -> Callable[ - [language_service.AnnotateTextRequest], language_service.AnnotateTextResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnnotateText(self._session, self._host, self._interceptor) # type: ignore - - @property - def classify_text( - self, - ) -> Callable[ - [language_service.ClassifyTextRequest], language_service.ClassifyTextResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ClassifyText(self._session, self._host, self._interceptor) # type: ignore - - @property - def moderate_text( - self, - ) -> Callable[ - [language_service.ModerateTextRequest], language_service.ModerateTextResponse - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ModerateText(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__ = ("LanguageServiceRestTransport",) diff --git a/google/cloud/language_v1beta2/types/__init__.py b/google/cloud/language_v1beta2/types/__init__.py deleted file mode 100644 index 4f98d4d3..00000000 --- a/google/cloud/language_v1beta2/types/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .language_service import ( - AnalyzeEntitiesRequest, - AnalyzeEntitiesResponse, - AnalyzeEntitySentimentRequest, - AnalyzeEntitySentimentResponse, - AnalyzeSentimentRequest, - AnalyzeSentimentResponse, - AnalyzeSyntaxRequest, - AnalyzeSyntaxResponse, - AnnotateTextRequest, - AnnotateTextResponse, - ClassificationCategory, - ClassificationModelOptions, - ClassifyTextRequest, - ClassifyTextResponse, - DependencyEdge, - Document, - EncodingType, - Entity, - EntityMention, - ModerateTextRequest, - ModerateTextResponse, - PartOfSpeech, - Sentence, - Sentiment, - TextSpan, - Token, -) - -__all__ = ( - "AnalyzeEntitiesRequest", - "AnalyzeEntitiesResponse", - "AnalyzeEntitySentimentRequest", - "AnalyzeEntitySentimentResponse", - "AnalyzeSentimentRequest", - "AnalyzeSentimentResponse", - "AnalyzeSyntaxRequest", - "AnalyzeSyntaxResponse", - "AnnotateTextRequest", - "AnnotateTextResponse", - "ClassificationCategory", - "ClassificationModelOptions", - "ClassifyTextRequest", - "ClassifyTextResponse", - "DependencyEdge", - "Document", - "Entity", - "EntityMention", - "ModerateTextRequest", - "ModerateTextResponse", - "PartOfSpeech", - "Sentence", - "Sentiment", - "TextSpan", - "Token", - "EncodingType", -) diff --git a/google/cloud/language_v1beta2/types/language_service.py b/google/cloud/language_v1beta2/types/language_service.py deleted file mode 100644 index d88273fd..00000000 --- a/google/cloud/language_v1beta2/types/language_service.py +++ /dev/null @@ -1,1769 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -__protobuf__ = proto.module( - package="google.cloud.language.v1beta2", - manifest={ - "EncodingType", - "Document", - "Sentence", - "Entity", - "Token", - "Sentiment", - "PartOfSpeech", - "DependencyEdge", - "EntityMention", - "TextSpan", - "ClassificationCategory", - "ClassificationModelOptions", - "AnalyzeSentimentRequest", - "AnalyzeSentimentResponse", - "AnalyzeEntitySentimentRequest", - "AnalyzeEntitySentimentResponse", - "AnalyzeEntitiesRequest", - "AnalyzeEntitiesResponse", - "AnalyzeSyntaxRequest", - "AnalyzeSyntaxResponse", - "ClassifyTextRequest", - "ClassifyTextResponse", - "ModerateTextRequest", - "ModerateTextResponse", - "AnnotateTextRequest", - "AnnotateTextResponse", - }, -) - - -class EncodingType(proto.Enum): - r"""Represents the text encoding that the caller uses to process the - output. Providing an ``EncodingType`` is recommended because the API - provides the beginning offsets for various outputs, such as tokens - and mentions, and languages that natively use different text - encodings may access offsets differently. - - Values: - NONE (0): - If ``EncodingType`` is not specified, encoding-dependent - information (such as ``begin_offset``) will be set at - ``-1``. - UTF8 (1): - Encoding-dependent information (such as ``begin_offset``) is - calculated based on the UTF-8 encoding of the input. C++ and - Go are examples of languages that use this encoding - natively. - UTF16 (2): - Encoding-dependent information (such as ``begin_offset``) is - calculated based on the UTF-16 encoding of the input. Java - and JavaScript are examples of languages that use this - encoding natively. - UTF32 (3): - Encoding-dependent information (such as ``begin_offset``) is - calculated based on the UTF-32 encoding of the input. Python - is an example of a language that uses this encoding - natively. - """ - NONE = 0 - UTF8 = 1 - UTF16 = 2 - UTF32 = 3 - - -class Document(proto.Message): - r"""Represents the input to API methods. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (google.cloud.language_v1beta2.types.Document.Type): - Required. If the type is not set or is ``TYPE_UNSPECIFIED``, - returns an ``INVALID_ARGUMENT`` error. - content (str): - The content of the input in string format. - Cloud audit logging exempt since it is based on - user data. - - This field is a member of `oneof`_ ``source``. - gcs_content_uri (str): - The Google Cloud Storage URI where the file content is - located. This URI must be of the form: - gs://bucket_name/object_name. For more details, see - https://cloud.google.com/storage/docs/reference-uris. NOTE: - Cloud Storage object versioning is not supported. - - This field is a member of `oneof`_ ``source``. - language (str): - The language of the document (if not specified, the language - is automatically detected). Both ISO and BCP-47 language - codes are accepted. `Language - Support <https://cloud.google.com/natural-language/docs/languages>`__ - lists currently supported languages for each API method. If - the language (either specified by the caller or - automatically detected) is not supported by the called API - method, an ``INVALID_ARGUMENT`` error is returned. - reference_web_uri (str): - The web URI where the document comes from. - This URI is not used for fetching the content, - but as a hint for analyzing the document. - boilerplate_handling (google.cloud.language_v1beta2.types.Document.BoilerplateHandling): - Indicates how detected boilerplate(e.g. - advertisements, copyright declarations, banners) - should be handled for this document. If not - specified, boilerplate will be treated the same - as content. - """ - - class Type(proto.Enum): - r"""The document types enum. - - Values: - TYPE_UNSPECIFIED (0): - The content type is not specified. - PLAIN_TEXT (1): - Plain text - HTML (2): - HTML - """ - TYPE_UNSPECIFIED = 0 - PLAIN_TEXT = 1 - HTML = 2 - - class BoilerplateHandling(proto.Enum): - r"""Ways of handling boilerplate detected in the document - - Values: - BOILERPLATE_HANDLING_UNSPECIFIED (0): - The boilerplate handling is not specified. - SKIP_BOILERPLATE (1): - Do not analyze detected boilerplate. - Reference web URI is required for detecting - boilerplate. - KEEP_BOILERPLATE (2): - Treat boilerplate the same as content. - """ - BOILERPLATE_HANDLING_UNSPECIFIED = 0 - SKIP_BOILERPLATE = 1 - KEEP_BOILERPLATE = 2 - - type_: Type = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - content: str = proto.Field( - proto.STRING, - number=2, - oneof="source", - ) - gcs_content_uri: str = proto.Field( - proto.STRING, - number=3, - oneof="source", - ) - language: str = proto.Field( - proto.STRING, - number=4, - ) - reference_web_uri: str = proto.Field( - proto.STRING, - number=5, - ) - boilerplate_handling: BoilerplateHandling = proto.Field( - proto.ENUM, - number=6, - enum=BoilerplateHandling, - ) - - -class Sentence(proto.Message): - r"""Represents a sentence in the input document. - - Attributes: - text (google.cloud.language_v1beta2.types.TextSpan): - The sentence text. - sentiment (google.cloud.language_v1beta2.types.Sentiment): - For calls to [AnalyzeSentiment][] or if - [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_document_sentiment] - is set to true, this field will contain the sentiment for - the sentence. - """ - - text: "TextSpan" = proto.Field( - proto.MESSAGE, - number=1, - message="TextSpan", - ) - sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=2, - message="Sentiment", - ) - - -class Entity(proto.Message): - r"""Represents a phrase in the text that is a known entity, such - as a person, an organization, or location. The API associates - information, such as salience and mentions, with entities. - - Attributes: - name (str): - The representative name for the entity. - type_ (google.cloud.language_v1beta2.types.Entity.Type): - The entity type. - metadata (MutableMapping[str, str]): - Metadata associated with the entity. - - For most entity types, the metadata is a Wikipedia URL - (``wikipedia_url``) and Knowledge Graph MID (``mid``), if - they are available. For the metadata associated with other - entity types, see the Type table below. - salience (float): - The salience score associated with the entity in the [0, - 1.0] range. - - The salience score for an entity provides information about - the importance or centrality of that entity to the entire - document text. Scores closer to 0 are less salient, while - scores closer to 1.0 are highly salient. - mentions (MutableSequence[google.cloud.language_v1beta2.types.EntityMention]): - The mentions of this entity in the input - document. The API currently supports proper noun - mentions. - sentiment (google.cloud.language_v1beta2.types.Sentiment): - For calls to [AnalyzeEntitySentiment][] or if - [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_entity_sentiment] - is set to true, this field will contain the aggregate - sentiment expressed for this entity in the provided - document. - """ - - class Type(proto.Enum): - r"""The type of the entity. For most entity types, the associated - metadata is a Wikipedia URL (``wikipedia_url``) and Knowledge Graph - MID (``mid``). The table below lists the associated fields for - entities that have different metadata. - - Values: - UNKNOWN (0): - Unknown - PERSON (1): - Person - LOCATION (2): - Location - ORGANIZATION (3): - Organization - EVENT (4): - Event - WORK_OF_ART (5): - Artwork - CONSUMER_GOOD (6): - Consumer product - OTHER (7): - Other types of entities - PHONE_NUMBER (9): - Phone number - - The metadata lists the phone number, formatted according to - local convention, plus whichever additional elements appear - in the text: - - - ``number`` - the actual number, broken down into sections - as per local convention - - ``national_prefix`` - country code, if detected - - ``area_code`` - region or area code, if detected - - ``extension`` - phone extension (to be dialed after - connection), if detected - ADDRESS (10): - Address - - The metadata identifies the street number and locality plus - whichever additional elements appear in the text: - - - ``street_number`` - street number - - ``locality`` - city or town - - ``street_name`` - street/route name, if detected - - ``postal_code`` - postal code, if detected - - ``country`` - country, if detected< - - ``broad_region`` - administrative area, such as the - state, if detected - - ``narrow_region`` - smaller administrative area, such as - county, if detected - - ``sublocality`` - used in Asian addresses to demark a - district within a city, if detected - DATE (11): - Date - - The metadata identifies the components of the date: - - - ``year`` - four digit year, if detected - - ``month`` - two digit month number, if detected - - ``day`` - two digit day number, if detected - NUMBER (12): - Number - The metadata is the number itself. - PRICE (13): - Price - - The metadata identifies the ``value`` and ``currency``. - """ - UNKNOWN = 0 - PERSON = 1 - LOCATION = 2 - ORGANIZATION = 3 - EVENT = 4 - WORK_OF_ART = 5 - CONSUMER_GOOD = 6 - OTHER = 7 - PHONE_NUMBER = 9 - ADDRESS = 10 - DATE = 11 - NUMBER = 12 - PRICE = 13 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - salience: float = proto.Field( - proto.FLOAT, - number=4, - ) - mentions: MutableSequence["EntityMention"] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message="EntityMention", - ) - sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=6, - message="Sentiment", - ) - - -class Token(proto.Message): - r"""Represents the smallest syntactic building block of the text. - - Attributes: - text (google.cloud.language_v1beta2.types.TextSpan): - The token text. - part_of_speech (google.cloud.language_v1beta2.types.PartOfSpeech): - Parts of speech tag for this token. - dependency_edge (google.cloud.language_v1beta2.types.DependencyEdge): - Dependency tree parse for this token. - lemma (str): - `Lemma <https://en.wikipedia.org/wiki/Lemma_%28morphology%29>`__ - of the token. - """ - - text: "TextSpan" = proto.Field( - proto.MESSAGE, - number=1, - message="TextSpan", - ) - part_of_speech: "PartOfSpeech" = proto.Field( - proto.MESSAGE, - number=2, - message="PartOfSpeech", - ) - dependency_edge: "DependencyEdge" = proto.Field( - proto.MESSAGE, - number=3, - message="DependencyEdge", - ) - lemma: str = proto.Field( - proto.STRING, - number=4, - ) - - -class Sentiment(proto.Message): - r"""Represents the feeling associated with the entire text or - entities in the text. - Next ID: 6 - - Attributes: - magnitude (float): - A non-negative number in the [0, +inf) range, which - represents the absolute magnitude of sentiment regardless of - score (positive or negative). - score (float): - Sentiment score between -1.0 (negative - sentiment) and 1.0 (positive sentiment). - """ - - magnitude: float = proto.Field( - proto.FLOAT, - number=2, - ) - score: float = proto.Field( - proto.FLOAT, - number=3, - ) - - -class PartOfSpeech(proto.Message): - r"""Represents part of speech information for a token. - - Attributes: - tag (google.cloud.language_v1beta2.types.PartOfSpeech.Tag): - The part of speech tag. - aspect (google.cloud.language_v1beta2.types.PartOfSpeech.Aspect): - The grammatical aspect. - case (google.cloud.language_v1beta2.types.PartOfSpeech.Case): - The grammatical case. - form (google.cloud.language_v1beta2.types.PartOfSpeech.Form): - The grammatical form. - gender (google.cloud.language_v1beta2.types.PartOfSpeech.Gender): - The grammatical gender. - mood (google.cloud.language_v1beta2.types.PartOfSpeech.Mood): - The grammatical mood. - number (google.cloud.language_v1beta2.types.PartOfSpeech.Number): - The grammatical number. - person (google.cloud.language_v1beta2.types.PartOfSpeech.Person): - The grammatical person. - proper (google.cloud.language_v1beta2.types.PartOfSpeech.Proper): - The grammatical properness. - reciprocity (google.cloud.language_v1beta2.types.PartOfSpeech.Reciprocity): - The grammatical reciprocity. - tense (google.cloud.language_v1beta2.types.PartOfSpeech.Tense): - The grammatical tense. - voice (google.cloud.language_v1beta2.types.PartOfSpeech.Voice): - The grammatical voice. - """ - - class Tag(proto.Enum): - r"""The part of speech tags enum. - - Values: - UNKNOWN (0): - Unknown - ADJ (1): - Adjective - ADP (2): - Adposition (preposition and postposition) - ADV (3): - Adverb - CONJ (4): - Conjunction - DET (5): - Determiner - NOUN (6): - Noun (common and proper) - NUM (7): - Cardinal number - PRON (8): - Pronoun - PRT (9): - Particle or other function word - PUNCT (10): - Punctuation - VERB (11): - Verb (all tenses and modes) - X (12): - Other: foreign words, typos, abbreviations - AFFIX (13): - Affix - """ - UNKNOWN = 0 - ADJ = 1 - ADP = 2 - ADV = 3 - CONJ = 4 - DET = 5 - NOUN = 6 - NUM = 7 - PRON = 8 - PRT = 9 - PUNCT = 10 - VERB = 11 - X = 12 - AFFIX = 13 - - class Aspect(proto.Enum): - r"""The characteristic of a verb that expresses time flow during - an event. - - Values: - ASPECT_UNKNOWN (0): - Aspect is not applicable in the analyzed - language or is not predicted. - PERFECTIVE (1): - Perfective - IMPERFECTIVE (2): - Imperfective - PROGRESSIVE (3): - Progressive - """ - ASPECT_UNKNOWN = 0 - PERFECTIVE = 1 - IMPERFECTIVE = 2 - PROGRESSIVE = 3 - - class Case(proto.Enum): - r"""The grammatical function performed by a noun or pronoun in a - phrase, clause, or sentence. In some languages, other parts of - speech, such as adjective and determiner, take case inflection - in agreement with the noun. - - Values: - CASE_UNKNOWN (0): - Case is not applicable in the analyzed - language or is not predicted. - ACCUSATIVE (1): - Accusative - ADVERBIAL (2): - Adverbial - COMPLEMENTIVE (3): - Complementive - DATIVE (4): - Dative - GENITIVE (5): - Genitive - INSTRUMENTAL (6): - Instrumental - LOCATIVE (7): - Locative - NOMINATIVE (8): - Nominative - OBLIQUE (9): - Oblique - PARTITIVE (10): - Partitive - PREPOSITIONAL (11): - Prepositional - REFLEXIVE_CASE (12): - Reflexive - RELATIVE_CASE (13): - Relative - VOCATIVE (14): - Vocative - """ - CASE_UNKNOWN = 0 - ACCUSATIVE = 1 - ADVERBIAL = 2 - COMPLEMENTIVE = 3 - DATIVE = 4 - GENITIVE = 5 - INSTRUMENTAL = 6 - LOCATIVE = 7 - NOMINATIVE = 8 - OBLIQUE = 9 - PARTITIVE = 10 - PREPOSITIONAL = 11 - REFLEXIVE_CASE = 12 - RELATIVE_CASE = 13 - VOCATIVE = 14 - - class Form(proto.Enum): - r"""Depending on the language, Form can be categorizing different - forms of verbs, adjectives, adverbs, etc. For example, - categorizing inflected endings of verbs and adjectives or - distinguishing between short and long forms of adjectives and - participles - - Values: - FORM_UNKNOWN (0): - Form is not applicable in the analyzed - language or is not predicted. - ADNOMIAL (1): - Adnomial - AUXILIARY (2): - Auxiliary - COMPLEMENTIZER (3): - Complementizer - FINAL_ENDING (4): - Final ending - GERUND (5): - Gerund - REALIS (6): - Realis - IRREALIS (7): - Irrealis - SHORT (8): - Short form - LONG (9): - Long form - ORDER (10): - Order form - SPECIFIC (11): - Specific form - """ - FORM_UNKNOWN = 0 - ADNOMIAL = 1 - AUXILIARY = 2 - COMPLEMENTIZER = 3 - FINAL_ENDING = 4 - GERUND = 5 - REALIS = 6 - IRREALIS = 7 - SHORT = 8 - LONG = 9 - ORDER = 10 - SPECIFIC = 11 - - class Gender(proto.Enum): - r"""Gender classes of nouns reflected in the behaviour of - associated words. - - Values: - GENDER_UNKNOWN (0): - Gender is not applicable in the analyzed - language or is not predicted. - FEMININE (1): - Feminine - MASCULINE (2): - Masculine - NEUTER (3): - Neuter - """ - GENDER_UNKNOWN = 0 - FEMININE = 1 - MASCULINE = 2 - NEUTER = 3 - - class Mood(proto.Enum): - r"""The grammatical feature of verbs, used for showing modality - and attitude. - - Values: - MOOD_UNKNOWN (0): - Mood is not applicable in the analyzed - language or is not predicted. - CONDITIONAL_MOOD (1): - Conditional - IMPERATIVE (2): - Imperative - INDICATIVE (3): - Indicative - INTERROGATIVE (4): - Interrogative - JUSSIVE (5): - Jussive - SUBJUNCTIVE (6): - Subjunctive - """ - MOOD_UNKNOWN = 0 - CONDITIONAL_MOOD = 1 - IMPERATIVE = 2 - INDICATIVE = 3 - INTERROGATIVE = 4 - JUSSIVE = 5 - SUBJUNCTIVE = 6 - - class Number(proto.Enum): - r"""Count distinctions. - - Values: - NUMBER_UNKNOWN (0): - Number is not applicable in the analyzed - language or is not predicted. - SINGULAR (1): - Singular - PLURAL (2): - Plural - DUAL (3): - Dual - """ - NUMBER_UNKNOWN = 0 - SINGULAR = 1 - PLURAL = 2 - DUAL = 3 - - class Person(proto.Enum): - r"""The distinction between the speaker, second person, third - person, etc. - - Values: - PERSON_UNKNOWN (0): - Person is not applicable in the analyzed - language or is not predicted. - FIRST (1): - First - SECOND (2): - Second - THIRD (3): - Third - REFLEXIVE_PERSON (4): - Reflexive - """ - PERSON_UNKNOWN = 0 - FIRST = 1 - SECOND = 2 - THIRD = 3 - REFLEXIVE_PERSON = 4 - - class Proper(proto.Enum): - r"""This category shows if the token is part of a proper name. - - Values: - PROPER_UNKNOWN (0): - Proper is not applicable in the analyzed - language or is not predicted. - PROPER (1): - Proper - NOT_PROPER (2): - Not proper - """ - PROPER_UNKNOWN = 0 - PROPER = 1 - NOT_PROPER = 2 - - class Reciprocity(proto.Enum): - r"""Reciprocal features of a pronoun. - - Values: - RECIPROCITY_UNKNOWN (0): - Reciprocity is not applicable in the analyzed - language or is not predicted. - RECIPROCAL (1): - Reciprocal - NON_RECIPROCAL (2): - Non-reciprocal - """ - RECIPROCITY_UNKNOWN = 0 - RECIPROCAL = 1 - NON_RECIPROCAL = 2 - - class Tense(proto.Enum): - r"""Time reference. - - Values: - TENSE_UNKNOWN (0): - Tense is not applicable in the analyzed - language or is not predicted. - CONDITIONAL_TENSE (1): - Conditional - FUTURE (2): - Future - PAST (3): - Past - PRESENT (4): - Present - IMPERFECT (5): - Imperfect - PLUPERFECT (6): - Pluperfect - """ - TENSE_UNKNOWN = 0 - CONDITIONAL_TENSE = 1 - FUTURE = 2 - PAST = 3 - PRESENT = 4 - IMPERFECT = 5 - PLUPERFECT = 6 - - class Voice(proto.Enum): - r"""The relationship between the action that a verb expresses and - the participants identified by its arguments. - - Values: - VOICE_UNKNOWN (0): - Voice is not applicable in the analyzed - language or is not predicted. - ACTIVE (1): - Active - CAUSATIVE (2): - Causative - PASSIVE (3): - Passive - """ - VOICE_UNKNOWN = 0 - ACTIVE = 1 - CAUSATIVE = 2 - PASSIVE = 3 - - tag: Tag = proto.Field( - proto.ENUM, - number=1, - enum=Tag, - ) - aspect: Aspect = proto.Field( - proto.ENUM, - number=2, - enum=Aspect, - ) - case: Case = proto.Field( - proto.ENUM, - number=3, - enum=Case, - ) - form: Form = proto.Field( - proto.ENUM, - number=4, - enum=Form, - ) - gender: Gender = proto.Field( - proto.ENUM, - number=5, - enum=Gender, - ) - mood: Mood = proto.Field( - proto.ENUM, - number=6, - enum=Mood, - ) - number: Number = proto.Field( - proto.ENUM, - number=7, - enum=Number, - ) - person: Person = proto.Field( - proto.ENUM, - number=8, - enum=Person, - ) - proper: Proper = proto.Field( - proto.ENUM, - number=9, - enum=Proper, - ) - reciprocity: Reciprocity = proto.Field( - proto.ENUM, - number=10, - enum=Reciprocity, - ) - tense: Tense = proto.Field( - proto.ENUM, - number=11, - enum=Tense, - ) - voice: Voice = proto.Field( - proto.ENUM, - number=12, - enum=Voice, - ) - - -class DependencyEdge(proto.Message): - r"""Represents dependency parse tree information for a token. - - Attributes: - head_token_index (int): - Represents the head of this token in the dependency tree. - This is the index of the token which has an arc going to - this token. The index is the position of the token in the - array of tokens returned by the API method. If this token is - a root token, then the ``head_token_index`` is its own - index. - label (google.cloud.language_v1beta2.types.DependencyEdge.Label): - The parse label for the token. - """ - - class Label(proto.Enum): - r"""The parse label enum for the token. - - Values: - UNKNOWN (0): - Unknown - ABBREV (1): - Abbreviation modifier - ACOMP (2): - Adjectival complement - ADVCL (3): - Adverbial clause modifier - ADVMOD (4): - Adverbial modifier - AMOD (5): - Adjectival modifier of an NP - APPOS (6): - Appositional modifier of an NP - ATTR (7): - Attribute dependent of a copular verb - AUX (8): - Auxiliary (non-main) verb - AUXPASS (9): - Passive auxiliary - CC (10): - Coordinating conjunction - CCOMP (11): - Clausal complement of a verb or adjective - CONJ (12): - Conjunct - CSUBJ (13): - Clausal subject - CSUBJPASS (14): - Clausal passive subject - DEP (15): - Dependency (unable to determine) - DET (16): - Determiner - DISCOURSE (17): - Discourse - DOBJ (18): - Direct object - EXPL (19): - Expletive - GOESWITH (20): - Goes with (part of a word in a text not well - edited) - IOBJ (21): - Indirect object - MARK (22): - Marker (word introducing a subordinate - clause) - MWE (23): - Multi-word expression - MWV (24): - Multi-word verbal expression - NEG (25): - Negation modifier - NN (26): - Noun compound modifier - NPADVMOD (27): - Noun phrase used as an adverbial modifier - NSUBJ (28): - Nominal subject - NSUBJPASS (29): - Passive nominal subject - NUM (30): - Numeric modifier of a noun - NUMBER (31): - Element of compound number - P (32): - Punctuation mark - PARATAXIS (33): - Parataxis relation - PARTMOD (34): - Participial modifier - PCOMP (35): - The complement of a preposition is a clause - POBJ (36): - Object of a preposition - POSS (37): - Possession modifier - POSTNEG (38): - Postverbal negative particle - PRECOMP (39): - Predicate complement - PRECONJ (40): - Preconjunt - PREDET (41): - Predeterminer - PREF (42): - Prefix - PREP (43): - Prepositional modifier - PRONL (44): - The relationship between a verb and verbal - morpheme - PRT (45): - Particle - PS (46): - Associative or possessive marker - QUANTMOD (47): - Quantifier phrase modifier - RCMOD (48): - Relative clause modifier - RCMODREL (49): - Complementizer in relative clause - RDROP (50): - Ellipsis without a preceding predicate - REF (51): - Referent - REMNANT (52): - Remnant - REPARANDUM (53): - Reparandum - ROOT (54): - Root - SNUM (55): - Suffix specifying a unit of number - SUFF (56): - Suffix - TMOD (57): - Temporal modifier - TOPIC (58): - Topic marker - VMOD (59): - Clause headed by an infinite form of the verb - that modifies a noun - VOCATIVE (60): - Vocative - XCOMP (61): - Open clausal complement - SUFFIX (62): - Name suffix - TITLE (63): - Name title - ADVPHMOD (64): - Adverbial phrase modifier - AUXCAUS (65): - Causative auxiliary - AUXVV (66): - Helper auxiliary - DTMOD (67): - Rentaishi (Prenominal modifier) - FOREIGN (68): - Foreign words - KW (69): - Keyword - LIST (70): - List for chains of comparable items - NOMC (71): - Nominalized clause - NOMCSUBJ (72): - Nominalized clausal subject - NOMCSUBJPASS (73): - Nominalized clausal passive - NUMC (74): - Compound of numeric modifier - COP (75): - Copula - DISLOCATED (76): - Dislocated relation (for fronted/topicalized - elements) - ASP (77): - Aspect marker - GMOD (78): - Genitive modifier - GOBJ (79): - Genitive object - INFMOD (80): - Infinitival modifier - MES (81): - Measure - NCOMP (82): - Nominal complement of a noun - """ - UNKNOWN = 0 - ABBREV = 1 - ACOMP = 2 - ADVCL = 3 - ADVMOD = 4 - AMOD = 5 - APPOS = 6 - ATTR = 7 - AUX = 8 - AUXPASS = 9 - CC = 10 - CCOMP = 11 - CONJ = 12 - CSUBJ = 13 - CSUBJPASS = 14 - DEP = 15 - DET = 16 - DISCOURSE = 17 - DOBJ = 18 - EXPL = 19 - GOESWITH = 20 - IOBJ = 21 - MARK = 22 - MWE = 23 - MWV = 24 - NEG = 25 - NN = 26 - NPADVMOD = 27 - NSUBJ = 28 - NSUBJPASS = 29 - NUM = 30 - NUMBER = 31 - P = 32 - PARATAXIS = 33 - PARTMOD = 34 - PCOMP = 35 - POBJ = 36 - POSS = 37 - POSTNEG = 38 - PRECOMP = 39 - PRECONJ = 40 - PREDET = 41 - PREF = 42 - PREP = 43 - PRONL = 44 - PRT = 45 - PS = 46 - QUANTMOD = 47 - RCMOD = 48 - RCMODREL = 49 - RDROP = 50 - REF = 51 - REMNANT = 52 - REPARANDUM = 53 - ROOT = 54 - SNUM = 55 - SUFF = 56 - TMOD = 57 - TOPIC = 58 - VMOD = 59 - VOCATIVE = 60 - XCOMP = 61 - SUFFIX = 62 - TITLE = 63 - ADVPHMOD = 64 - AUXCAUS = 65 - AUXVV = 66 - DTMOD = 67 - FOREIGN = 68 - KW = 69 - LIST = 70 - NOMC = 71 - NOMCSUBJ = 72 - NOMCSUBJPASS = 73 - NUMC = 74 - COP = 75 - DISLOCATED = 76 - ASP = 77 - GMOD = 78 - GOBJ = 79 - INFMOD = 80 - MES = 81 - NCOMP = 82 - - head_token_index: int = proto.Field( - proto.INT32, - number=1, - ) - label: Label = proto.Field( - proto.ENUM, - number=2, - enum=Label, - ) - - -class EntityMention(proto.Message): - r"""Represents a mention for an entity in the text. Currently, - proper noun mentions are supported. - - Attributes: - text (google.cloud.language_v1beta2.types.TextSpan): - The mention text. - type_ (google.cloud.language_v1beta2.types.EntityMention.Type): - The type of the entity mention. - sentiment (google.cloud.language_v1beta2.types.Sentiment): - For calls to [AnalyzeEntitySentiment][] or if - [AnnotateTextRequest.Features.extract_entity_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_entity_sentiment] - is set to true, this field will contain the sentiment - expressed for this mention of the entity in the provided - document. - """ - - class Type(proto.Enum): - r"""The supported types of mentions. - - Values: - TYPE_UNKNOWN (0): - Unknown - PROPER (1): - Proper name - COMMON (2): - Common noun (or noun compound) - """ - TYPE_UNKNOWN = 0 - PROPER = 1 - COMMON = 2 - - text: "TextSpan" = proto.Field( - proto.MESSAGE, - number=1, - message="TextSpan", - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=3, - message="Sentiment", - ) - - -class TextSpan(proto.Message): - r"""Represents an output piece of text. - - Attributes: - content (str): - The content of the output text. - begin_offset (int): - The API calculates the beginning offset of the content in - the original document according to the - [EncodingType][google.cloud.language.v1beta2.EncodingType] - specified in the API request. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - begin_offset: int = proto.Field( - proto.INT32, - number=2, - ) - - -class ClassificationCategory(proto.Message): - r"""Represents a category returned from the text classifier. - - Attributes: - name (str): - The name of the category representing the - document. - confidence (float): - The classifier's confidence of the category. - Number represents how certain the classifier is - that this category represents the given text. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -class ClassificationModelOptions(proto.Message): - r"""Model options available for classification requests. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - v1_model (google.cloud.language_v1beta2.types.ClassificationModelOptions.V1Model): - Setting this field will use the V1 model and - V1 content categories version. The V1 model is a - legacy model; support for this will be - discontinued in the future. - - This field is a member of `oneof`_ ``model_type``. - v2_model (google.cloud.language_v1beta2.types.ClassificationModelOptions.V2Model): - Setting this field will use the V2 model with - the appropriate content categories version. The - V2 model is a better performing model. - - This field is a member of `oneof`_ ``model_type``. - """ - - class V1Model(proto.Message): - r"""Options for the V1 model.""" - - class V2Model(proto.Message): - r"""Options for the V2 model. - - Attributes: - content_categories_version (google.cloud.language_v1beta2.types.ClassificationModelOptions.V2Model.ContentCategoriesVersion): - The content categories used for - classification. - """ - - class ContentCategoriesVersion(proto.Enum): - r"""The content categories used for classification. - - Values: - CONTENT_CATEGORIES_VERSION_UNSPECIFIED (0): - If ``ContentCategoriesVersion`` is not specified, this - option will default to ``V1``. - V1 (1): - Legacy content categories of our initial - launch in 2017. - V2 (2): - Updated content categories in 2022. - """ - CONTENT_CATEGORIES_VERSION_UNSPECIFIED = 0 - V1 = 1 - V2 = 2 - - content_categories_version: "ClassificationModelOptions.V2Model.ContentCategoriesVersion" = proto.Field( - proto.ENUM, - number=1, - enum="ClassificationModelOptions.V2Model.ContentCategoriesVersion", - ) - - v1_model: V1Model = proto.Field( - proto.MESSAGE, - number=1, - oneof="model_type", - message=V1Model, - ) - v2_model: V2Model = proto.Field( - proto.MESSAGE, - number=2, - oneof="model_type", - message=V2Model, - ) - - -class AnalyzeSentimentRequest(proto.Message): - r"""The sentiment analysis request message. - - Attributes: - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate sentence offsets for the sentence - sentiment. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeSentimentResponse(proto.Message): - r"""The sentiment analysis response message. - - Attributes: - document_sentiment (google.cloud.language_v1beta2.types.Sentiment): - The overall sentiment of the input document. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1beta2.Document.language] - field for more details. - sentences (MutableSequence[google.cloud.language_v1beta2.types.Sentence]): - The sentiment for all the sentences in the - document. - """ - - document_sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=1, - message="Sentiment", - ) - language: str = proto.Field( - proto.STRING, - number=2, - ) - sentences: MutableSequence["Sentence"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="Sentence", - ) - - -class AnalyzeEntitySentimentRequest(proto.Message): - r"""The entity-level sentiment analysis request message. - - Attributes: - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeEntitySentimentResponse(proto.Message): - r"""The entity-level sentiment analysis response message. - - Attributes: - entities (MutableSequence[google.cloud.language_v1beta2.types.Entity]): - The recognized entities in the input document - with associated sentiments. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1beta2.Document.language] - field for more details. - """ - - entities: MutableSequence["Entity"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Entity", - ) - language: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AnalyzeEntitiesRequest(proto.Message): - r"""The entity analysis request message. - - Attributes: - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeEntitiesResponse(proto.Message): - r"""The entity analysis response message. - - Attributes: - entities (MutableSequence[google.cloud.language_v1beta2.types.Entity]): - The recognized entities in the input - document. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1beta2.Document.language] - field for more details. - """ - - entities: MutableSequence["Entity"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Entity", - ) - language: str = proto.Field( - proto.STRING, - number=2, - ) - - -class AnalyzeSyntaxRequest(proto.Message): - r"""The syntax analysis request message. - - Attributes: - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=2, - enum="EncodingType", - ) - - -class AnalyzeSyntaxResponse(proto.Message): - r"""The syntax analysis response message. - - Attributes: - sentences (MutableSequence[google.cloud.language_v1beta2.types.Sentence]): - Sentences in the input document. - tokens (MutableSequence[google.cloud.language_v1beta2.types.Token]): - Tokens, along with their syntactic - information, in the input document. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1beta2.Document.language] - field for more details. - """ - - sentences: MutableSequence["Sentence"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Sentence", - ) - tokens: MutableSequence["Token"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Token", - ) - language: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ClassifyTextRequest(proto.Message): - r"""The document classification request message. - - Attributes: - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - classification_model_options (google.cloud.language_v1beta2.types.ClassificationModelOptions): - Model options to use for classification. - Defaults to v1 options if not specified. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - classification_model_options: "ClassificationModelOptions" = proto.Field( - proto.MESSAGE, - number=3, - message="ClassificationModelOptions", - ) - - -class ClassifyTextResponse(proto.Message): - r"""The document classification response message. - - Attributes: - categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): - Categories representing the input document. - """ - - categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="ClassificationCategory", - ) - - -class ModerateTextRequest(proto.Message): - r"""The document moderation request message. - - Attributes: - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - """ - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - - -class ModerateTextResponse(proto.Message): - r"""The document moderation response message. - - Attributes: - moderation_categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): - Harmful and sensitive categories representing - the input document. - """ - - moderation_categories: MutableSequence[ - "ClassificationCategory" - ] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="ClassificationCategory", - ) - - -class AnnotateTextRequest(proto.Message): - r"""The request message for the text annotation API, which can - perform multiple analysis types (sentiment, entities, and - syntax) in one call. - - Attributes: - document (google.cloud.language_v1beta2.types.Document): - Required. Input document. - features (google.cloud.language_v1beta2.types.AnnotateTextRequest.Features): - Required. The enabled features. - encoding_type (google.cloud.language_v1beta2.types.EncodingType): - The encoding type used by the API to - calculate offsets. - """ - - class Features(proto.Message): - r"""All available features for sentiment, syntax, and semantic - analysis. Setting each one to true will enable that specific - analysis for the input. Next ID: 12 - - Attributes: - extract_syntax (bool): - Extract syntax information. - extract_entities (bool): - Extract entities. - extract_document_sentiment (bool): - Extract document-level sentiment. - extract_entity_sentiment (bool): - Extract entities and their associated - sentiment. - classify_text (bool): - Classify the full document into categories. If this is true, - the API will use the default model which classifies into a - `predefined - taxonomy <https://cloud.google.com/natural-language/docs/categories>`__. - moderate_text (bool): - Moderate the document for harmful and - sensitive categories. - classification_model_options (google.cloud.language_v1beta2.types.ClassificationModelOptions): - The model options to use for classification. Defaults to v1 - options if not specified. Only used if ``classify_text`` is - set to true. - """ - - extract_syntax: bool = proto.Field( - proto.BOOL, - number=1, - ) - extract_entities: bool = proto.Field( - proto.BOOL, - number=2, - ) - extract_document_sentiment: bool = proto.Field( - proto.BOOL, - number=3, - ) - extract_entity_sentiment: bool = proto.Field( - proto.BOOL, - number=4, - ) - classify_text: bool = proto.Field( - proto.BOOL, - number=6, - ) - moderate_text: bool = proto.Field( - proto.BOOL, - number=11, - ) - classification_model_options: "ClassificationModelOptions" = proto.Field( - proto.MESSAGE, - number=10, - message="ClassificationModelOptions", - ) - - document: "Document" = proto.Field( - proto.MESSAGE, - number=1, - message="Document", - ) - features: Features = proto.Field( - proto.MESSAGE, - number=2, - message=Features, - ) - encoding_type: "EncodingType" = proto.Field( - proto.ENUM, - number=3, - enum="EncodingType", - ) - - -class AnnotateTextResponse(proto.Message): - r"""The text annotations response message. - - Attributes: - sentences (MutableSequence[google.cloud.language_v1beta2.types.Sentence]): - Sentences in the input document. Populated if the user - enables - [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_syntax]. - tokens (MutableSequence[google.cloud.language_v1beta2.types.Token]): - Tokens, along with their syntactic information, in the input - document. Populated if the user enables - [AnnotateTextRequest.Features.extract_syntax][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_syntax]. - entities (MutableSequence[google.cloud.language_v1beta2.types.Entity]): - Entities, along with their semantic information, in the - input document. Populated if the user enables - [AnnotateTextRequest.Features.extract_entities][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_entities]. - document_sentiment (google.cloud.language_v1beta2.types.Sentiment): - The overall sentiment for the document. Populated if the - user enables - [AnnotateTextRequest.Features.extract_document_sentiment][google.cloud.language.v1beta2.AnnotateTextRequest.Features.extract_document_sentiment]. - language (str): - The language of the text, which will be the same as the - language specified in the request or, if not specified, the - automatically-detected language. See - [Document.language][google.cloud.language.v1beta2.Document.language] - field for more details. - categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): - Categories identified in the input document. - moderation_categories (MutableSequence[google.cloud.language_v1beta2.types.ClassificationCategory]): - Harmful and sensitive categories identified - in the input document. - """ - - sentences: MutableSequence["Sentence"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Sentence", - ) - tokens: MutableSequence["Token"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Token", - ) - entities: MutableSequence["Entity"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="Entity", - ) - document_sentiment: "Sentiment" = proto.Field( - proto.MESSAGE, - number=4, - message="Sentiment", - ) - language: str = proto.Field( - proto.STRING, - number=5, - ) - categories: MutableSequence["ClassificationCategory"] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message="ClassificationCategory", - ) - moderation_categories: MutableSequence[ - "ClassificationCategory" - ] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message="ClassificationCategory", - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/language-v1beta2-py.tar.gz b/language-v1beta2-py.tar.gz deleted file mode 100644 index e69de29b..00000000 diff --git a/mypy.ini b/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/noxfile.py b/noxfile.py deleted file mode 100644 index 7d411fea..00000000 --- a/noxfile.py +++ /dev/null @@ -1,425 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2018 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! - -from __future__ import absolute_import - -import os -import pathlib -import re -import shutil -import warnings - -import nox - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -DEFAULT_PYTHON_VERSION = "3.8" - -UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"] -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES = [] -UNIT_TEST_LOCAL_DEPENDENCIES = [] -UNIT_TEST_DEPENDENCIES = [] -UNIT_TEST_EXTRAS = [] -UNIT_TEST_EXTRAS_BY_PYTHON = {} - -SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES = [] -SYSTEM_TEST_DEPENDENCIES = [] -SYSTEM_TEST_EXTRAS = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON = {} - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -# 'docfx' is excluded since it only needs to run in 'docs-presubmit' -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run( - "isort", - "--fss", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -def default(session): - # Install all test dependencies, then install this package in-place. - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - ) - - -@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) -def unit(session): - """Run the unit test suite.""" - default(session) - - -def install_systemtest_dependencies(session, *constraints): - - # Use pre-release gRPC for system tests. - # Exclude version 1.52.0rc1 which has a known issue. - # See https://github.com/grpc/grpc/issues/32163 - session.install("--pre", "grpcio!=1.52.0rc1") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # 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") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.9") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - "sphinx==4.0.1", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python="3.9") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def prerelease_deps(session): - """Run all tests with prerelease versions of dependencies installed.""" - - # Install all dependencies - session.install("-e", ".[all, tests, tracing]") - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "protobuf", - # dependency of grpc - "six", - "googleapis-common-protos", - # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 - "grpcio!=1.52.0rc1", - "grpcio-status", - "google-api-core", - "google-auth", - "proto-plus", - "google-cloud-testutils", - # dependencies of google-cloud-testutils" - "click", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run("python", "-c", "import grpc; print(grpc.__version__)") - - session.run("py.test", "tests/unit") - - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Only run system tests if found. - if os.path.exists(system_test_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if os.path.exists(system_test_folder_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) diff --git a/owlbot.py b/owlbot.py deleted file mode 100644 index ce738f01..00000000 --- a/owlbot.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -from pathlib import Path -import shutil - -import synthtool as s -import synthtool.gcp as gcp -from synthtool.languages import python - -# ---------------------------------------------------------------------------- -# Copy the generated client from the owl-bot staging directory -# ---------------------------------------------------------------------------- - -clean_up_generated_samples = True - -# Load the default version defined in .repo-metadata.json. -default_version = json.load(open(".repo-metadata.json", "rt")).get( - "default_version" -) - -for library in s.get_staging_dirs(default_version): - if clean_up_generated_samples: - shutil.rmtree("samples/generated_samples", ignore_errors=True) - clean_up_generated_samples = False - s.move([library], excludes=["**/gapic_version.py"]) -s.remove_staging_dirs() - -# ---------------------------------------------------------------------------- -# Add templated files -# ---------------------------------------------------------------------------- - -templated_files = gcp.CommonTemplates().py_library( - cov_level=100, - microgenerator=True, - versions=gcp.common.detect_versions(path="./google", default_first=True), -) -s.move(templated_files, excludes=[".coveragerc", ".github/release-please.yml"]) - -python.py_samples(skip_readmes=True) - -# run format session for all directories which have a noxfile -for noxfile in Path(".").glob("**/noxfile.py"): - s.shell.run(["nox", "-s", "format"], cwd=noxfile.parent, hide_output=False) diff --git a/pylint.config.py b/pylint.config.py deleted file mode 100644 index 5d64b9d2..00000000 --- a/pylint.config.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2017 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. - -"""This module is used to configure gcp-devrel-py-tools run-pylint.""" - -# Library configuration - -# library_additions = {} -# library_replacements = {} - -# Test configuration - -# test_additions = copy.deepcopy(library_additions) -# test_replacements = copy.deepcopy(library_replacements) diff --git a/release-please-config.json b/release-please-config.json deleted file mode 100644 index e623c390..00000000 --- a/release-please-config.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", - "packages": { - ".": { - "release-type": "python", - "extra-files": [ - "google/cloud/language/gapic_version.py", - "google/cloud/language_v1beta2/gapic_version.py", - "google/cloud/language_v1/gapic_version.py", - { - "type": "json", - "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1.json", - "jsonpath": "$.clientLibrary.version" - }, - { - "type": "json", - "path": "samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json", - "jsonpath": "$.clientLibrary.version" - } - ] - } - }, - "release-type": "python", - "plugins": [ - { - "type": "sentence-case" - } - ], - "initial-version": "0.1.0" -} diff --git a/renovate.json b/renovate.json deleted file mode 100644 index 39b2a0ec..00000000 --- a/renovate.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": [ - "config:base", - "group:all", - ":preserveSemverRanges", - ":disableDependencyDashboard" - ], - "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt", "setup.py"], - "pip_requirements": { - "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] - } -} diff --git a/samples/README.txt b/samples/README.txt deleted file mode 100644 index c87a54f3..00000000 --- a/samples/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -# Handwritten code samples migrated - -The handwritten samples were moved to: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/language diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py deleted file mode 100644 index 71f2d049..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -async def sample_analyze_entities(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entities(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeEntities_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py deleted file mode 100644 index 14beb557..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entities_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -def sample_analyze_entities(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = client.analyze_entities(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeEntities_sync] diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py deleted file mode 100644 index a8a1b59b..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntitySentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeEntitySentiment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -async def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeEntitySentiment_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py deleted file mode 100644 index c6d27ac8..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_entity_sentiment_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntitySentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync] diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py deleted file mode 100644 index 6b65f274..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeSentiment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -async def sample_analyze_sentiment(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeSentiment_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py deleted file mode 100644 index c9a48df7..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_sentiment_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeSentiment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -def sample_analyze_sentiment(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeSentiment_sync] diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py deleted file mode 100644 index 31640e52..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSyntax -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeSyntax_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -async def sample_analyze_syntax(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = await client.analyze_syntax(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeSyntax_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py deleted file mode 100644 index 947613db..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_analyze_syntax_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSyntax -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnalyzeSyntax_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -def sample_analyze_syntax(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = client.analyze_syntax(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnalyzeSyntax_sync] diff --git a/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py deleted file mode 100644 index 02a54aee..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_annotate_text_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnnotateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnnotateText_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -async def sample_annotate_text(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = await client.annotate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnnotateText_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py deleted file mode 100644 index 9d90a0f0..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_annotate_text_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnnotateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_AnnotateText_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -def sample_annotate_text(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = client.annotate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_AnnotateText_sync] diff --git a/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py deleted file mode 100644 index a6497c09..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_classify_text_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClassifyText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_ClassifyText_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -async def sample_classify_text(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = await client.classify_text(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_ClassifyText_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py deleted file mode 100644 index e1d32646..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_classify_text_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClassifyText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_ClassifyText_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -def sample_classify_text(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = client.classify_text(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_ClassifyText_sync] diff --git a/samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py b/samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py deleted file mode 100644 index 6f4d033d..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_moderate_text_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModerateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_ModerateText_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -async def sample_moderate_text(): - # Create a client - client = language_v1.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ModerateTextRequest( - document=document, - ) - - # Make the request - response = await client.moderate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_ModerateText_async] diff --git a/samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py b/samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py deleted file mode 100644 index 788b4a08..00000000 --- a/samples/generated_samples/language_v1_generated_language_service_moderate_text_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModerateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1_generated_LanguageService_ModerateText_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1 - - -def sample_moderate_text(): - # Create a client - client = language_v1.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1.Document() - document.content = "content_value" - - request = language_v1.ModerateTextRequest( - document=document, - ) - - # Make the request - response = client.moderate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1_generated_LanguageService_ModerateText_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py deleted file mode 100644 index ef2d4a6d..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -async def sample_analyze_entities(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entities(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeEntities_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py deleted file mode 100644 index b8c2694b..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entities_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -def sample_analyze_entities(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitiesRequest( - document=document, - ) - - # Make the request - response = client.analyze_entities(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeEntities_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py deleted file mode 100644 index 818d4209..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntitySentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -async def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py deleted file mode 100644 index cabc3ff5..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeEntitySentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -def sample_analyze_entity_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeEntitySentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_entity_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py deleted file mode 100644 index b60e606a..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeSentiment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -async def sample_analyze_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = await client.analyze_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeSentiment_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py deleted file mode 100644 index df735913..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_sentiment_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSentiment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -def sample_analyze_sentiment(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSentimentRequest( - document=document, - ) - - # Make the request - response = client.analyze_sentiment(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py deleted file mode 100644 index e42a0728..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSyntax -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeSyntax_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -async def sample_analyze_syntax(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = await client.analyze_syntax(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeSyntax_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py deleted file mode 100644 index f9ed77cc..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_analyze_syntax_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeSyntax -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -def sample_analyze_syntax(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnalyzeSyntaxRequest( - document=document, - ) - - # Make the request - response = client.analyze_syntax(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py deleted file mode 100644 index 5b17e2b1..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnnotateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnnotateText_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -async def sample_annotate_text(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = await client.annotate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnnotateText_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py deleted file mode 100644 index 701c94e5..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_annotate_text_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnnotateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_AnnotateText_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -def sample_annotate_text(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.AnnotateTextRequest( - document=document, - ) - - # Make the request - response = client.annotate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_AnnotateText_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py deleted file mode 100644 index 94b5ebcc..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClassifyText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_ClassifyText_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -async def sample_classify_text(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = await client.classify_text(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_ClassifyText_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py deleted file mode 100644 index f9415093..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_classify_text_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClassifyText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_ClassifyText_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -def sample_classify_text(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ClassifyTextRequest( - document=document, - ) - - # Make the request - response = client.classify_text(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_ClassifyText_sync] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py b/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py deleted file mode 100644 index d8385285..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModerateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_ModerateText_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -async def sample_moderate_text(): - # Create a client - client = language_v1beta2.LanguageServiceAsyncClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ModerateTextRequest( - document=document, - ) - - # Make the request - response = await client.moderate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_ModerateText_async] diff --git a/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py b/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py deleted file mode 100644 index 78d11521..00000000 --- a/samples/generated_samples/language_v1beta2_generated_language_service_moderate_text_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModerateText -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-language - - -# [START language_v1beta2_generated_LanguageService_ModerateText_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import language_v1beta2 - - -def sample_moderate_text(): - # Create a client - client = language_v1beta2.LanguageServiceClient() - - # Initialize request argument(s) - document = language_v1beta2.Document() - document.content = "content_value" - - request = language_v1beta2.ModerateTextRequest( - document=document, - ) - - # Make the request - response = client.moderate_text(request=request) - - # Handle the response - print(response) - -# [END language_v1beta2_generated_LanguageService_ModerateText_sync] diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json deleted file mode 100644 index c9fb8b8a..00000000 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ /dev/null @@ -1,1190 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.language.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-language", - "version": "2.10.1" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_entities", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntities", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeEntitiesRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeEntitiesResponse", - "shortName": "analyze_entities" - }, - "description": "Sample for AnalyzeEntities", - "file": "language_v1_generated_language_service_analyze_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_entities", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntities", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeEntitiesRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeEntitiesResponse", - "shortName": "analyze_entities" - }, - "description": "Sample for AnalyzeEntities", - "file": "language_v1_generated_language_service_analyze_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeEntities_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_entity_sentiment", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntitySentiment", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntitySentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeEntitySentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeEntitySentimentResponse", - "shortName": "analyze_entity_sentiment" - }, - "description": "Sample for AnalyzeEntitySentiment", - "file": "language_v1_generated_language_service_analyze_entity_sentiment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_entity_sentiment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_entity_sentiment", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeEntitySentiment", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntitySentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeEntitySentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeEntitySentimentResponse", - "shortName": "analyze_entity_sentiment" - }, - "description": "Sample for AnalyzeEntitySentiment", - "file": "language_v1_generated_language_service_analyze_entity_sentiment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_entity_sentiment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_sentiment", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSentiment", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeSentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeSentimentResponse", - "shortName": "analyze_sentiment" - }, - "description": "Sample for AnalyzeSentiment", - "file": "language_v1_generated_language_service_analyze_sentiment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_sentiment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_sentiment", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSentiment", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeSentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeSentimentResponse", - "shortName": "analyze_sentiment" - }, - "description": "Sample for AnalyzeSentiment", - "file": "language_v1_generated_language_service_analyze_sentiment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeSentiment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_sentiment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.analyze_syntax", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSyntax", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSyntax" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeSyntaxRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeSyntaxResponse", - "shortName": "analyze_syntax" - }, - "description": "Sample for AnalyzeSyntax", - "file": "language_v1_generated_language_service_analyze_syntax_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_syntax_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceClient.analyze_syntax", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnalyzeSyntax", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSyntax" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnalyzeSyntaxRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnalyzeSyntaxResponse", - "shortName": "analyze_syntax" - }, - "description": "Sample for AnalyzeSyntax", - "file": "language_v1_generated_language_service_analyze_syntax_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnalyzeSyntax_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_analyze_syntax_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.annotate_text", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnnotateText", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnnotateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnnotateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "features", - "type": "google.cloud.language_v1.types.AnnotateTextRequest.Features" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnnotateTextResponse", - "shortName": "annotate_text" - }, - "description": "Sample for AnnotateText", - "file": "language_v1_generated_language_service_annotate_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnnotateText_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_annotate_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceClient.annotate_text", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.AnnotateText", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnnotateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.AnnotateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "features", - "type": "google.cloud.language_v1.types.AnnotateTextRequest.Features" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.AnnotateTextResponse", - "shortName": "annotate_text" - }, - "description": "Sample for AnnotateText", - "file": "language_v1_generated_language_service_annotate_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_AnnotateText_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_annotate_text_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.classify_text", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.ClassifyText", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ClassifyText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.ClassifyTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.ClassifyTextResponse", - "shortName": "classify_text" - }, - "description": "Sample for ClassifyText", - "file": "language_v1_generated_language_service_classify_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_ClassifyText_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_classify_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceClient.classify_text", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.ClassifyText", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ClassifyText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.ClassifyTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.ClassifyTextResponse", - "shortName": "classify_text" - }, - "description": "Sample for ClassifyText", - "file": "language_v1_generated_language_service_classify_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_ClassifyText_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_classify_text_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceAsyncClient.moderate_text", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.ModerateText", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ModerateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.ModerateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.ModerateTextResponse", - "shortName": "moderate_text" - }, - "description": "Sample for ModerateText", - "file": "language_v1_generated_language_service_moderate_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_ModerateText_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_moderate_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1.LanguageServiceClient.moderate_text", - "method": { - "fullName": "google.cloud.language.v1.LanguageService.ModerateText", - "service": { - "fullName": "google.cloud.language.v1.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ModerateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1.types.ModerateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1.types.ModerateTextResponse", - "shortName": "moderate_text" - }, - "description": "Sample for ModerateText", - "file": "language_v1_generated_language_service_moderate_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1_generated_LanguageService_ModerateText_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1_generated_language_service_moderate_text_sync.py" - } - ] -} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json deleted file mode 100644 index e97d0475..00000000 --- a/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ /dev/null @@ -1,1190 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.language.v1beta2", - "version": "v1beta2" - } - ], - "language": "PYTHON", - "name": "google-cloud-language", - "version": "2.10.1" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_entities", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntities", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitiesResponse", - "shortName": "analyze_entities" - }, - "description": "Sample for AnalyzeEntities", - "file": "language_v1beta2_generated_language_service_analyze_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_entities", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntities", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeEntitiesRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitiesResponse", - "shortName": "analyze_entities" - }, - "description": "Sample for AnalyzeEntities", - "file": "language_v1beta2_generated_language_service_analyze_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntities_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_entity_sentiment", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntitySentiment", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntitySentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentResponse", - "shortName": "analyze_entity_sentiment" - }, - "description": "Sample for AnalyzeEntitySentiment", - "file": "language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_entity_sentiment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_entity_sentiment", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeEntitySentiment", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeEntitySentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeEntitySentimentResponse", - "shortName": "analyze_entity_sentiment" - }, - "description": "Sample for AnalyzeEntitySentiment", - "file": "language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeEntitySentiment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_entity_sentiment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_sentiment", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSentiment", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeSentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeSentimentResponse", - "shortName": "analyze_sentiment" - }, - "description": "Sample for AnalyzeSentiment", - "file": "language_v1beta2_generated_language_service_analyze_sentiment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_sentiment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_sentiment", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSentiment", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSentiment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeSentimentRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeSentimentResponse", - "shortName": "analyze_sentiment" - }, - "description": "Sample for AnalyzeSentiment", - "file": "language_v1beta2_generated_language_service_analyze_sentiment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSentiment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_sentiment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.analyze_syntax", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSyntax", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSyntax" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeSyntaxResponse", - "shortName": "analyze_syntax" - }, - "description": "Sample for AnalyzeSyntax", - "file": "language_v1beta2_generated_language_service_analyze_syntax_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_syntax_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.analyze_syntax", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnalyzeSyntax", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnalyzeSyntax" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnalyzeSyntaxRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnalyzeSyntaxResponse", - "shortName": "analyze_syntax" - }, - "description": "Sample for AnalyzeSyntax", - "file": "language_v1beta2_generated_language_service_analyze_syntax_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnalyzeSyntax_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_analyze_syntax_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.annotate_text", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnnotateText", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnnotateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "features", - "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest.Features" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnnotateTextResponse", - "shortName": "annotate_text" - }, - "description": "Sample for AnnotateText", - "file": "language_v1beta2_generated_language_service_annotate_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_annotate_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.annotate_text", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.AnnotateText", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "AnnotateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "features", - "type": "google.cloud.language_v1beta2.types.AnnotateTextRequest.Features" - }, - { - "name": "encoding_type", - "type": "google.cloud.language_v1beta2.types.EncodingType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.AnnotateTextResponse", - "shortName": "annotate_text" - }, - "description": "Sample for AnnotateText", - "file": "language_v1beta2_generated_language_service_annotate_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_AnnotateText_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_annotate_text_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.classify_text", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.ClassifyText", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ClassifyText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.ClassifyTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.ClassifyTextResponse", - "shortName": "classify_text" - }, - "description": "Sample for ClassifyText", - "file": "language_v1beta2_generated_language_service_classify_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_classify_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.classify_text", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.ClassifyText", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ClassifyText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.ClassifyTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.ClassifyTextResponse", - "shortName": "classify_text" - }, - "description": "Sample for ClassifyText", - "file": "language_v1beta2_generated_language_service_classify_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_ClassifyText_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_classify_text_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient", - "shortName": "LanguageServiceAsyncClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceAsyncClient.moderate_text", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.ModerateText", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ModerateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.ModerateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.ModerateTextResponse", - "shortName": "moderate_text" - }, - "description": "Sample for ModerateText", - "file": "language_v1beta2_generated_language_service_moderate_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_ModerateText_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_moderate_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient", - "shortName": "LanguageServiceClient" - }, - "fullName": "google.cloud.language_v1beta2.LanguageServiceClient.moderate_text", - "method": { - "fullName": "google.cloud.language.v1beta2.LanguageService.ModerateText", - "service": { - "fullName": "google.cloud.language.v1beta2.LanguageService", - "shortName": "LanguageService" - }, - "shortName": "ModerateText" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.language_v1beta2.types.ModerateTextRequest" - }, - { - "name": "document", - "type": "google.cloud.language_v1beta2.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.language_v1beta2.types.ModerateTextResponse", - "shortName": "moderate_text" - }, - "description": "Sample for ModerateText", - "file": "language_v1beta2_generated_language_service_moderate_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "language_v1beta2_generated_LanguageService_ModerateText_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "language_v1beta2_generated_language_service_moderate_text_sync.py" - } - ] -} diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh deleted file mode 100755 index 21f6d2a2..00000000 --- a/scripts/decrypt-secrets.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/bash - -# Copyright 2015 Google Inc. All rights reserved. -# -# 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. - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -ROOT=$( dirname "$DIR" ) - -# Work from the project root. -cd $ROOT - -# Prevent it from overriding files. -# We recommend that sample authors use their own service account files and cloud project. -# In that case, they are supposed to prepare these files by themselves. -if [[ -f "testing/test-env.sh" ]] || \ - [[ -f "testing/service-account.json" ]] || \ - [[ -f "testing/client-secrets.json" ]]; then - echo "One or more target files exist, aborting." - exit 1 -fi - -# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. -PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" - -gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ - --project="${PROJECT_ID}" \ - > testing/test-env.sh -gcloud secrets versions access latest \ - --secret="python-docs-samples-service-account" \ - --project="${PROJECT_ID}" \ - > testing/service-account.json -gcloud secrets versions access latest \ - --secret="python-docs-samples-client-secrets" \ - --project="${PROJECT_ID}" \ - > testing/client-secrets.json diff --git a/scripts/fixup_language_v1_keywords.py b/scripts/fixup_language_v1_keywords.py deleted file mode 100644 index 10fa218c..00000000 --- a/scripts/fixup_language_v1_keywords.py +++ /dev/null @@ -1,182 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class languageCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_entities': ('document', 'encoding_type', ), - 'analyze_entity_sentiment': ('document', 'encoding_type', ), - 'analyze_sentiment': ('document', 'encoding_type', ), - 'analyze_syntax': ('document', 'encoding_type', ), - 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', 'classification_model_options', ), - 'moderate_text': ('document', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=languageCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the language client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/scripts/fixup_language_v1beta2_keywords.py b/scripts/fixup_language_v1beta2_keywords.py deleted file mode 100644 index 10fa218c..00000000 --- a/scripts/fixup_language_v1beta2_keywords.py +++ /dev/null @@ -1,182 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class languageCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_entities': ('document', 'encoding_type', ), - 'analyze_entity_sentiment': ('document', 'encoding_type', ), - 'analyze_sentiment': ('document', 'encoding_type', ), - 'analyze_syntax': ('document', 'encoding_type', ), - 'annotate_text': ('document', 'features', 'encoding_type', ), - 'classify_text': ('document', 'classification_model_options', ), - 'moderate_text': ('document', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=languageCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the language client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py deleted file mode 100644 index 91b59676..00000000 --- a/scripts/readme-gen/readme_gen.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2016 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. - -"""Generates READMEs using configuration defined in yaml.""" - -import argparse -import io -import os -import subprocess - -import jinja2 -import yaml - - -jinja_env = jinja2.Environment( - trim_blocks=True, - loader=jinja2.FileSystemLoader( - os.path.abspath(os.path.join(os.path.dirname(__file__), "templates")) - ), - autoescape=True, -) - -README_TMPL = jinja_env.get_template('README.tmpl.rst') - - -def get_help(file): - return subprocess.check_output(['python', file, '--help']).decode() - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('source') - parser.add_argument('--destination', default='README.rst') - - args = parser.parse_args() - - source = os.path.abspath(args.source) - root = os.path.dirname(source) - destination = os.path.join(root, args.destination) - - jinja_env.globals['get_help'] = get_help - - with io.open(source, 'r') as f: - config = yaml.load(f) - - # This allows get_help to execute in the right directory. - os.chdir(root) - - output = README_TMPL.render(config) - - with io.open(destination, 'w') as f: - f.write(output) - - -if __name__ == '__main__': - main() diff --git a/scripts/readme-gen/templates/README.tmpl.rst b/scripts/readme-gen/templates/README.tmpl.rst deleted file mode 100644 index 4fd23976..00000000 --- a/scripts/readme-gen/templates/README.tmpl.rst +++ /dev/null @@ -1,87 +0,0 @@ -{# The following line is a lie. BUT! Once jinja2 is done with it, it will - become truth! #} -.. This file is automatically generated. Do not edit this file directly. - -{{product.name}} Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/README.rst - - -This directory contains samples for {{product.name}}. {{product.description}} - -{{description}} - -.. _{{product.name}}: {{product.url}} - -{% if required_api_url %} -To run the sample, you need to enable the API at: {{required_api_url}} -{% endif %} - -{% if required_role %} -To run the sample, you need to have `{{required_role}}` role. -{% endif %} - -{{other_required_steps}} - -{% if setup %} -Setup -------------------------------------------------------------------------------- - -{% for section in setup %} - -{% include section + '.tmpl.rst' %} - -{% endfor %} -{% endif %} - -{% if samples %} -Samples -------------------------------------------------------------------------------- - -{% for sample in samples %} -{{sample.name}} -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -{% if not sample.hide_cloudshell_button %} -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/{{sample.file}},{{folder}}/README.rst -{% endif %} - - -{{sample.description}} - -To run this sample: - -.. code-block:: bash - - $ python {{sample.file}} -{% if sample.show_help %} - - {{get_help(sample.file)|indent}} -{% endif %} - - -{% endfor %} -{% endif %} - -{% if cloud_client_library %} - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - -{% endif %} - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/scripts/readme-gen/templates/auth.tmpl.rst b/scripts/readme-gen/templates/auth.tmpl.rst deleted file mode 100644 index 1446b94a..00000000 --- a/scripts/readme-gen/templates/auth.tmpl.rst +++ /dev/null @@ -1,9 +0,0 @@ -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started diff --git a/scripts/readme-gen/templates/auth_api_key.tmpl.rst b/scripts/readme-gen/templates/auth_api_key.tmpl.rst deleted file mode 100644 index 11957ce2..00000000 --- a/scripts/readme-gen/templates/auth_api_key.tmpl.rst +++ /dev/null @@ -1,14 +0,0 @@ -Authentication -++++++++++++++ - -Authentication for this service is done via an `API Key`_. To obtain an API -Key: - -1. Open the `Cloud Platform Console`_ -2. Make sure that billing is enabled for your project. -3. From the **Credentials** page, create a new **API Key** or use an existing - one for your project. - -.. _API Key: - https://developers.google.com/api-client-library/python/guide/aaa_apikeys -.. _Cloud Console: https://console.cloud.google.com/project?_ diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst deleted file mode 100644 index 6f069c6c..00000000 --- a/scripts/readme-gen/templates/install_deps.tmpl.rst +++ /dev/null @@ -1,29 +0,0 @@ -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 3.7+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ diff --git a/scripts/readme-gen/templates/install_portaudio.tmpl.rst b/scripts/readme-gen/templates/install_portaudio.tmpl.rst deleted file mode 100644 index 5ea33d18..00000000 --- a/scripts/readme-gen/templates/install_portaudio.tmpl.rst +++ /dev/null @@ -1,35 +0,0 @@ -Install PortAudio -+++++++++++++++++ - -Install `PortAudio`_. This is required by the `PyAudio`_ library to stream -audio from your computer's microphone. PyAudio depends on PortAudio for cross-platform compatibility, and is installed differently depending on the -platform. - -* For Mac OS X, you can use `Homebrew`_:: - - brew install portaudio - - **Note**: if you encounter an error when running `pip install` that indicates - it can't find `portaudio.h`, try running `pip install` with the following - flags:: - - pip install --global-option='build_ext' \ - --global-option='-I/usr/local/include' \ - --global-option='-L/usr/local/lib' \ - pyaudio - -* For Debian / Ubuntu Linux:: - - apt-get install portaudio19-dev python-all-dev - -* Windows may work without having to install PortAudio explicitly (it will get - installed with PyAudio). - -For more details, see the `PyAudio installation`_ page. - - -.. _PyAudio: https://people.csail.mit.edu/hubert/pyaudio/ -.. _PortAudio: http://www.portaudio.com/ -.. _PyAudio installation: - https://people.csail.mit.edu/hubert/pyaudio/#downloads -.. _Homebrew: http://brew.sh diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index c3a2b39f..00000000 --- a/setup.cfg +++ /dev/null @@ -1,19 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[bdist_wheel] -universal = 1 diff --git a/setup.py b/setup.py deleted file mode 100644 index 8991c6f5..00000000 --- a/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = "google-cloud-language" - - -description = "Google Cloud Language API client library" - -version = {} -with open(os.path.join(package_root, "google/cloud/language/gapic_version.py")) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-language" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/testing/.gitignore b/testing/.gitignore deleted file mode 100644 index b05fbd63..00000000 --- a/testing/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -test-env.sh -service-account.json -client-secrets.json \ No newline at end of file diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/testing/constraints-3.12.txt b/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfe..00000000 --- a/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed..00000000 --- a/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/tests/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/tests/unit/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/tests/unit/gapic/language_v1/__init__.py b/tests/unit/gapic/language_v1/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/tests/unit/gapic/language_v1/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/tests/unit/gapic/language_v1/test_language_service.py b/tests/unit/gapic/language_v1/test_language_service.py deleted file mode 100644 index 77957902..00000000 --- a/tests/unit/gapic/language_v1/test_language_service.py +++ /dev/null @@ -1,4735 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os - -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -from collections.abc import Iterable -import json -import math - -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers -from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response -from requests.sessions import Session - -from google.cloud.language_v1.services.language_service import ( - LanguageServiceAsyncClient, - LanguageServiceClient, - transports, -) -from google.cloud.language_v1.types import language_service - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert LanguageServiceClient._get_default_mtls_endpoint(None) is None - assert ( - LanguageServiceClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (LanguageServiceClient, "grpc"), - (LanguageServiceAsyncClient, "grpc_asyncio"), - (LanguageServiceClient, "rest"), - ], -) -def test_language_service_client_from_service_account_info( - client_class, transport_name -): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - "language.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com" - ) - - -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.LanguageServiceGrpcTransport, "grpc"), - (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LanguageServiceRestTransport, "rest"), - ], -) -def test_language_service_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (LanguageServiceClient, "grpc"), - (LanguageServiceAsyncClient, "grpc_asyncio"), - (LanguageServiceClient, "rest"), - ], -) -def test_language_service_client_from_service_account_file( - client_class, transport_name -): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: - factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - "language.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com" - ) - - -def test_language_service_client_get_transport_class(): - transport = LanguageServiceClient.get_transport_class() - available_transports = [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceRestTransport, - ] - assert transport in available_transports - - transport = LanguageServiceClient.get_transport_class("grpc") - assert transport == transports.LanguageServiceGrpcTransport - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport, "grpc"), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), - ], -) -@mock.patch.object( - LanguageServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceClient), -) -@mock.patch.object( - LanguageServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceAsyncClient), -) -def test_language_service_client_client_options( - client_class, transport_class, transport_name -): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(LanguageServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(LanguageServiceClient, "get_transport_class") as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - "true", - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - "false", - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - ( - LanguageServiceClient, - transports.LanguageServiceRestTransport, - "rest", - "true", - ), - ( - LanguageServiceClient, - transports.LanguageServiceRestTransport, - "rest", - "false", - ), - ], -) -@mock.patch.object( - LanguageServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceClient), -) -@mock.patch.object( - LanguageServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceAsyncClient), -) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_language_service_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient] -) -@mock.patch.object( - LanguageServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceClient), -) -@mock.patch.object( - LanguageServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceAsyncClient), -) -def test_language_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport, "grpc"), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), - ], -) -def test_language_service_client_client_options_scopes( - client_class, transport_class, transport_name -): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest", None), - ], -) -def test_language_service_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): - # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") - - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -def test_language_service_client_client_options_from_dict(): - with mock.patch( - "google.cloud.language_v1.services.language_service.transports.LanguageServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = LanguageServiceClient( - client_options={"api_endpoint": "squid.clam.whelk"} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_language_service_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): - # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") - - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "language.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - scopes=None, - default_host="language.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSentimentRequest, - dict, - ], -) -def test_analyze_sentiment(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSentimentResponse( - language="language_value", - ) - response = client.analyze_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" - - -def test_analyze_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - client.analyze_sentiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() - - -@pytest.mark.asyncio -async def test_analyze_sentiment_async( - transport: str = "grpc_asyncio", - request_type=language_service.AnalyzeSentimentRequest, -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSentimentResponse( - language="language_value", - ) - ) - response = await client.analyze_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_sentiment_async_from_dict(): - await test_analyze_sentiment_async(request_type=dict) - - -def test_analyze_sentiment_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSentimentResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_sentiment_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_sentiment( - language_service.AnalyzeSentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_sentiment_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSentimentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSentimentResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_sentiment( - language_service.AnalyzeSentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitiesRequest, - dict, - ], -) -def test_analyze_entities(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitiesResponse( - language="language_value", - ) - response = client.analyze_entities(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" - - -def test_analyze_entities_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - client.analyze_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() - - -@pytest.mark.asyncio -async def test_analyze_entities_async( - transport: str = "grpc_asyncio", - request_type=language_service.AnalyzeEntitiesRequest, -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitiesResponse( - language="language_value", - ) - ) - response = await client.analyze_entities(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_entities_async_from_dict(): - await test_analyze_entities_async(request_type=dict) - - -def test_analyze_entities_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitiesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_entities( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_entities_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entities( - language_service.AnalyzeEntitiesRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_entities_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitiesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitiesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_entities( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_entities_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_entities( - language_service.AnalyzeEntitiesRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitySentimentRequest, - dict, - ], -) -def test_analyze_entity_sentiment(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitySentimentResponse( - language="language_value", - ) - response = client.analyze_entity_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" - - -def test_analyze_entity_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - client.analyze_entity_sentiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_async( - transport: str = "grpc_asyncio", - request_type=language_service.AnalyzeEntitySentimentRequest, -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitySentimentResponse( - language="language_value", - ) - ) - response = await client.analyze_entity_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_async_from_dict(): - await test_analyze_entity_sentiment_async(request_type=dict) - - -def test_analyze_entity_sentiment_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitySentimentResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_entity_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_entity_sentiment_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entity_sentiment( - language_service.AnalyzeEntitySentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitySentimentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitySentimentResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_entity_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_entity_sentiment( - language_service.AnalyzeEntitySentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSyntaxRequest, - dict, - ], -) -def test_analyze_syntax(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSyntaxResponse( - language="language_value", - ) - response = client.analyze_syntax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" - - -def test_analyze_syntax_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - client.analyze_syntax() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() - - -@pytest.mark.asyncio -async def test_analyze_syntax_async( - transport: str = "grpc_asyncio", request_type=language_service.AnalyzeSyntaxRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSyntaxResponse( - language="language_value", - ) - ) - response = await client.analyze_syntax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_syntax_async_from_dict(): - await test_analyze_syntax_async(request_type=dict) - - -def test_analyze_syntax_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSyntaxResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_syntax( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_syntax_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_syntax( - language_service.AnalyzeSyntaxRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_syntax_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSyntaxResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSyntaxResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_syntax( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_syntax_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_syntax( - language_service.AnalyzeSyntaxRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ClassifyTextRequest, - dict, - ], -) -def test_classify_text(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ClassifyTextResponse() - response = client.classify_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) - - -def test_classify_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - client.classify_text() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() - - -@pytest.mark.asyncio -async def test_classify_text_async( - transport: str = "grpc_asyncio", request_type=language_service.ClassifyTextRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ClassifyTextResponse() - ) - response = await client.classify_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) - - -@pytest.mark.asyncio -async def test_classify_text_async_from_dict(): - await test_classify_text_async(request_type=dict) - - -def test_classify_text_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ClassifyTextResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.classify_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -def test_classify_text_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.classify_text( - language_service.ClassifyTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.asyncio -async def test_classify_text_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ClassifyTextResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ClassifyTextResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.classify_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_classify_text_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.classify_text( - language_service.ClassifyTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ModerateTextRequest, - dict, - ], -) -def test_moderate_text(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ModerateTextResponse() - response = client.moderate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ModerateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ModerateTextResponse) - - -def test_moderate_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - client.moderate_text() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ModerateTextRequest() - - -@pytest.mark.asyncio -async def test_moderate_text_async( - transport: str = "grpc_asyncio", request_type=language_service.ModerateTextRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ModerateTextResponse() - ) - response = await client.moderate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ModerateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ModerateTextResponse) - - -@pytest.mark.asyncio -async def test_moderate_text_async_from_dict(): - await test_moderate_text_async(request_type=dict) - - -def test_moderate_text_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ModerateTextResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.moderate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -def test_moderate_text_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.moderate_text( - language_service.ModerateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.asyncio -async def test_moderate_text_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ModerateTextResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ModerateTextResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.moderate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_moderate_text_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.moderate_text( - language_service.ModerateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnnotateTextRequest, - dict, - ], -) -def test_annotate_text(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnnotateTextResponse( - language="language_value", - ) - response = client.annotate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" - - -def test_annotate_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - client.annotate_text() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() - - -@pytest.mark.asyncio -async def test_annotate_text_async( - transport: str = "grpc_asyncio", request_type=language_service.AnnotateTextRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnnotateTextResponse( - language="language_value", - ) - ) - response = await client.annotate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_annotate_text_async_from_dict(): - await test_annotate_text_async(request_type=dict) - - -def test_annotate_text_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnnotateTextResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.annotate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].features - mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_annotate_text_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_text( - language_service.AnnotateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_annotate_text_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnnotateTextResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnnotateTextResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.annotate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].features - mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_annotate_text_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.annotate_text( - language_service.AnnotateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSentimentRequest, - dict, - ], -) -def test_analyze_sentiment_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSentimentResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_sentiment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" - - -def test_analyze_sentiment_rest_required_fields( - request_type=language_service.AnalyzeSentimentRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSentimentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_sentiment(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_sentiment_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_sentiment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_sentiment_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_sentiment" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_sentiment" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeSentimentRequest.pb( - language_service.AnalyzeSentimentRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnalyzeSentimentResponse.to_json( - language_service.AnalyzeSentimentResponse() - ) - - request = language_service.AnalyzeSentimentRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeSentimentResponse() - - client.analyze_sentiment( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_sentiment_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeSentimentRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_sentiment(request) - - -def test_analyze_sentiment_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSentimentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_sentiment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/documents:analyzeSentiment" % client.transport._host, args[1] - ) - - -def test_analyze_sentiment_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_sentiment( - language_service.AnalyzeSentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_sentiment_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitiesRequest, - dict, - ], -) -def test_analyze_entities_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitiesResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_entities(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" - - -def test_analyze_entities_rest_required_fields( - request_type=language_service.AnalyzeEntitiesRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitiesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_entities(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_entities_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_entities_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_entities" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_entities" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeEntitiesRequest.pb( - language_service.AnalyzeEntitiesRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnalyzeEntitiesResponse.to_json( - language_service.AnalyzeEntitiesResponse() - ) - - request = language_service.AnalyzeEntitiesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeEntitiesResponse() - - client.analyze_entities( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_entities_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeEntitiesRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_entities(request) - - -def test_analyze_entities_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitiesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/documents:analyzeEntities" % client.transport._host, args[1] - ) - - -def test_analyze_entities_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entities( - language_service.AnalyzeEntitiesRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_entities_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitySentimentRequest, - dict, - ], -) -def test_analyze_entity_sentiment_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitySentimentResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_entity_sentiment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" - - -def test_analyze_entity_sentiment_rest_required_fields( - request_type=language_service.AnalyzeEntitySentimentRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitySentimentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_entity_sentiment(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_entity_sentiment_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_entity_sentiment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_entity_sentiment_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_entity_sentiment" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_entity_sentiment" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeEntitySentimentRequest.pb( - language_service.AnalyzeEntitySentimentRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - language_service.AnalyzeEntitySentimentResponse.to_json( - language_service.AnalyzeEntitySentimentResponse() - ) - ) - - request = language_service.AnalyzeEntitySentimentRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeEntitySentimentResponse() - - client.analyze_entity_sentiment( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_entity_sentiment_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeEntitySentimentRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_entity_sentiment(request) - - -def test_analyze_entity_sentiment_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitySentimentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_entity_sentiment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/documents:analyzeEntitySentiment" % client.transport._host, args[1] - ) - - -def test_analyze_entity_sentiment_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entity_sentiment( - language_service.AnalyzeEntitySentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_entity_sentiment_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSyntaxRequest, - dict, - ], -) -def test_analyze_syntax_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSyntaxResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_syntax(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" - - -def test_analyze_syntax_rest_required_fields( - request_type=language_service.AnalyzeSyntaxRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_syntax._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_syntax._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSyntaxResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_syntax(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_syntax_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_syntax._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_syntax_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_syntax" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_syntax" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeSyntaxRequest.pb( - language_service.AnalyzeSyntaxRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnalyzeSyntaxResponse.to_json( - language_service.AnalyzeSyntaxResponse() - ) - - request = language_service.AnalyzeSyntaxRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeSyntaxResponse() - - client.analyze_syntax( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_syntax_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeSyntaxRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_syntax(request) - - -def test_analyze_syntax_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSyntaxResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_syntax(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/documents:analyzeSyntax" % client.transport._host, args[1] - ) - - -def test_analyze_syntax_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_syntax( - language_service.AnalyzeSyntaxRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_syntax_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ClassifyTextRequest, - dict, - ], -) -def test_classify_text_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ClassifyTextResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ClassifyTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.classify_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) - - -def test_classify_text_rest_required_fields( - request_type=language_service.ClassifyTextRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).classify_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).classify_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.ClassifyTextResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.ClassifyTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.classify_text(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_classify_text_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.classify_text._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_classify_text_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_classify_text" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_classify_text" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.ClassifyTextRequest.pb( - language_service.ClassifyTextRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.ClassifyTextResponse.to_json( - language_service.ClassifyTextResponse() - ) - - request = language_service.ClassifyTextRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.ClassifyTextResponse() - - client.classify_text( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_classify_text_rest_bad_request( - transport: str = "rest", request_type=language_service.ClassifyTextRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.classify_text(request) - - -def test_classify_text_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ClassifyTextResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ClassifyTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.classify_text(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/documents:classifyText" % client.transport._host, args[1] - ) - - -def test_classify_text_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.classify_text( - language_service.ClassifyTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -def test_classify_text_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ModerateTextRequest, - dict, - ], -) -def test_moderate_text_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ModerateTextResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ModerateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.moderate_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ModerateTextResponse) - - -def test_moderate_text_rest_required_fields( - request_type=language_service.ModerateTextRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).moderate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).moderate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.ModerateTextResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.ModerateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.moderate_text(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_moderate_text_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.moderate_text._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_moderate_text_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_moderate_text" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_moderate_text" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.ModerateTextRequest.pb( - language_service.ModerateTextRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.ModerateTextResponse.to_json( - language_service.ModerateTextResponse() - ) - - request = language_service.ModerateTextRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.ModerateTextResponse() - - client.moderate_text( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_moderate_text_rest_bad_request( - transport: str = "rest", request_type=language_service.ModerateTextRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.moderate_text(request) - - -def test_moderate_text_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ModerateTextResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ModerateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.moderate_text(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/documents:moderateText" % client.transport._host, args[1] - ) - - -def test_moderate_text_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.moderate_text( - language_service.ModerateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -def test_moderate_text_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnnotateTextRequest, - dict, - ], -) -def test_annotate_text_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnnotateTextResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnnotateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.annotate_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" - - -def test_annotate_text_rest_required_fields( - request_type=language_service.AnnotateTextRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).annotate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).annotate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnnotateTextResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnnotateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.annotate_text(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_annotate_text_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.annotate_text._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "document", - "features", - ) - ) - ) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_annotate_text_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_annotate_text" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_annotate_text" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnnotateTextRequest.pb( - language_service.AnnotateTextRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnnotateTextResponse.to_json( - language_service.AnnotateTextResponse() - ) - - request = language_service.AnnotateTextRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnnotateTextResponse() - - client.annotate_text( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_annotate_text_rest_bad_request( - transport: str = "rest", request_type=language_service.AnnotateTextRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.annotate_text(request) - - -def test_annotate_text_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnnotateTextResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnnotateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.annotate_text(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/documents:annotateText" % client.transport._host, args[1] - ) - - -def test_annotate_text_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_text( - language_service.AnnotateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_annotate_text_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LanguageServiceClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LanguageServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - transports.LanguageServiceRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = LanguageServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LanguageServiceGrpcTransport, - ) - - -def test_language_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) - - -def test_language_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.language_v1.services.language_service.transports.LanguageServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "analyze_sentiment", - "analyze_entities", - "analyze_entity_sentiment", - "analyze_syntax", - "classify_text", - "moderate_text", - "annotate_text", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_language_service_base_transport_with_credentials_file(): - # 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.language_v1.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport( - 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-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - -def test_language_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.language_v1.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport() - adc.assert_called_once() - - -def test_language_service_auth_adc(): - # 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) - LanguageServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_transport_auth_adc(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", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - transports.LanguageServiceRestTransport, - ], -) -def test_language_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LanguageServiceGrpcTransport, grpc_helpers), - (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_language_service_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( - "language.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - scopes=["1", "2"], - default_host="language.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) - - -def test_language_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ) as mock_configure_mtls_channel: - transports.LanguageServiceRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_language_service_host_no_port(transport_name): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="language.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "language.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com" - ) - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_language_service_host_with_port(transport_name): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="language.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "language.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com:8000" - ) - - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_language_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LanguageServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LanguageServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.analyze_sentiment._session - session2 = client2.transport.analyze_sentiment._session - assert session1 != session2 - session1 = client1.transport.analyze_entities._session - session2 = client2.transport.analyze_entities._session - assert session1 != session2 - session1 = client1.transport.analyze_entity_sentiment._session - session2 = client2.transport.analyze_entity_sentiment._session - assert session1 != session2 - session1 = client1.transport.analyze_syntax._session - session2 = client2.transport.analyze_syntax._session - assert session1 != session2 - session1 = client1.transport.classify_text._session - session2 = client2.transport.classify_text._session - assert session1 != session2 - session1 = client1.transport.moderate_text._session - session2 = client2.transport.moderate_text._session - assert session1 != session2 - session1 = client1.transport.annotate_text._session - session2 = client2.transport.annotate_text._session - assert session1 != session2 - - -def test_language_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LanguageServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_language_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LanguageServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = LanguageServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = LanguageServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = LanguageServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = LanguageServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = LanguageServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = LanguageServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) - actual = LanguageServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = LanguageServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = LanguageServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = LanguageServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.LanguageServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.LanguageServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = LanguageServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - "rest", - "grpc", - ] - for transport in transports: - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport), - (LanguageServiceAsyncClient, transports.LanguageServiceGrpcAsyncIOTransport), - ], -) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/tests/unit/gapic/language_v1beta2/__init__.py b/tests/unit/gapic/language_v1beta2/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/tests/unit/gapic/language_v1beta2/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/tests/unit/gapic/language_v1beta2/test_language_service.py b/tests/unit/gapic/language_v1beta2/test_language_service.py deleted file mode 100644 index adfc2301..00000000 --- a/tests/unit/gapic/language_v1beta2/test_language_service.py +++ /dev/null @@ -1,4736 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os - -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -from collections.abc import Iterable -import json -import math - -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers -from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response -from requests.sessions import Session - -from google.cloud.language_v1beta2.services.language_service import ( - LanguageServiceAsyncClient, - LanguageServiceClient, - transports, -) -from google.cloud.language_v1beta2.types import language_service - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert LanguageServiceClient._get_default_mtls_endpoint(None) is None - assert ( - LanguageServiceClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - LanguageServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (LanguageServiceClient, "grpc"), - (LanguageServiceAsyncClient, "grpc_asyncio"), - (LanguageServiceClient, "rest"), - ], -) -def test_language_service_client_from_service_account_info( - client_class, transport_name -): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - "language.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com" - ) - - -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.LanguageServiceGrpcTransport, "grpc"), - (transports.LanguageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LanguageServiceRestTransport, "rest"), - ], -) -def test_language_service_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (LanguageServiceClient, "grpc"), - (LanguageServiceAsyncClient, "grpc_asyncio"), - (LanguageServiceClient, "rest"), - ], -) -def test_language_service_client_from_service_account_file( - client_class, transport_name -): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: - factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - "language.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com" - ) - - -def test_language_service_client_get_transport_class(): - transport = LanguageServiceClient.get_transport_class() - available_transports = [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceRestTransport, - ] - assert transport in available_transports - - transport = LanguageServiceClient.get_transport_class("grpc") - assert transport == transports.LanguageServiceGrpcTransport - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport, "grpc"), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), - ], -) -@mock.patch.object( - LanguageServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceClient), -) -@mock.patch.object( - LanguageServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceAsyncClient), -) -def test_language_service_client_client_options( - client_class, transport_class, transport_name -): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(LanguageServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(LanguageServiceClient, "get_transport_class") as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - "true", - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - "false", - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - ( - LanguageServiceClient, - transports.LanguageServiceRestTransport, - "rest", - "true", - ), - ( - LanguageServiceClient, - transports.LanguageServiceRestTransport, - "rest", - "false", - ), - ], -) -@mock.patch.object( - LanguageServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceClient), -) -@mock.patch.object( - LanguageServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceAsyncClient), -) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_language_service_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class", [LanguageServiceClient, LanguageServiceAsyncClient] -) -@mock.patch.object( - LanguageServiceClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceClient), -) -@mock.patch.object( - LanguageServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(LanguageServiceAsyncClient), -) -def test_language_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport, "grpc"), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest"), - ], -) -def test_language_service_client_client_options_scopes( - client_class, transport_class, transport_name -): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (LanguageServiceClient, transports.LanguageServiceRestTransport, "rest", None), - ], -) -def test_language_service_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): - # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") - - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -def test_language_service_client_client_options_from_dict(): - with mock.patch( - "google.cloud.language_v1beta2.services.language_service.transports.LanguageServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = LanguageServiceClient( - client_options={"api_endpoint": "squid.clam.whelk"} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - LanguageServiceClient, - transports.LanguageServiceGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - LanguageServiceAsyncClient, - transports.LanguageServiceGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_language_service_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): - # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") - - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "language.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - scopes=None, - default_host="language.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSentimentRequest, - dict, - ], -) -def test_analyze_sentiment(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSentimentResponse( - language="language_value", - ) - response = client.analyze_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" - - -def test_analyze_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - client.analyze_sentiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() - - -@pytest.mark.asyncio -async def test_analyze_sentiment_async( - transport: str = "grpc_asyncio", - request_type=language_service.AnalyzeSentimentRequest, -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSentimentResponse( - language="language_value", - ) - ) - response = await client.analyze_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_sentiment_async_from_dict(): - await test_analyze_sentiment_async(request_type=dict) - - -def test_analyze_sentiment_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSentimentResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_sentiment_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_sentiment( - language_service.AnalyzeSentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_sentiment_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSentimentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSentimentResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_sentiment( - language_service.AnalyzeSentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitiesRequest, - dict, - ], -) -def test_analyze_entities(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitiesResponse( - language="language_value", - ) - response = client.analyze_entities(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" - - -def test_analyze_entities_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - client.analyze_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() - - -@pytest.mark.asyncio -async def test_analyze_entities_async( - transport: str = "grpc_asyncio", - request_type=language_service.AnalyzeEntitiesRequest, -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitiesResponse( - language="language_value", - ) - ) - response = await client.analyze_entities(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitiesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_entities_async_from_dict(): - await test_analyze_entities_async(request_type=dict) - - -def test_analyze_entities_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitiesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_entities( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_entities_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entities( - language_service.AnalyzeEntitiesRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_entities_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_entities), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitiesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitiesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_entities( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_entities_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_entities( - language_service.AnalyzeEntitiesRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitySentimentRequest, - dict, - ], -) -def test_analyze_entity_sentiment(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitySentimentResponse( - language="language_value", - ) - response = client.analyze_entity_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" - - -def test_analyze_entity_sentiment_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - client.analyze_entity_sentiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_async( - transport: str = "grpc_asyncio", - request_type=language_service.AnalyzeEntitySentimentRequest, -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitySentimentResponse( - language="language_value", - ) - ) - response = await client.analyze_entity_sentiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeEntitySentimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_async_from_dict(): - await test_analyze_entity_sentiment_async(request_type=dict) - - -def test_analyze_entity_sentiment_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitySentimentResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_entity_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_entity_sentiment_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entity_sentiment( - language_service.AnalyzeEntitySentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_entity_sentiment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeEntitySentimentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeEntitySentimentResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_entity_sentiment( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_entity_sentiment_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_entity_sentiment( - language_service.AnalyzeEntitySentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSyntaxRequest, - dict, - ], -) -def test_analyze_syntax(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSyntaxResponse( - language="language_value", - ) - response = client.analyze_syntax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" - - -def test_analyze_syntax_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - client.analyze_syntax() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() - - -@pytest.mark.asyncio -async def test_analyze_syntax_async( - transport: str = "grpc_asyncio", request_type=language_service.AnalyzeSyntaxRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSyntaxResponse( - language="language_value", - ) - ) - response = await client.analyze_syntax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnalyzeSyntaxRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_analyze_syntax_async_from_dict(): - await test_analyze_syntax_async(request_type=dict) - - -def test_analyze_syntax_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSyntaxResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_syntax( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_analyze_syntax_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_syntax( - language_service.AnalyzeSyntaxRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_analyze_syntax_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.analyze_syntax), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnalyzeSyntaxResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnalyzeSyntaxResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_syntax( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_analyze_syntax_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.analyze_syntax( - language_service.AnalyzeSyntaxRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ClassifyTextRequest, - dict, - ], -) -def test_classify_text(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ClassifyTextResponse() - response = client.classify_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) - - -def test_classify_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - client.classify_text() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() - - -@pytest.mark.asyncio -async def test_classify_text_async( - transport: str = "grpc_asyncio", request_type=language_service.ClassifyTextRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ClassifyTextResponse() - ) - response = await client.classify_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ClassifyTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) - - -@pytest.mark.asyncio -async def test_classify_text_async_from_dict(): - await test_classify_text_async(request_type=dict) - - -def test_classify_text_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ClassifyTextResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.classify_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -def test_classify_text_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.classify_text( - language_service.ClassifyTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.asyncio -async def test_classify_text_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.classify_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ClassifyTextResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ClassifyTextResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.classify_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_classify_text_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.classify_text( - language_service.ClassifyTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ModerateTextRequest, - dict, - ], -) -def test_moderate_text(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ModerateTextResponse() - response = client.moderate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ModerateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ModerateTextResponse) - - -def test_moderate_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - client.moderate_text() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ModerateTextRequest() - - -@pytest.mark.asyncio -async def test_moderate_text_async( - transport: str = "grpc_asyncio", request_type=language_service.ModerateTextRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ModerateTextResponse() - ) - response = await client.moderate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.ModerateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ModerateTextResponse) - - -@pytest.mark.asyncio -async def test_moderate_text_async_from_dict(): - await test_moderate_text_async(request_type=dict) - - -def test_moderate_text_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ModerateTextResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.moderate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -def test_moderate_text_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.moderate_text( - language_service.ModerateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.asyncio -async def test_moderate_text_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.moderate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.ModerateTextResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.ModerateTextResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.moderate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_moderate_text_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.moderate_text( - language_service.ModerateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnnotateTextRequest, - dict, - ], -) -def test_annotate_text(request_type, transport: str = "grpc"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnnotateTextResponse( - language="language_value", - ) - response = client.annotate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" - - -def test_annotate_text_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 = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - client.annotate_text() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() - - -@pytest.mark.asyncio -async def test_annotate_text_async( - transport: str = "grpc_asyncio", request_type=language_service.AnnotateTextRequest -): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnnotateTextResponse( - language="language_value", - ) - ) - response = await client.annotate_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == language_service.AnnotateTextRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" - - -@pytest.mark.asyncio -async def test_annotate_text_async_from_dict(): - await test_annotate_text_async(request_type=dict) - - -def test_annotate_text_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnnotateTextResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.annotate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].features - mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -def test_annotate_text_flattened_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_text( - language_service.AnnotateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.asyncio -async def test_annotate_text_flattened_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.annotate_text), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = language_service.AnnotateTextResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - language_service.AnnotateTextResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.annotate_text( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].document - mock_val = language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ) - assert arg == mock_val - arg = args[0].features - mock_val = language_service.AnnotateTextRequest.Features(extract_syntax=True) - assert arg == mock_val - arg = args[0].encoding_type - mock_val = language_service.EncodingType.UTF8 - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_annotate_text_flattened_error_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.annotate_text( - language_service.AnnotateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSentimentRequest, - dict, - ], -) -def test_analyze_sentiment_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSentimentResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_sentiment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSentimentResponse) - assert response.language == "language_value" - - -def test_analyze_sentiment_rest_required_fields( - request_type=language_service.AnalyzeSentimentRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSentimentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_sentiment(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_sentiment_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_sentiment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_sentiment_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_sentiment" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_sentiment" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeSentimentRequest.pb( - language_service.AnalyzeSentimentRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnalyzeSentimentResponse.to_json( - language_service.AnalyzeSentimentResponse() - ) - - request = language_service.AnalyzeSentimentRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeSentimentResponse() - - client.analyze_sentiment( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_sentiment_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeSentimentRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_sentiment(request) - - -def test_analyze_sentiment_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSentimentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSentimentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_sentiment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta2/documents:analyzeSentiment" % client.transport._host, args[1] - ) - - -def test_analyze_sentiment_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_sentiment( - language_service.AnalyzeSentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_sentiment_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitiesRequest, - dict, - ], -) -def test_analyze_entities_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitiesResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_entities(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitiesResponse) - assert response.language == "language_value" - - -def test_analyze_entities_rest_required_fields( - request_type=language_service.AnalyzeEntitiesRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitiesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_entities(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_entities_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_entities_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_entities" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_entities" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeEntitiesRequest.pb( - language_service.AnalyzeEntitiesRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnalyzeEntitiesResponse.to_json( - language_service.AnalyzeEntitiesResponse() - ) - - request = language_service.AnalyzeEntitiesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeEntitiesResponse() - - client.analyze_entities( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_entities_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeEntitiesRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_entities(request) - - -def test_analyze_entities_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitiesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta2/documents:analyzeEntities" % client.transport._host, args[1] - ) - - -def test_analyze_entities_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entities( - language_service.AnalyzeEntitiesRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_entities_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeEntitySentimentRequest, - dict, - ], -) -def test_analyze_entity_sentiment_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitySentimentResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_entity_sentiment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeEntitySentimentResponse) - assert response.language == "language_value" - - -def test_analyze_entity_sentiment_rest_required_fields( - request_type=language_service.AnalyzeEntitySentimentRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_entity_sentiment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitySentimentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_entity_sentiment(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_entity_sentiment_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_entity_sentiment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_entity_sentiment_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_entity_sentiment" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_entity_sentiment" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeEntitySentimentRequest.pb( - language_service.AnalyzeEntitySentimentRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - language_service.AnalyzeEntitySentimentResponse.to_json( - language_service.AnalyzeEntitySentimentResponse() - ) - ) - - request = language_service.AnalyzeEntitySentimentRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeEntitySentimentResponse() - - client.analyze_entity_sentiment( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_entity_sentiment_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeEntitySentimentRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_entity_sentiment(request) - - -def test_analyze_entity_sentiment_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeEntitySentimentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeEntitySentimentResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_entity_sentiment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta2/documents:analyzeEntitySentiment" % client.transport._host, - args[1], - ) - - -def test_analyze_entity_sentiment_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_entity_sentiment( - language_service.AnalyzeEntitySentimentRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_entity_sentiment_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnalyzeSyntaxRequest, - dict, - ], -) -def test_analyze_syntax_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSyntaxResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.analyze_syntax(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnalyzeSyntaxResponse) - assert response.language == "language_value" - - -def test_analyze_syntax_rest_required_fields( - request_type=language_service.AnalyzeSyntaxRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_syntax._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).analyze_syntax._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSyntaxResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.analyze_syntax(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_analyze_syntax_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.analyze_syntax._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_syntax_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_analyze_syntax" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_analyze_syntax" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnalyzeSyntaxRequest.pb( - language_service.AnalyzeSyntaxRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnalyzeSyntaxResponse.to_json( - language_service.AnalyzeSyntaxResponse() - ) - - request = language_service.AnalyzeSyntaxRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnalyzeSyntaxResponse() - - client.analyze_syntax( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_syntax_rest_bad_request( - transport: str = "rest", request_type=language_service.AnalyzeSyntaxRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_syntax(request) - - -def test_analyze_syntax_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnalyzeSyntaxResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnalyzeSyntaxResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.analyze_syntax(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta2/documents:analyzeSyntax" % client.transport._host, args[1] - ) - - -def test_analyze_syntax_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_syntax( - language_service.AnalyzeSyntaxRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_analyze_syntax_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ClassifyTextRequest, - dict, - ], -) -def test_classify_text_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ClassifyTextResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ClassifyTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.classify_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ClassifyTextResponse) - - -def test_classify_text_rest_required_fields( - request_type=language_service.ClassifyTextRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).classify_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).classify_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.ClassifyTextResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.ClassifyTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.classify_text(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_classify_text_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.classify_text._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_classify_text_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_classify_text" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_classify_text" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.ClassifyTextRequest.pb( - language_service.ClassifyTextRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.ClassifyTextResponse.to_json( - language_service.ClassifyTextResponse() - ) - - request = language_service.ClassifyTextRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.ClassifyTextResponse() - - client.classify_text( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_classify_text_rest_bad_request( - transport: str = "rest", request_type=language_service.ClassifyTextRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.classify_text(request) - - -def test_classify_text_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ClassifyTextResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ClassifyTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.classify_text(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta2/documents:classifyText" % client.transport._host, args[1] - ) - - -def test_classify_text_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.classify_text( - language_service.ClassifyTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -def test_classify_text_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.ModerateTextRequest, - dict, - ], -) -def test_moderate_text_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ModerateTextResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ModerateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.moderate_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.ModerateTextResponse) - - -def test_moderate_text_rest_required_fields( - request_type=language_service.ModerateTextRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).moderate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).moderate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.ModerateTextResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.ModerateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.moderate_text(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_moderate_text_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.moderate_text._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("document",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_moderate_text_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_moderate_text" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_moderate_text" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.ModerateTextRequest.pb( - language_service.ModerateTextRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.ModerateTextResponse.to_json( - language_service.ModerateTextResponse() - ) - - request = language_service.ModerateTextRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.ModerateTextResponse() - - client.moderate_text( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_moderate_text_rest_bad_request( - transport: str = "rest", request_type=language_service.ModerateTextRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.moderate_text(request) - - -def test_moderate_text_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.ModerateTextResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.ModerateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.moderate_text(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta2/documents:moderateText" % client.transport._host, args[1] - ) - - -def test_moderate_text_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.moderate_text( - language_service.ModerateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - ) - - -def test_moderate_text_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - language_service.AnnotateTextRequest, - dict, - ], -) -def test_annotate_text_rest(request_type): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnnotateTextResponse( - language="language_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnnotateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.annotate_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, language_service.AnnotateTextResponse) - assert response.language == "language_value" - - -def test_annotate_text_rest_required_fields( - request_type=language_service.AnnotateTextRequest, -): - transport_class = transports.LanguageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).annotate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).annotate_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = language_service.AnnotateTextResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = language_service.AnnotateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.annotate_text(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_annotate_text_rest_unset_required_fields(): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.annotate_text._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "document", - "features", - ) - ) - ) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_annotate_text_rest_interceptors(null_interceptor): - transport = transports.LanguageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LanguageServiceRestInterceptor(), - ) - client = LanguageServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.LanguageServiceRestInterceptor, "post_annotate_text" - ) as post, mock.patch.object( - transports.LanguageServiceRestInterceptor, "pre_annotate_text" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = language_service.AnnotateTextRequest.pb( - language_service.AnnotateTextRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = language_service.AnnotateTextResponse.to_json( - language_service.AnnotateTextResponse() - ) - - request = language_service.AnnotateTextRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = language_service.AnnotateTextResponse() - - client.annotate_text( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_annotate_text_rest_bad_request( - transport: str = "rest", request_type=language_service.AnnotateTextRequest -): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.annotate_text(request) - - -def test_annotate_text_rest_flattened(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = language_service.AnnotateTextResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = language_service.AnnotateTextResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.annotate_text(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta2/documents:annotateText" % client.transport._host, args[1] - ) - - -def test_annotate_text_rest_flattened_error(transport: str = "rest"): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_text( - language_service.AnnotateTextRequest(), - document=language_service.Document( - type_=language_service.Document.Type.PLAIN_TEXT - ), - features=language_service.AnnotateTextRequest.Features(extract_syntax=True), - encoding_type=language_service.EncodingType.UTF8, - ) - - -def test_annotate_text_rest_error(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LanguageServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LanguageServiceClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LanguageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LanguageServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - transports.LanguageServiceRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = LanguageServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LanguageServiceGrpcTransport, - ) - - -def test_language_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) - - -def test_language_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.language_v1beta2.services.language_service.transports.LanguageServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.LanguageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "analyze_sentiment", - "analyze_entities", - "analyze_entity_sentiment", - "analyze_syntax", - "classify_text", - "moderate_text", - "annotate_text", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_language_service_base_transport_with_credentials_file(): - # 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.language_v1beta2.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport( - 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-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - -def test_language_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.language_v1beta2.services.language_service.transports.LanguageServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LanguageServiceTransport() - adc.assert_called_once() - - -def test_language_service_auth_adc(): - # 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) - LanguageServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_transport_auth_adc(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", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - transports.LanguageServiceRestTransport, - ], -) -def test_language_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LanguageServiceGrpcTransport, grpc_helpers), - (transports.LanguageServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_language_service_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( - "language.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - "https://www.googleapis.com/auth/cloud-language", - "https://www.googleapis.com/auth/cloud-platform", - ), - scopes=["1", "2"], - default_host="language.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) - - -def test_language_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ) as mock_configure_mtls_channel: - transports.LanguageServiceRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_language_service_host_no_port(transport_name): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="language.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "language.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com" - ) - - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_language_service_host_with_port(transport_name): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="language.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "language.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://language.googleapis.com:8000" - ) - - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_language_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LanguageServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LanguageServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.analyze_sentiment._session - session2 = client2.transport.analyze_sentiment._session - assert session1 != session2 - session1 = client1.transport.analyze_entities._session - session2 = client2.transport.analyze_entities._session - assert session1 != session2 - session1 = client1.transport.analyze_entity_sentiment._session - session2 = client2.transport.analyze_entity_sentiment._session - assert session1 != session2 - session1 = client1.transport.analyze_syntax._session - session2 = client2.transport.analyze_syntax._session - assert session1 != session2 - session1 = client1.transport.classify_text._session - session2 = client2.transport.classify_text._session - assert session1 != session2 - session1 = client1.transport.moderate_text._session - session2 = client2.transport.moderate_text._session - assert session1 != session2 - session1 = client1.transport.annotate_text._session - session2 = client2.transport.annotate_text._session - assert session1 != session2 - - -def test_language_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LanguageServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_language_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LanguageServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.LanguageServiceGrpcTransport, - transports.LanguageServiceGrpcAsyncIOTransport, - ], -) -def test_language_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = LanguageServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = LanguageServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = LanguageServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = LanguageServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = LanguageServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = LanguageServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) - actual = LanguageServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = LanguageServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = LanguageServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = LanguageServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LanguageServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.LanguageServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.LanguageServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = LanguageServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = LanguageServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - "rest", - "grpc", - ] - for transport in transports: - client = LanguageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (LanguageServiceClient, transports.LanguageServiceGrpcTransport), - (LanguageServiceAsyncClient, transports.LanguageServiceGrpcAsyncIOTransport), - ], -) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - )