From 07227a06b555d590fc35055ec229f22c6d8dd139 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 14 Dec 2022 13:49:52 -0500 Subject: [PATCH] docs: fix minor docstring formatting (#349) 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 * feat: add LRS API PiperOrigin-RevId: 493338018 Source-Link: https://github.com/googleapis/googleapis/commit/380b2f0721b0b0bd014f72eb9c0aad98bd39595c Source-Link: https://github.com/googleapis/googleapis-gen/commit/5802e4bd244f11abf88c8ee3968dc1d7281c496a Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTgwMmU0YmQyNDRmMTFhYmY4OGM4ZWUzOTY4ZGMxZDcyODFjNDk2YSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * feat: add LRS API PiperOrigin-RevId: 493606501 Source-Link: https://github.com/googleapis/googleapis/commit/a1b5429eec257c4f3a8425b20d4689d1df5812bc Source-Link: https://github.com/googleapis/googleapis-gen/commit/ea4e7802b7da7db3a2f422a5dbf4e3f4f8c6067d Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiZWE0ZTc4MDJiN2RhN2RiM2EyZjQyMmE1ZGJmNGUzZjRmOGM2MDY3ZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * docs: fix minor docstring formatting PiperOrigin-RevId: 495308712 Source-Link: https://github.com/googleapis/googleapis/commit/45c90e286e35a5210b6363c11f0ae60816d0ece8 Source-Link: https://github.com/googleapis/googleapis-gen/commit/61828bbdcf00aeabfed3f55ed0f9cb5252ef9d46 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjE4MjhiYmRjZjAwYWVhYmZlZDNmNTVlZDBmOWNiNTI1MmVmOWQ0NiJ9 * 🦉 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 Co-authored-by: Anthonios Partheniou --- .coveragerc | 5 - docs/texttospeech_v1/services.rst | 1 + .../text_to_speech_long_audio_synthesize.rst | 6 + docs/texttospeech_v1beta1/services.rst | 1 + .../text_to_speech_long_audio_synthesize.rst | 6 + google/cloud/texttospeech/__init__.py | 16 + google/cloud/texttospeech_v1/__init__.py | 14 + .../cloud/texttospeech_v1/gapic_metadata.json | 24 + google/cloud/texttospeech_v1/gapic_version.py | 16 + .../services/text_to_speech/async_client.py | 20 +- .../services/text_to_speech/client.py | 20 +- .../text_to_speech/transports/base.py | 14 +- .../text_to_speech/transports/grpc.py | 1 + .../text_to_speech/transports/grpc_asyncio.py | 1 + .../__init__.py | 22 + .../async_client.py | 349 ++++ .../client.py | 579 ++++++ .../transports/__init__.py | 36 + .../transports/base.py | 161 ++ .../transports/grpc.py | 283 +++ .../transports/grpc_asyncio.py | 286 +++ .../cloud/texttospeech_v1/types/__init__.py | 8 + .../cloud/texttospeech_v1/types/cloud_tts.py | 12 +- .../texttospeech_v1/types/cloud_tts_lrs.py | 118 ++ google/cloud/texttospeech_v1beta1/__init__.py | 14 + .../texttospeech_v1beta1/gapic_metadata.json | 24 + .../texttospeech_v1beta1/gapic_version.py | 16 + .../services/text_to_speech/async_client.py | 20 +- .../services/text_to_speech/client.py | 20 +- .../text_to_speech/transports/base.py | 14 +- .../text_to_speech/transports/grpc.py | 1 + .../text_to_speech/transports/grpc_asyncio.py | 1 + .../__init__.py | 22 + .../async_client.py | 349 ++++ .../client.py | 579 ++++++ .../transports/__init__.py | 36 + .../transports/base.py | 161 ++ .../transports/grpc.py | 283 +++ .../transports/grpc_asyncio.py | 286 +++ .../texttospeech_v1beta1/types/__init__.py | 8 + .../texttospeech_v1beta1/types/cloud_tts.py | 12 +- .../types/cloud_tts_lrs.py | 118 ++ release-please-config.json | 2 + ...metadata_google.cloud.texttospeech.v1.json | 153 ++ ...ata_google.cloud.texttospeech.v1beta1.json | 153 ++ ..._synthesize_synthesize_long_audio_async.py | 63 + ...o_synthesize_synthesize_long_audio_sync.py | 63 + ..._synthesize_synthesize_long_audio_async.py | 63 + ...o_synthesize_synthesize_long_audio_sync.py | 63 + scripts/fixup_texttospeech_v1_keywords.py | 1 + .../fixup_texttospeech_v1beta1_keywords.py | 1 + setup.py | 2 +- testing/constraints-3.7.txt | 2 +- .../texttospeech_v1/test_text_to_speech.py | 1 + ...st_text_to_speech_long_audio_synthesize.py | 1662 +++++++++++++++++ .../test_text_to_speech.py | 1 + ...st_text_to_speech_long_audio_synthesize.py | 1662 +++++++++++++++++ 57 files changed, 7776 insertions(+), 79 deletions(-) create mode 100644 docs/texttospeech_v1/text_to_speech_long_audio_synthesize.rst create mode 100644 docs/texttospeech_v1beta1/text_to_speech_long_audio_synthesize.rst create mode 100644 google/cloud/texttospeech_v1/gapic_version.py create mode 100644 google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/__init__.py create mode 100644 google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/async_client.py create mode 100644 google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/client.py create mode 100644 google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/__init__.py create mode 100644 google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/base.py create mode 100644 google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc.py create mode 100644 google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py create mode 100644 google/cloud/texttospeech_v1/types/cloud_tts_lrs.py create mode 100644 google/cloud/texttospeech_v1beta1/gapic_version.py create mode 100644 google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/__init__.py create mode 100644 google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/async_client.py create mode 100644 google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/client.py create mode 100644 google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/__init__.py create mode 100644 google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/base.py create mode 100644 google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc.py create mode 100644 google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py create mode 100644 google/cloud/texttospeech_v1beta1/types/cloud_tts_lrs.py create mode 100644 samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py create mode 100644 samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py create mode 100644 samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py create mode 100644 samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py create mode 100644 tests/unit/gapic/texttospeech_v1/test_text_to_speech_long_audio_synthesize.py create mode 100644 tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech_long_audio_synthesize.py diff --git a/.coveragerc b/.coveragerc index 3d145aee..c5ff5cae 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/docs/texttospeech_v1/services.rst b/docs/texttospeech_v1/services.rst index a77f8167..71958842 100644 --- a/docs/texttospeech_v1/services.rst +++ b/docs/texttospeech_v1/services.rst @@ -4,3 +4,4 @@ Services for Google Cloud Texttospeech v1 API :maxdepth: 2 text_to_speech + text_to_speech_long_audio_synthesize diff --git a/docs/texttospeech_v1/text_to_speech_long_audio_synthesize.rst b/docs/texttospeech_v1/text_to_speech_long_audio_synthesize.rst new file mode 100644 index 00000000..2a202504 --- /dev/null +++ b/docs/texttospeech_v1/text_to_speech_long_audio_synthesize.rst @@ -0,0 +1,6 @@ +TextToSpeechLongAudioSynthesize +------------------------------------------------- + +.. automodule:: google.cloud.texttospeech_v1.services.text_to_speech_long_audio_synthesize + :members: + :inherited-members: diff --git a/docs/texttospeech_v1beta1/services.rst b/docs/texttospeech_v1beta1/services.rst index 67852d05..338598a6 100644 --- a/docs/texttospeech_v1beta1/services.rst +++ b/docs/texttospeech_v1beta1/services.rst @@ -4,3 +4,4 @@ Services for Google Cloud Texttospeech v1beta1 API :maxdepth: 2 text_to_speech + text_to_speech_long_audio_synthesize diff --git a/docs/texttospeech_v1beta1/text_to_speech_long_audio_synthesize.rst b/docs/texttospeech_v1beta1/text_to_speech_long_audio_synthesize.rst new file mode 100644 index 00000000..50ef34c6 --- /dev/null +++ b/docs/texttospeech_v1beta1/text_to_speech_long_audio_synthesize.rst @@ -0,0 +1,6 @@ +TextToSpeechLongAudioSynthesize +------------------------------------------------- + +.. automodule:: google.cloud.texttospeech_v1beta1.services.text_to_speech_long_audio_synthesize + :members: + :inherited-members: diff --git a/google/cloud/texttospeech/__init__.py b/google/cloud/texttospeech/__init__.py index ea6e9364..7f540adf 100644 --- a/google/cloud/texttospeech/__init__.py +++ b/google/cloud/texttospeech/__init__.py @@ -24,6 +24,12 @@ from google.cloud.texttospeech_v1.services.text_to_speech.client import ( TextToSpeechClient, ) +from google.cloud.texttospeech_v1.services.text_to_speech_long_audio_synthesize.async_client import ( + TextToSpeechLongAudioSynthesizeAsyncClient, +) +from google.cloud.texttospeech_v1.services.text_to_speech_long_audio_synthesize.client import ( + TextToSpeechLongAudioSynthesizeClient, +) from google.cloud.texttospeech_v1.types.cloud_tts import ( AudioConfig, AudioEncoding, @@ -37,10 +43,17 @@ Voice, VoiceSelectionParams, ) +from google.cloud.texttospeech_v1.types.cloud_tts_lrs import ( + SynthesizeLongAudioMetadata, + SynthesizeLongAudioRequest, + SynthesizeLongAudioResponse, +) __all__ = ( "TextToSpeechClient", "TextToSpeechAsyncClient", + "TextToSpeechLongAudioSynthesizeClient", + "TextToSpeechLongAudioSynthesizeAsyncClient", "AudioConfig", "CustomVoiceParams", "ListVoicesRequest", @@ -52,4 +65,7 @@ "VoiceSelectionParams", "AudioEncoding", "SsmlVoiceGender", + "SynthesizeLongAudioMetadata", + "SynthesizeLongAudioRequest", + "SynthesizeLongAudioResponse", ) diff --git a/google/cloud/texttospeech_v1/__init__.py b/google/cloud/texttospeech_v1/__init__.py index 5507eda3..84c5d12a 100644 --- a/google/cloud/texttospeech_v1/__init__.py +++ b/google/cloud/texttospeech_v1/__init__.py @@ -19,6 +19,10 @@ from .services.text_to_speech import TextToSpeechAsyncClient, TextToSpeechClient +from .services.text_to_speech_long_audio_synthesize import ( + TextToSpeechLongAudioSynthesizeAsyncClient, + TextToSpeechLongAudioSynthesizeClient, +) from .types.cloud_tts import ( AudioConfig, AudioEncoding, @@ -32,9 +36,15 @@ Voice, VoiceSelectionParams, ) +from .types.cloud_tts_lrs import ( + SynthesizeLongAudioMetadata, + SynthesizeLongAudioRequest, + SynthesizeLongAudioResponse, +) __all__ = ( "TextToSpeechAsyncClient", + "TextToSpeechLongAudioSynthesizeAsyncClient", "AudioConfig", "AudioEncoding", "CustomVoiceParams", @@ -42,9 +52,13 @@ "ListVoicesResponse", "SsmlVoiceGender", "SynthesisInput", + "SynthesizeLongAudioMetadata", + "SynthesizeLongAudioRequest", + "SynthesizeLongAudioResponse", "SynthesizeSpeechRequest", "SynthesizeSpeechResponse", "TextToSpeechClient", + "TextToSpeechLongAudioSynthesizeClient", "Voice", "VoiceSelectionParams", ) diff --git a/google/cloud/texttospeech_v1/gapic_metadata.json b/google/cloud/texttospeech_v1/gapic_metadata.json index f9c0c9bd..2d0867a0 100644 --- a/google/cloud/texttospeech_v1/gapic_metadata.json +++ b/google/cloud/texttospeech_v1/gapic_metadata.json @@ -38,6 +38,30 @@ } } } + }, + "TextToSpeechLongAudioSynthesize": { + "clients": { + "grpc": { + "libraryClient": "TextToSpeechLongAudioSynthesizeClient", + "rpcs": { + "SynthesizeLongAudio": { + "methods": [ + "synthesize_long_audio" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TextToSpeechLongAudioSynthesizeAsyncClient", + "rpcs": { + "SynthesizeLongAudio": { + "methods": [ + "synthesize_long_audio" + ] + } + } + } + } } } } diff --git a/google/cloud/texttospeech_v1/gapic_version.py b/google/cloud/texttospeech_v1/gapic_version.py new file mode 100644 index 00000000..e0546e8c --- /dev/null +++ b/google/cloud/texttospeech_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.12.3" # {x-release-please-version} diff --git a/google/cloud/texttospeech_v1/services/text_to_speech/async_client.py b/google/cloud/texttospeech_v1/services/text_to_speech/async_client.py index db5f0a80..3dfd19c4 100644 --- a/google/cloud/texttospeech_v1/services/text_to_speech/async_client.py +++ b/google/cloud/texttospeech_v1/services/text_to_speech/async_client.py @@ -34,13 +34,16 @@ 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.texttospeech_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.longrunning import operations_pb2 + from google.cloud.texttospeech_v1.types import cloud_tts from .client import TextToSpeechClient @@ -214,7 +217,7 @@ async def list_voices( *, language_code: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.ListVoicesResponse: r"""Returns a list of Voice supported for synthesis. @@ -318,7 +321,7 @@ async def synthesize_speech( voice: Optional[cloud_tts.VoiceSelectionParams] = None, audio_config: Optional[cloud_tts.AudioConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.SynthesizeSpeechResponse: r"""Synthesizes speech synchronously: receive results @@ -445,14 +448,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-texttospeech", - ).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__ = ("TextToSpeechAsyncClient",) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech/client.py b/google/cloud/texttospeech_v1/services/text_to_speech/client.py index 673140d8..dd21df3b 100644 --- a/google/cloud/texttospeech_v1/services/text_to_speech/client.py +++ b/google/cloud/texttospeech_v1/services/text_to_speech/client.py @@ -38,13 +38,16 @@ 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.texttospeech_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.longrunning import operations_pb2 + from google.cloud.texttospeech_v1.types import cloud_tts from .transports.base import DEFAULT_CLIENT_INFO, TextToSpeechTransport @@ -443,7 +446,7 @@ def list_voices( *, language_code: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.ListVoicesResponse: r"""Returns a list of Voice supported for synthesis. @@ -547,7 +550,7 @@ def synthesize_speech( voice: Optional[cloud_tts.VoiceSelectionParams] = None, audio_config: Optional[cloud_tts.AudioConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.SynthesizeSpeechResponse: r"""Synthesizes speech synchronously: receive results @@ -681,14 +684,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-texttospeech", - ).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__ = ("TextToSpeechClient",) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech/transports/base.py b/google/cloud/texttospeech_v1/services/text_to_speech/transports/base.py index 70c446b7..9589ad13 100644 --- a/google/cloud/texttospeech_v1/services/text_to_speech/transports/base.py +++ b/google/cloud/texttospeech_v1/services/text_to_speech/transports/base.py @@ -22,19 +22,15 @@ 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.longrunning import operations_pb2 from google.oauth2 import service_account # type: ignore -import pkg_resources +from google.cloud.texttospeech_v1 import gapic_version as package_version from google.cloud.texttospeech_v1.types import cloud_tts -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-texttospeech", - ).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 TextToSpeechTransport(abc.ABC): diff --git a/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc.py b/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc.py index 3d240bbd..a45dbe53 100644 --- a/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc.py +++ b/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc.py @@ -20,6 +20,7 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 import grpc # type: ignore from google.cloud.texttospeech_v1.types import cloud_tts diff --git a/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc_asyncio.py b/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc_asyncio.py index 54ff277d..77f2bed0 100644 --- a/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc_asyncio.py +++ b/google/cloud/texttospeech_v1/services/text_to_speech/transports/grpc_asyncio.py @@ -19,6 +19,7 @@ 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 +from google.longrunning import operations_pb2 import grpc # type: ignore from grpc.experimental import aio # type: ignore diff --git a/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/__init__.py b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/__init__.py new file mode 100644 index 00000000..8b596bd7 --- /dev/null +++ b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 TextToSpeechLongAudioSynthesizeAsyncClient +from .client import TextToSpeechLongAudioSynthesizeClient + +__all__ = ( + "TextToSpeechLongAudioSynthesizeClient", + "TextToSpeechLongAudioSynthesizeAsyncClient", +) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/async_client.py b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/async_client.py new file mode 100644 index 00000000..32cc183c --- /dev/null +++ b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/async_client.py @@ -0,0 +1,349 @@ +# -*- 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.texttospeech_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 + +from google.cloud.texttospeech_v1.types import cloud_tts_lrs + +from .client import TextToSpeechLongAudioSynthesizeClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + TextToSpeechLongAudioSynthesizeTransport, +) +from .transports.grpc_asyncio import TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + + +class TextToSpeechLongAudioSynthesizeAsyncClient: + """Service that implements Google Cloud Text-to-Speech API.""" + + _client: TextToSpeechLongAudioSynthesizeClient + + DEFAULT_ENDPOINT = TextToSpeechLongAudioSynthesizeClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TextToSpeechLongAudioSynthesizeClient.DEFAULT_MTLS_ENDPOINT + + model_path = staticmethod(TextToSpeechLongAudioSynthesizeClient.model_path) + parse_model_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_model_path + ) + common_billing_account_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_organization_path + ) + common_project_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_project_path + ) + parse_common_project_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_project_path + ) + common_location_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_location_path + ) + parse_common_location_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.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: + TextToSpeechLongAudioSynthesizeAsyncClient: The constructed client. + """ + return TextToSpeechLongAudioSynthesizeClient.from_service_account_info.__func__(TextToSpeechLongAudioSynthesizeAsyncClient, 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: + TextToSpeechLongAudioSynthesizeAsyncClient: The constructed client. + """ + return TextToSpeechLongAudioSynthesizeClient.from_service_account_file.__func__(TextToSpeechLongAudioSynthesizeAsyncClient, 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 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 TextToSpeechLongAudioSynthesizeClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TextToSpeechLongAudioSynthesizeTransport: + """Returns the transport used by the client instance. + + Returns: + TextToSpeechLongAudioSynthesizeTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(TextToSpeechLongAudioSynthesizeClient).get_transport_class, + type(TextToSpeechLongAudioSynthesizeClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[ + str, TextToSpeechLongAudioSynthesizeTransport + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the text to speech long audio synthesize 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, ~.TextToSpeechLongAudioSynthesizeTransport]): 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 = TextToSpeechLongAudioSynthesizeClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def synthesize_long_audio( + self, + request: Optional[Union[cloud_tts_lrs.SynthesizeLongAudioRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Synthesizes long form text asynchronously. + + .. 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 texttospeech_v1 + + async def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1.TextToSpeechLongAudioSynthesizeAsyncClient() + + # Initialize request argument(s) + input = texttospeech_v1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.texttospeech_v1.types.SynthesizeLongAudioRequest, dict]]): + The request object. The top-level message sent by the + client for the `SynthesizeLongAudio` method. + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.texttospeech_v1.types.SynthesizeLongAudioResponse` + The message returned to the client by the + SynthesizeLongAudio method. + + """ + # Create or coerce a protobuf request object. + request = cloud_tts_lrs.SynthesizeLongAudioRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.synthesize_long_audio, + default_timeout=5000.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloud_tts_lrs.SynthesizeLongAudioResponse, + metadata_type=cloud_tts_lrs.SynthesizeLongAudioMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + 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__ = ("TextToSpeechLongAudioSynthesizeAsyncClient",) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/client.py b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/client.py new file mode 100644 index 00000000..46bab627 --- /dev/null +++ b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/client.py @@ -0,0 +1,579 @@ +# -*- 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.texttospeech_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 + +from google.cloud.texttospeech_v1.types import cloud_tts_lrs + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + TextToSpeechLongAudioSynthesizeTransport, +) +from .transports.grpc import TextToSpeechLongAudioSynthesizeGrpcTransport +from .transports.grpc_asyncio import TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + + +class TextToSpeechLongAudioSynthesizeClientMeta(type): + """Metaclass for the TextToSpeechLongAudioSynthesize 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[TextToSpeechLongAudioSynthesizeTransport]] + _transport_registry["grpc"] = TextToSpeechLongAudioSynthesizeGrpcTransport + _transport_registry[ + "grpc_asyncio" + ] = TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[TextToSpeechLongAudioSynthesizeTransport]: + """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 TextToSpeechLongAudioSynthesizeClient( + metaclass=TextToSpeechLongAudioSynthesizeClientMeta +): + """Service that implements Google Cloud Text-to-Speech API.""" + + @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[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "texttospeech.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: + TextToSpeechLongAudioSynthesizeClient: 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: + TextToSpeechLongAudioSynthesizeClient: 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) -> TextToSpeechLongAudioSynthesizeTransport: + """Returns the transport used by the client instance. + + Returns: + TextToSpeechLongAudioSynthesizeTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def model_path( + project: str, + location: str, + model: str, + ) -> str: + """Returns a fully-qualified model string.""" + return "projects/{project}/locations/{location}/models/{model}".format( + project=project, + location=location, + model=model, + ) + + @staticmethod + def parse_model_path(path: str) -> Dict[str, str]: + """Parses a model path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/models/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @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.+?)$", 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.+?)$", 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.+?)$", 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.+?)$", 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.+?)/locations/(?P.+?)$", 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, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, TextToSpeechLongAudioSynthesizeTransport] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the text to speech long audio synthesize 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, TextToSpeechLongAudioSynthesizeTransport]): 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, TextToSpeechLongAudioSynthesizeTransport): + # transport is a TextToSpeechLongAudioSynthesizeTransport 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 synthesize_long_audio( + self, + request: Optional[Union[cloud_tts_lrs.SynthesizeLongAudioRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Synthesizes long form text asynchronously. + + .. 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 texttospeech_v1 + + def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1.TextToSpeechLongAudioSynthesizeClient() + + # Initialize request argument(s) + input = texttospeech_v1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.texttospeech_v1.types.SynthesizeLongAudioRequest, dict]): + The request object. The top-level message sent by the + client for the `SynthesizeLongAudio` method. + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.texttospeech_v1.types.SynthesizeLongAudioResponse` + The message returned to the client by the + SynthesizeLongAudio method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a cloud_tts_lrs.SynthesizeLongAudioRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloud_tts_lrs.SynthesizeLongAudioRequest): + request = cloud_tts_lrs.SynthesizeLongAudioRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.synthesize_long_audio] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_tts_lrs.SynthesizeLongAudioResponse, + metadata_type=cloud_tts_lrs.SynthesizeLongAudioMetadata, + ) + + # 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() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("TextToSpeechLongAudioSynthesizeClient",) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/__init__.py b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/__init__.py new file mode 100644 index 00000000..be5d9e99 --- /dev/null +++ b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- 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 TextToSpeechLongAudioSynthesizeTransport +from .grpc import TextToSpeechLongAudioSynthesizeGrpcTransport +from .grpc_asyncio import TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[TextToSpeechLongAudioSynthesizeTransport]] +_transport_registry["grpc"] = TextToSpeechLongAudioSynthesizeGrpcTransport +_transport_registry[ + "grpc_asyncio" +] = TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + +__all__ = ( + "TextToSpeechLongAudioSynthesizeTransport", + "TextToSpeechLongAudioSynthesizeGrpcTransport", + "TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport", +) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/base.py b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/base.py new file mode 100644 index 00000000..9aae93d4 --- /dev/null +++ b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/base.py @@ -0,0 +1,161 @@ +# -*- 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, operations_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.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.texttospeech_v1 import gapic_version as package_version +from google.cloud.texttospeech_v1.types import cloud_tts_lrs + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class TextToSpeechLongAudioSynthesizeTransport(abc.ABC): + """Abstract transport class for TextToSpeechLongAudioSynthesize.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "texttospeech.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.synthesize_long_audio: gapic_v1.method.wrap_method( + self.synthesize_long_audio, + default_timeout=5000.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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def synthesize_long_audio( + self, + ) -> Callable[ + [cloud_tts_lrs.SynthesizeLongAudioRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("TextToSpeechLongAudioSynthesizeTransport",) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc.py b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc.py new file mode 100644 index 00000000..e109b9f5 --- /dev/null +++ b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc.py @@ -0,0 +1,283 @@ +# -*- 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, operations_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 +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.texttospeech_v1.types import cloud_tts_lrs + +from .base import DEFAULT_CLIENT_INFO, TextToSpeechLongAudioSynthesizeTransport + + +class TextToSpeechLongAudioSynthesizeGrpcTransport( + TextToSpeechLongAudioSynthesizeTransport +): + """gRPC backend transport for TextToSpeechLongAudioSynthesize. + + Service that implements Google Cloud Text-to-Speech API. + + 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 = "texttospeech.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + 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 = "texttospeech.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def synthesize_long_audio( + self, + ) -> Callable[[cloud_tts_lrs.SynthesizeLongAudioRequest], operations_pb2.Operation]: + r"""Return a callable for the synthesize long audio method over gRPC. + + Synthesizes long form text asynchronously. + + Returns: + Callable[[~.SynthesizeLongAudioRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "synthesize_long_audio" not in self._stubs: + self._stubs["synthesize_long_audio"] = self.grpc_channel.unary_unary( + "/google.cloud.texttospeech.v1.TextToSpeechLongAudioSynthesize/SynthesizeLongAudio", + request_serializer=cloud_tts_lrs.SynthesizeLongAudioRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["synthesize_long_audio"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("TextToSpeechLongAudioSynthesizeGrpcTransport",) diff --git a/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py new file mode 100644 index 00000000..d882d0e8 --- /dev/null +++ b/google/cloud/texttospeech_v1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py @@ -0,0 +1,286 @@ +# -*- 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, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.texttospeech_v1.types import cloud_tts_lrs + +from .base import DEFAULT_CLIENT_INFO, TextToSpeechLongAudioSynthesizeTransport +from .grpc import TextToSpeechLongAudioSynthesizeGrpcTransport + + +class TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport( + TextToSpeechLongAudioSynthesizeTransport +): + """gRPC AsyncIO backend transport for TextToSpeechLongAudioSynthesize. + + Service that implements Google Cloud Text-to-Speech API. + + 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 = "texttospeech.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 = "texttospeech.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def synthesize_long_audio( + self, + ) -> Callable[ + [cloud_tts_lrs.SynthesizeLongAudioRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the synthesize long audio method over gRPC. + + Synthesizes long form text asynchronously. + + Returns: + Callable[[~.SynthesizeLongAudioRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "synthesize_long_audio" not in self._stubs: + self._stubs["synthesize_long_audio"] = self.grpc_channel.unary_unary( + "/google.cloud.texttospeech.v1.TextToSpeechLongAudioSynthesize/SynthesizeLongAudio", + request_serializer=cloud_tts_lrs.SynthesizeLongAudioRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["synthesize_long_audio"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport",) diff --git a/google/cloud/texttospeech_v1/types/__init__.py b/google/cloud/texttospeech_v1/types/__init__.py index f7225093..a737cb37 100644 --- a/google/cloud/texttospeech_v1/types/__init__.py +++ b/google/cloud/texttospeech_v1/types/__init__.py @@ -26,6 +26,11 @@ Voice, VoiceSelectionParams, ) +from .cloud_tts_lrs import ( + SynthesizeLongAudioMetadata, + SynthesizeLongAudioRequest, + SynthesizeLongAudioResponse, +) __all__ = ( "AudioConfig", @@ -39,4 +44,7 @@ "VoiceSelectionParams", "AudioEncoding", "SsmlVoiceGender", + "SynthesizeLongAudioMetadata", + "SynthesizeLongAudioRequest", + "SynthesizeLongAudioResponse", ) diff --git a/google/cloud/texttospeech_v1/types/cloud_tts.py b/google/cloud/texttospeech_v1/types/cloud_tts.py index d4bef357..26268473 100644 --- a/google/cloud/texttospeech_v1/types/cloud_tts.py +++ b/google/cloud/texttospeech_v1/types/cloud_tts.py @@ -168,8 +168,8 @@ class SynthesizeSpeechRequest(proto.Message): class SynthesisInput(proto.Message): r"""Contains text input to be synthesized. Either ``text`` or ``ssml`` must be supplied. Supplying both or neither returns - [google.rpc.Code.INVALID_ARGUMENT][]. The input size is limited to - 5000 characters. + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + The input size is limited to 5000 bytes. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -186,8 +186,9 @@ class SynthesisInput(proto.Message): ssml (str): The SSML document to be synthesized. The SSML document must be valid and well-formed. Otherwise the RPC will fail and - return [google.rpc.Code.INVALID_ARGUMENT][]. For more - information, see + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + For more information, see `SSML `__. This field is a member of `oneof`_ ``input_source``. @@ -298,7 +299,8 @@ class AudioConfig(proto.Message): desired sample rate (which might result in worse audio quality), unless the specified sample rate is not supported for the encoding chosen, in which case it will fail the - request and return [google.rpc.Code.INVALID_ARGUMENT][]. + request and return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. effects_profile_id (MutableSequence[str]): Optional. Input only. An identifier which selects 'audio effects' profiles that are applied on (post synthesized) diff --git a/google/cloud/texttospeech_v1/types/cloud_tts_lrs.py b/google/cloud/texttospeech_v1/types/cloud_tts_lrs.py new file mode 100644 index 00000000..bdfc6471 --- /dev/null +++ b/google/cloud/texttospeech_v1/types/cloud_tts_lrs.py @@ -0,0 +1,118 @@ +# -*- 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 MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.texttospeech_v1.types import cloud_tts + +__protobuf__ = proto.module( + package="google.cloud.texttospeech.v1", + manifest={ + "SynthesizeLongAudioRequest", + "SynthesizeLongAudioResponse", + "SynthesizeLongAudioMetadata", + }, +) + + +class SynthesizeLongAudioRequest(proto.Message): + r"""The top-level message sent by the client for the + ``SynthesizeLongAudio`` method. + + Attributes: + parent (str): + The resource states of the request in the form of + ``projects/*/locations/*/voices/*``. + input (google.cloud.texttospeech_v1.types.SynthesisInput): + Required. The Synthesizer requires either + plain text or SSML as input. + audio_config (google.cloud.texttospeech_v1.types.AudioConfig): + Required. The configuration of the + synthesized audio. + output_gcs_uri (str): + Specifies a Cloud Storage URI for the synthesis results. + Must be specified in the format: + ``gs://bucket_name/object_name``, and the bucket must + already exist. + voice (google.cloud.texttospeech_v1.types.VoiceSelectionParams): + The desired voice of the synthesized audio. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + input: cloud_tts.SynthesisInput = proto.Field( + proto.MESSAGE, + number=2, + message=cloud_tts.SynthesisInput, + ) + audio_config: cloud_tts.AudioConfig = proto.Field( + proto.MESSAGE, + number=3, + message=cloud_tts.AudioConfig, + ) + output_gcs_uri: str = proto.Field( + proto.STRING, + number=4, + ) + voice: cloud_tts.VoiceSelectionParams = proto.Field( + proto.MESSAGE, + number=5, + message=cloud_tts.VoiceSelectionParams, + ) + + +class SynthesizeLongAudioResponse(proto.Message): + r"""The message returned to the client by the ``SynthesizeLongAudio`` + method. + + """ + + +class SynthesizeLongAudioMetadata(proto.Message): + r"""Metadata for response returned by the ``SynthesizeLongAudio`` + method. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent processing update. + progress_percentage (float): + The progress of the most recent processing + update in percentage, ie. 70.0%. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + progress_percentage: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/texttospeech_v1beta1/__init__.py b/google/cloud/texttospeech_v1beta1/__init__.py index 6447f1a0..8e8dcd13 100644 --- a/google/cloud/texttospeech_v1beta1/__init__.py +++ b/google/cloud/texttospeech_v1beta1/__init__.py @@ -19,6 +19,10 @@ from .services.text_to_speech import TextToSpeechAsyncClient, TextToSpeechClient +from .services.text_to_speech_long_audio_synthesize import ( + TextToSpeechLongAudioSynthesizeAsyncClient, + TextToSpeechLongAudioSynthesizeClient, +) from .types.cloud_tts import ( AudioConfig, AudioEncoding, @@ -33,9 +37,15 @@ Voice, VoiceSelectionParams, ) +from .types.cloud_tts_lrs import ( + SynthesizeLongAudioMetadata, + SynthesizeLongAudioRequest, + SynthesizeLongAudioResponse, +) __all__ = ( "TextToSpeechAsyncClient", + "TextToSpeechLongAudioSynthesizeAsyncClient", "AudioConfig", "AudioEncoding", "CustomVoiceParams", @@ -43,9 +53,13 @@ "ListVoicesResponse", "SsmlVoiceGender", "SynthesisInput", + "SynthesizeLongAudioMetadata", + "SynthesizeLongAudioRequest", + "SynthesizeLongAudioResponse", "SynthesizeSpeechRequest", "SynthesizeSpeechResponse", "TextToSpeechClient", + "TextToSpeechLongAudioSynthesizeClient", "Timepoint", "Voice", "VoiceSelectionParams", diff --git a/google/cloud/texttospeech_v1beta1/gapic_metadata.json b/google/cloud/texttospeech_v1beta1/gapic_metadata.json index 2a31677f..bf0ffd26 100644 --- a/google/cloud/texttospeech_v1beta1/gapic_metadata.json +++ b/google/cloud/texttospeech_v1beta1/gapic_metadata.json @@ -38,6 +38,30 @@ } } } + }, + "TextToSpeechLongAudioSynthesize": { + "clients": { + "grpc": { + "libraryClient": "TextToSpeechLongAudioSynthesizeClient", + "rpcs": { + "SynthesizeLongAudio": { + "methods": [ + "synthesize_long_audio" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TextToSpeechLongAudioSynthesizeAsyncClient", + "rpcs": { + "SynthesizeLongAudio": { + "methods": [ + "synthesize_long_audio" + ] + } + } + } + } } } } diff --git a/google/cloud/texttospeech_v1beta1/gapic_version.py b/google/cloud/texttospeech_v1beta1/gapic_version.py new file mode 100644 index 00000000..e0546e8c --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/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.12.3" # {x-release-please-version} diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech/async_client.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech/async_client.py index eaa05e1a..4a66daf5 100644 --- a/google/cloud/texttospeech_v1beta1/services/text_to_speech/async_client.py +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech/async_client.py @@ -34,13 +34,16 @@ 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.texttospeech_v1beta1 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.longrunning import operations_pb2 + from google.cloud.texttospeech_v1beta1.types import cloud_tts from .client import TextToSpeechClient @@ -214,7 +217,7 @@ async def list_voices( *, language_code: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.ListVoicesResponse: r"""Returns a list of Voice supported for synthesis. @@ -318,7 +321,7 @@ async def synthesize_speech( voice: Optional[cloud_tts.VoiceSelectionParams] = None, audio_config: Optional[cloud_tts.AudioConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.SynthesizeSpeechResponse: r"""Synthesizes speech synchronously: receive results @@ -445,14 +448,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-texttospeech", - ).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__ = ("TextToSpeechAsyncClient",) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech/client.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech/client.py index b4e0d902..d4fb882c 100644 --- a/google/cloud/texttospeech_v1beta1/services/text_to_speech/client.py +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech/client.py @@ -38,13 +38,16 @@ 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.texttospeech_v1beta1 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.longrunning import operations_pb2 + from google.cloud.texttospeech_v1beta1.types import cloud_tts from .transports.base import DEFAULT_CLIENT_INFO, TextToSpeechTransport @@ -443,7 +446,7 @@ def list_voices( *, language_code: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.ListVoicesResponse: r"""Returns a list of Voice supported for synthesis. @@ -547,7 +550,7 @@ def synthesize_speech( voice: Optional[cloud_tts.VoiceSelectionParams] = None, audio_config: Optional[cloud_tts.AudioConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> cloud_tts.SynthesizeSpeechResponse: r"""Synthesizes speech synchronously: receive results @@ -681,14 +684,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-texttospeech", - ).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__ = ("TextToSpeechClient",) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/base.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/base.py index d36ad9af..ae4827e1 100644 --- a/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/base.py +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/base.py @@ -22,19 +22,15 @@ 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.longrunning import operations_pb2 from google.oauth2 import service_account # type: ignore -import pkg_resources +from google.cloud.texttospeech_v1beta1 import gapic_version as package_version from google.cloud.texttospeech_v1beta1.types import cloud_tts -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-texttospeech", - ).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 TextToSpeechTransport(abc.ABC): diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc.py index 5f793aa4..f203ded3 100644 --- a/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc.py +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc.py @@ -20,6 +20,7 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 import grpc # type: ignore from google.cloud.texttospeech_v1beta1.types import cloud_tts diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc_asyncio.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc_asyncio.py index 37536b83..15c85392 100644 --- a/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc_asyncio.py +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech/transports/grpc_asyncio.py @@ -19,6 +19,7 @@ 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 +from google.longrunning import operations_pb2 import grpc # type: ignore from grpc.experimental import aio # type: ignore diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/__init__.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/__init__.py new file mode 100644 index 00000000..8b596bd7 --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 TextToSpeechLongAudioSynthesizeAsyncClient +from .client import TextToSpeechLongAudioSynthesizeClient + +__all__ = ( + "TextToSpeechLongAudioSynthesizeClient", + "TextToSpeechLongAudioSynthesizeAsyncClient", +) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/async_client.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/async_client.py new file mode 100644 index 00000000..312a2759 --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/async_client.py @@ -0,0 +1,349 @@ +# -*- 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.texttospeech_v1beta1 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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 + +from google.cloud.texttospeech_v1beta1.types import cloud_tts_lrs + +from .client import TextToSpeechLongAudioSynthesizeClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + TextToSpeechLongAudioSynthesizeTransport, +) +from .transports.grpc_asyncio import TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + + +class TextToSpeechLongAudioSynthesizeAsyncClient: + """Service that implements Google Cloud Text-to-Speech API.""" + + _client: TextToSpeechLongAudioSynthesizeClient + + DEFAULT_ENDPOINT = TextToSpeechLongAudioSynthesizeClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TextToSpeechLongAudioSynthesizeClient.DEFAULT_MTLS_ENDPOINT + + model_path = staticmethod(TextToSpeechLongAudioSynthesizeClient.model_path) + parse_model_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_model_path + ) + common_billing_account_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_organization_path + ) + common_project_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_project_path + ) + parse_common_project_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.parse_common_project_path + ) + common_location_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.common_location_path + ) + parse_common_location_path = staticmethod( + TextToSpeechLongAudioSynthesizeClient.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: + TextToSpeechLongAudioSynthesizeAsyncClient: The constructed client. + """ + return TextToSpeechLongAudioSynthesizeClient.from_service_account_info.__func__(TextToSpeechLongAudioSynthesizeAsyncClient, 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: + TextToSpeechLongAudioSynthesizeAsyncClient: The constructed client. + """ + return TextToSpeechLongAudioSynthesizeClient.from_service_account_file.__func__(TextToSpeechLongAudioSynthesizeAsyncClient, 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 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 TextToSpeechLongAudioSynthesizeClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TextToSpeechLongAudioSynthesizeTransport: + """Returns the transport used by the client instance. + + Returns: + TextToSpeechLongAudioSynthesizeTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(TextToSpeechLongAudioSynthesizeClient).get_transport_class, + type(TextToSpeechLongAudioSynthesizeClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[ + str, TextToSpeechLongAudioSynthesizeTransport + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the text to speech long audio synthesize 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, ~.TextToSpeechLongAudioSynthesizeTransport]): 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 = TextToSpeechLongAudioSynthesizeClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def synthesize_long_audio( + self, + request: Optional[Union[cloud_tts_lrs.SynthesizeLongAudioRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Synthesizes long form text asynchronously. + + .. 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 texttospeech_v1beta1 + + async def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeAsyncClient() + + # Initialize request argument(s) + input = texttospeech_v1beta1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1beta1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1beta1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.texttospeech_v1beta1.types.SynthesizeLongAudioRequest, dict]]): + The request object. The top-level message sent by the + client for the `SynthesizeLongAudio` method. + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.texttospeech_v1beta1.types.SynthesizeLongAudioResponse` + The message returned to the client by the + SynthesizeLongAudio method. + + """ + # Create or coerce a protobuf request object. + request = cloud_tts_lrs.SynthesizeLongAudioRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.synthesize_long_audio, + default_timeout=5000.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloud_tts_lrs.SynthesizeLongAudioResponse, + metadata_type=cloud_tts_lrs.SynthesizeLongAudioMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + 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__ = ("TextToSpeechLongAudioSynthesizeAsyncClient",) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/client.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/client.py new file mode 100644 index 00000000..b9508f3a --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/client.py @@ -0,0 +1,579 @@ +# -*- 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.texttospeech_v1beta1 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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 + +from google.cloud.texttospeech_v1beta1.types import cloud_tts_lrs + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + TextToSpeechLongAudioSynthesizeTransport, +) +from .transports.grpc import TextToSpeechLongAudioSynthesizeGrpcTransport +from .transports.grpc_asyncio import TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + + +class TextToSpeechLongAudioSynthesizeClientMeta(type): + """Metaclass for the TextToSpeechLongAudioSynthesize 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[TextToSpeechLongAudioSynthesizeTransport]] + _transport_registry["grpc"] = TextToSpeechLongAudioSynthesizeGrpcTransport + _transport_registry[ + "grpc_asyncio" + ] = TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[TextToSpeechLongAudioSynthesizeTransport]: + """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 TextToSpeechLongAudioSynthesizeClient( + metaclass=TextToSpeechLongAudioSynthesizeClientMeta +): + """Service that implements Google Cloud Text-to-Speech API.""" + + @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[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "texttospeech.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: + TextToSpeechLongAudioSynthesizeClient: 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: + TextToSpeechLongAudioSynthesizeClient: 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) -> TextToSpeechLongAudioSynthesizeTransport: + """Returns the transport used by the client instance. + + Returns: + TextToSpeechLongAudioSynthesizeTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def model_path( + project: str, + location: str, + model: str, + ) -> str: + """Returns a fully-qualified model string.""" + return "projects/{project}/locations/{location}/models/{model}".format( + project=project, + location=location, + model=model, + ) + + @staticmethod + def parse_model_path(path: str) -> Dict[str, str]: + """Parses a model path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/models/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @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.+?)$", 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.+?)$", 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.+?)$", 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.+?)$", 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.+?)/locations/(?P.+?)$", 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, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, TextToSpeechLongAudioSynthesizeTransport] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the text to speech long audio synthesize 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, TextToSpeechLongAudioSynthesizeTransport]): 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, TextToSpeechLongAudioSynthesizeTransport): + # transport is a TextToSpeechLongAudioSynthesizeTransport 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 synthesize_long_audio( + self, + request: Optional[Union[cloud_tts_lrs.SynthesizeLongAudioRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Synthesizes long form text asynchronously. + + .. 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 texttospeech_v1beta1 + + def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeClient() + + # Initialize request argument(s) + input = texttospeech_v1beta1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1beta1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1beta1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.texttospeech_v1beta1.types.SynthesizeLongAudioRequest, dict]): + The request object. The top-level message sent by the + client for the `SynthesizeLongAudio` method. + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.texttospeech_v1beta1.types.SynthesizeLongAudioResponse` + The message returned to the client by the + SynthesizeLongAudio method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a cloud_tts_lrs.SynthesizeLongAudioRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloud_tts_lrs.SynthesizeLongAudioRequest): + request = cloud_tts_lrs.SynthesizeLongAudioRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.synthesize_long_audio] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_tts_lrs.SynthesizeLongAudioResponse, + metadata_type=cloud_tts_lrs.SynthesizeLongAudioMetadata, + ) + + # 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() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("TextToSpeechLongAudioSynthesizeClient",) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/__init__.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/__init__.py new file mode 100644 index 00000000..be5d9e99 --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- 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 TextToSpeechLongAudioSynthesizeTransport +from .grpc import TextToSpeechLongAudioSynthesizeGrpcTransport +from .grpc_asyncio import TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[TextToSpeechLongAudioSynthesizeTransport]] +_transport_registry["grpc"] = TextToSpeechLongAudioSynthesizeGrpcTransport +_transport_registry[ + "grpc_asyncio" +] = TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport + +__all__ = ( + "TextToSpeechLongAudioSynthesizeTransport", + "TextToSpeechLongAudioSynthesizeGrpcTransport", + "TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport", +) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/base.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/base.py new file mode 100644 index 00000000..63f9a65a --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/base.py @@ -0,0 +1,161 @@ +# -*- 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, operations_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.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.texttospeech_v1beta1 import gapic_version as package_version +from google.cloud.texttospeech_v1beta1.types import cloud_tts_lrs + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class TextToSpeechLongAudioSynthesizeTransport(abc.ABC): + """Abstract transport class for TextToSpeechLongAudioSynthesize.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "texttospeech.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.synthesize_long_audio: gapic_v1.method.wrap_method( + self.synthesize_long_audio, + default_timeout=5000.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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def synthesize_long_audio( + self, + ) -> Callable[ + [cloud_tts_lrs.SynthesizeLongAudioRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("TextToSpeechLongAudioSynthesizeTransport",) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc.py new file mode 100644 index 00000000..0793bcbd --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc.py @@ -0,0 +1,283 @@ +# -*- 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, operations_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 +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.texttospeech_v1beta1.types import cloud_tts_lrs + +from .base import DEFAULT_CLIENT_INFO, TextToSpeechLongAudioSynthesizeTransport + + +class TextToSpeechLongAudioSynthesizeGrpcTransport( + TextToSpeechLongAudioSynthesizeTransport +): + """gRPC backend transport for TextToSpeechLongAudioSynthesize. + + Service that implements Google Cloud Text-to-Speech API. + + 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 = "texttospeech.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + 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 = "texttospeech.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def synthesize_long_audio( + self, + ) -> Callable[[cloud_tts_lrs.SynthesizeLongAudioRequest], operations_pb2.Operation]: + r"""Return a callable for the synthesize long audio method over gRPC. + + Synthesizes long form text asynchronously. + + Returns: + Callable[[~.SynthesizeLongAudioRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "synthesize_long_audio" not in self._stubs: + self._stubs["synthesize_long_audio"] = self.grpc_channel.unary_unary( + "/google.cloud.texttospeech.v1beta1.TextToSpeechLongAudioSynthesize/SynthesizeLongAudio", + request_serializer=cloud_tts_lrs.SynthesizeLongAudioRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["synthesize_long_audio"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("TextToSpeechLongAudioSynthesizeGrpcTransport",) diff --git a/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py new file mode 100644 index 00000000..fe16251e --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/services/text_to_speech_long_audio_synthesize/transports/grpc_asyncio.py @@ -0,0 +1,286 @@ +# -*- 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, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.texttospeech_v1beta1.types import cloud_tts_lrs + +from .base import DEFAULT_CLIENT_INFO, TextToSpeechLongAudioSynthesizeTransport +from .grpc import TextToSpeechLongAudioSynthesizeGrpcTransport + + +class TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport( + TextToSpeechLongAudioSynthesizeTransport +): + """gRPC AsyncIO backend transport for TextToSpeechLongAudioSynthesize. + + Service that implements Google Cloud Text-to-Speech API. + + 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 = "texttospeech.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 = "texttospeech.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def synthesize_long_audio( + self, + ) -> Callable[ + [cloud_tts_lrs.SynthesizeLongAudioRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the synthesize long audio method over gRPC. + + Synthesizes long form text asynchronously. + + Returns: + Callable[[~.SynthesizeLongAudioRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "synthesize_long_audio" not in self._stubs: + self._stubs["synthesize_long_audio"] = self.grpc_channel.unary_unary( + "/google.cloud.texttospeech.v1beta1.TextToSpeechLongAudioSynthesize/SynthesizeLongAudio", + request_serializer=cloud_tts_lrs.SynthesizeLongAudioRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["synthesize_long_audio"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport",) diff --git a/google/cloud/texttospeech_v1beta1/types/__init__.py b/google/cloud/texttospeech_v1beta1/types/__init__.py index 2a34ccab..d030ec6b 100644 --- a/google/cloud/texttospeech_v1beta1/types/__init__.py +++ b/google/cloud/texttospeech_v1beta1/types/__init__.py @@ -27,6 +27,11 @@ Voice, VoiceSelectionParams, ) +from .cloud_tts_lrs import ( + SynthesizeLongAudioMetadata, + SynthesizeLongAudioRequest, + SynthesizeLongAudioResponse, +) __all__ = ( "AudioConfig", @@ -41,4 +46,7 @@ "VoiceSelectionParams", "AudioEncoding", "SsmlVoiceGender", + "SynthesizeLongAudioMetadata", + "SynthesizeLongAudioRequest", + "SynthesizeLongAudioResponse", ) diff --git a/google/cloud/texttospeech_v1beta1/types/cloud_tts.py b/google/cloud/texttospeech_v1beta1/types/cloud_tts.py index e0b6dcb1..f97a7302 100644 --- a/google/cloud/texttospeech_v1beta1/types/cloud_tts.py +++ b/google/cloud/texttospeech_v1beta1/types/cloud_tts.py @@ -185,8 +185,8 @@ class TimepointType(proto.Enum): class SynthesisInput(proto.Message): r"""Contains text input to be synthesized. Either ``text`` or ``ssml`` must be supplied. Supplying both or neither returns - [google.rpc.Code.INVALID_ARGUMENT][]. The input size is limited to - 5000 characters. + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + The input size is limited to 5000 bytes. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -203,8 +203,9 @@ class SynthesisInput(proto.Message): ssml (str): The SSML document to be synthesized. The SSML document must be valid and well-formed. Otherwise the RPC will fail and - return [google.rpc.Code.INVALID_ARGUMENT][]. For more - information, see + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + For more information, see `SSML `__. This field is a member of `oneof`_ ``input_source``. @@ -315,7 +316,8 @@ class AudioConfig(proto.Message): desired sample rate (which might result in worse audio quality), unless the specified sample rate is not supported for the encoding chosen, in which case it will fail the - request and return [google.rpc.Code.INVALID_ARGUMENT][]. + request and return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. effects_profile_id (MutableSequence[str]): Optional. Input only. An identifier which selects 'audio effects' profiles that are applied on (post synthesized) diff --git a/google/cloud/texttospeech_v1beta1/types/cloud_tts_lrs.py b/google/cloud/texttospeech_v1beta1/types/cloud_tts_lrs.py new file mode 100644 index 00000000..14f3e504 --- /dev/null +++ b/google/cloud/texttospeech_v1beta1/types/cloud_tts_lrs.py @@ -0,0 +1,118 @@ +# -*- 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 MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.texttospeech_v1beta1.types import cloud_tts + +__protobuf__ = proto.module( + package="google.cloud.texttospeech.v1beta1", + manifest={ + "SynthesizeLongAudioRequest", + "SynthesizeLongAudioResponse", + "SynthesizeLongAudioMetadata", + }, +) + + +class SynthesizeLongAudioRequest(proto.Message): + r"""The top-level message sent by the client for the + ``SynthesizeLongAudio`` method. + + Attributes: + parent (str): + The resource states of the request in the form of + ``projects/*/locations/*/voices/*``. + input (google.cloud.texttospeech_v1beta1.types.SynthesisInput): + Required. The Synthesizer requires either + plain text or SSML as input. + audio_config (google.cloud.texttospeech_v1beta1.types.AudioConfig): + Required. The configuration of the + synthesized audio. + output_gcs_uri (str): + Specifies a Cloud Storage URI for the synthesis results. + Must be specified in the format: + ``gs://bucket_name/object_name``, and the bucket must + already exist. + voice (google.cloud.texttospeech_v1beta1.types.VoiceSelectionParams): + The desired voice of the synthesized audio. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + input: cloud_tts.SynthesisInput = proto.Field( + proto.MESSAGE, + number=2, + message=cloud_tts.SynthesisInput, + ) + audio_config: cloud_tts.AudioConfig = proto.Field( + proto.MESSAGE, + number=3, + message=cloud_tts.AudioConfig, + ) + output_gcs_uri: str = proto.Field( + proto.STRING, + number=4, + ) + voice: cloud_tts.VoiceSelectionParams = proto.Field( + proto.MESSAGE, + number=5, + message=cloud_tts.VoiceSelectionParams, + ) + + +class SynthesizeLongAudioResponse(proto.Message): + r"""The message returned to the client by the ``SynthesizeLongAudio`` + method. + + """ + + +class SynthesizeLongAudioMetadata(proto.Message): + r"""Metadata for response returned by the ``SynthesizeLongAudio`` + method. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent processing update. + progress_percentage (float): + The progress of the most recent processing + update in percentage, ie. 70.0%. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + progress_percentage: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/release-please-config.json b/release-please-config.json index 25daa576..b6a64559 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -4,7 +4,9 @@ ".": { "release-type": "python", "extra-files": [ + "google/cloud/texttospeech_v1/gapic_version.py", "google/cloud/texttospeech/gapic_version.py", + "google/cloud/texttospeech_v1beta1/gapic_version.py", { "type": "json", "path": "samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json", diff --git a/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json index 5aa209bd..0735eb51 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json @@ -11,6 +11,159 @@ "version": "0.1.0" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.texttospeech_v1.TextToSpeechLongAudioSynthesizeAsyncClient", + "shortName": "TextToSpeechLongAudioSynthesizeAsyncClient" + }, + "fullName": "google.cloud.texttospeech_v1.TextToSpeechLongAudioSynthesizeAsyncClient.synthesize_long_audio", + "method": { + "fullName": "google.cloud.texttospeech.v1.TextToSpeechLongAudioSynthesize.SynthesizeLongAudio", + "service": { + "fullName": "google.cloud.texttospeech.v1.TextToSpeechLongAudioSynthesize", + "shortName": "TextToSpeechLongAudioSynthesize" + }, + "shortName": "SynthesizeLongAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.texttospeech_v1.types.SynthesizeLongAudioRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "synthesize_long_audio" + }, + "description": "Sample for SynthesizeLongAudio", + "file": "texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "texttospeech_v1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.texttospeech_v1.TextToSpeechLongAudioSynthesizeClient", + "shortName": "TextToSpeechLongAudioSynthesizeClient" + }, + "fullName": "google.cloud.texttospeech_v1.TextToSpeechLongAudioSynthesizeClient.synthesize_long_audio", + "method": { + "fullName": "google.cloud.texttospeech.v1.TextToSpeechLongAudioSynthesize.SynthesizeLongAudio", + "service": { + "fullName": "google.cloud.texttospeech.v1.TextToSpeechLongAudioSynthesize", + "shortName": "TextToSpeechLongAudioSynthesize" + }, + "shortName": "SynthesizeLongAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.texttospeech_v1.types.SynthesizeLongAudioRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "synthesize_long_audio" + }, + "description": "Sample for SynthesizeLongAudio", + "file": "texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "texttospeech_v1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json index a338941c..e94d8681 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json @@ -11,6 +11,159 @@ "version": "0.1.0" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeAsyncClient", + "shortName": "TextToSpeechLongAudioSynthesizeAsyncClient" + }, + "fullName": "google.cloud.texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeAsyncClient.synthesize_long_audio", + "method": { + "fullName": "google.cloud.texttospeech.v1beta1.TextToSpeechLongAudioSynthesize.SynthesizeLongAudio", + "service": { + "fullName": "google.cloud.texttospeech.v1beta1.TextToSpeechLongAudioSynthesize", + "shortName": "TextToSpeechLongAudioSynthesize" + }, + "shortName": "SynthesizeLongAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.texttospeech_v1beta1.types.SynthesizeLongAudioRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "synthesize_long_audio" + }, + "description": "Sample for SynthesizeLongAudio", + "file": "texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "texttospeech_v1beta1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeClient", + "shortName": "TextToSpeechLongAudioSynthesizeClient" + }, + "fullName": "google.cloud.texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeClient.synthesize_long_audio", + "method": { + "fullName": "google.cloud.texttospeech.v1beta1.TextToSpeechLongAudioSynthesize.SynthesizeLongAudio", + "service": { + "fullName": "google.cloud.texttospeech.v1beta1.TextToSpeechLongAudioSynthesize", + "shortName": "TextToSpeechLongAudioSynthesize" + }, + "shortName": "SynthesizeLongAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.texttospeech_v1beta1.types.SynthesizeLongAudioRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "synthesize_long_audio" + }, + "description": "Sample for SynthesizeLongAudio", + "file": "texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "texttospeech_v1beta1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py b/samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py new file mode 100644 index 00000000..25a5900f --- /dev/null +++ b/samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py @@ -0,0 +1,63 @@ +# -*- 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 SynthesizeLongAudio +# 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-texttospeech + + +# [START texttospeech_v1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_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 texttospeech_v1 + + +async def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1.TextToSpeechLongAudioSynthesizeAsyncClient() + + # Initialize request argument(s) + input = texttospeech_v1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END texttospeech_v1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_async] diff --git a/samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py b/samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py new file mode 100644 index 00000000..094a3226 --- /dev/null +++ b/samples/generated_samples/texttospeech_v1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py @@ -0,0 +1,63 @@ +# -*- 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 SynthesizeLongAudio +# 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-texttospeech + + +# [START texttospeech_v1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_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 texttospeech_v1 + + +def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1.TextToSpeechLongAudioSynthesizeClient() + + # Initialize request argument(s) + input = texttospeech_v1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END texttospeech_v1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_sync] diff --git a/samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py b/samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py new file mode 100644 index 00000000..1a7ff149 --- /dev/null +++ b/samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_async.py @@ -0,0 +1,63 @@ +# -*- 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 SynthesizeLongAudio +# 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-texttospeech + + +# [START texttospeech_v1beta1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_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 texttospeech_v1beta1 + + +async def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeAsyncClient() + + # Initialize request argument(s) + input = texttospeech_v1beta1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1beta1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1beta1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END texttospeech_v1beta1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_async] diff --git a/samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py b/samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py new file mode 100644 index 00000000..0dadefe5 --- /dev/null +++ b/samples/generated_samples/texttospeech_v1beta1_generated_text_to_speech_long_audio_synthesize_synthesize_long_audio_sync.py @@ -0,0 +1,63 @@ +# -*- 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 SynthesizeLongAudio +# 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-texttospeech + + +# [START texttospeech_v1beta1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_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 texttospeech_v1beta1 + + +def sample_synthesize_long_audio(): + # Create a client + client = texttospeech_v1beta1.TextToSpeechLongAudioSynthesizeClient() + + # Initialize request argument(s) + input = texttospeech_v1beta1.SynthesisInput() + input.text = "text_value" + + audio_config = texttospeech_v1beta1.AudioConfig() + audio_config.audio_encoding = "ALAW" + + request = texttospeech_v1beta1.SynthesizeLongAudioRequest( + input=input, + audio_config=audio_config, + ) + + # Make the request + operation = client.synthesize_long_audio(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END texttospeech_v1beta1_generated_TextToSpeechLongAudioSynthesize_SynthesizeLongAudio_sync] diff --git a/scripts/fixup_texttospeech_v1_keywords.py b/scripts/fixup_texttospeech_v1_keywords.py index 22feca28..8c4e82be 100644 --- a/scripts/fixup_texttospeech_v1_keywords.py +++ b/scripts/fixup_texttospeech_v1_keywords.py @@ -40,6 +40,7 @@ class texttospeechCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'list_voices': ('language_code', ), + 'synthesize_long_audio': ('input', 'audio_config', 'parent', 'output_gcs_uri', 'voice', ), 'synthesize_speech': ('input', 'voice', 'audio_config', ), } diff --git a/scripts/fixup_texttospeech_v1beta1_keywords.py b/scripts/fixup_texttospeech_v1beta1_keywords.py index 51094d94..510d44cb 100644 --- a/scripts/fixup_texttospeech_v1beta1_keywords.py +++ b/scripts/fixup_texttospeech_v1beta1_keywords.py @@ -40,6 +40,7 @@ class texttospeechCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'list_voices': ('language_code', ), + 'synthesize_long_audio': ('input', 'audio_config', 'parent', 'output_gcs_uri', 'voice', ), 'synthesize_speech': ('input', 'voice', 'audio_config', 'enable_time_pointing', ), } diff --git a/setup.py b/setup.py index fd43160b..e7ed1826 100644 --- a/setup.py +++ b/setup.py @@ -38,7 +38,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 diff --git a/tests/unit/gapic/texttospeech_v1/test_text_to_speech.py b/tests/unit/gapic/texttospeech_v1/test_text_to_speech.py index b6ea000b..daac2c05 100644 --- a/tests/unit/gapic/texttospeech_v1/test_text_to_speech.py +++ b/tests/unit/gapic/texttospeech_v1/test_text_to_speech.py @@ -30,6 +30,7 @@ import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 from google.oauth2 import service_account import grpc from grpc.experimental import aio diff --git a/tests/unit/gapic/texttospeech_v1/test_text_to_speech_long_audio_synthesize.py b/tests/unit/gapic/texttospeech_v1/test_text_to_speech_long_audio_synthesize.py new file mode 100644 index 00000000..4d22e7f6 --- /dev/null +++ b/tests/unit/gapic/texttospeech_v1/test_text_to_speech_long_audio_synthesize.py @@ -0,0 +1,1662 @@ +# -*- 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 + +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 +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 google.cloud.texttospeech_v1.services.text_to_speech_long_audio_synthesize import ( + TextToSpeechLongAudioSynthesizeAsyncClient, + TextToSpeechLongAudioSynthesizeClient, + transports, +) +from google.cloud.texttospeech_v1.types import cloud_tts, cloud_tts_lrs + + +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 ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint(None) is None + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (TextToSpeechLongAudioSynthesizeClient, "grpc"), + (TextToSpeechLongAudioSynthesizeAsyncClient, "grpc_asyncio"), + ], +) +def test_text_to_speech_long_audio_synthesize_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 == ("texttospeech.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.TextToSpeechLongAudioSynthesizeGrpcTransport, "grpc"), + ( + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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", + [ + (TextToSpeechLongAudioSynthesizeClient, "grpc"), + (TextToSpeechLongAudioSynthesizeAsyncClient, "grpc_asyncio"), + ], +) +def test_text_to_speech_long_audio_synthesize_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 == ("texttospeech.googleapis.com:443") + + +def test_text_to_speech_long_audio_synthesize_client_get_transport_class(): + transport = TextToSpeechLongAudioSynthesizeClient.get_transport_class() + available_transports = [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + ] + assert transport in available_transports + + transport = TextToSpeechLongAudioSynthesizeClient.get_transport_class("grpc") + assert transport == transports.TextToSpeechLongAudioSynthesizeGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeClient), +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeAsyncClient), +) +def test_text_to_speech_long_audio_synthesize_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( + TextToSpeechLongAudioSynthesizeClient, "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( + TextToSpeechLongAudioSynthesizeClient, "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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + "true", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + "false", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeClient), +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_text_to_speech_long_audio_synthesize_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", + [TextToSpeechLongAudioSynthesizeClient, TextToSpeechLongAudioSynthesizeAsyncClient], +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeClient), +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeAsyncClient), +) +def test_text_to_speech_long_audio_synthesize_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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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_text_to_speech_long_audio_synthesize_client_client_options_from_dict(): + with mock.patch( + "google.cloud.texttospeech_v1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = TextToSpeechLongAudioSynthesizeClient( + 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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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( + "texttospeech.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="texttospeech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tts_lrs.SynthesizeLongAudioRequest, + dict, + ], +) +def test_synthesize_long_audio(request_type, transport: str = "grpc"): + client = TextToSpeechLongAudioSynthesizeClient( + 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.synthesize_long_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tts_lrs.SynthesizeLongAudioRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_synthesize_long_audio_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 = TextToSpeechLongAudioSynthesizeClient( + 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.synthesize_long_audio), "__call__" + ) as call: + client.synthesize_long_audio() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tts_lrs.SynthesizeLongAudioRequest() + + +@pytest.mark.asyncio +async def test_synthesize_long_audio_async( + transport: str = "grpc_asyncio", + request_type=cloud_tts_lrs.SynthesizeLongAudioRequest, +): + client = TextToSpeechLongAudioSynthesizeAsyncClient( + 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.synthesize_long_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tts_lrs.SynthesizeLongAudioRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_synthesize_long_audio_async_from_dict(): + await test_synthesize_long_audio_async(request_type=dict) + + +def test_synthesize_long_audio_field_headers(): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloud_tts_lrs.SynthesizeLongAudioRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.synthesize_long_audio), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_synthesize_long_audio_field_headers_async(): + client = TextToSpeechLongAudioSynthesizeAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloud_tts_lrs.SynthesizeLongAudioRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.synthesize_long_audio), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + 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 = TextToSpeechLongAudioSynthesizeClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TextToSpeechLongAudioSynthesizeClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +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", + ], +) +def test_transport_kind(transport_name): + transport = TextToSpeechLongAudioSynthesizeClient.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 = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + ) + + +def test_text_to_speech_long_audio_synthesize_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TextToSpeechLongAudioSynthesizeTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_text_to_speech_long_audio_synthesize_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.texttospeech_v1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TextToSpeechLongAudioSynthesizeTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("synthesize_long_audio",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_text_to_speech_long_audio_synthesize_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.texttospeech_v1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TextToSpeechLongAudioSynthesizeTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_text_to_speech_long_audio_synthesize_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.texttospeech_v1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TextToSpeechLongAudioSynthesizeTransport() + adc.assert_called_once() + + +def test_text_to_speech_long_audio_synthesize_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) + TextToSpeechLongAudioSynthesizeClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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.TextToSpeechLongAudioSynthesizeGrpcTransport, grpc_helpers), + ( + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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( + "texttospeech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="texttospeech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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 + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_text_to_speech_long_audio_synthesize_host_no_port(transport_name): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="texttospeech.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ("texttospeech.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_text_to_speech_long_audio_synthesize_host_with_port(transport_name): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="texttospeech.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ("texttospeech.googleapis.com:8000") + + +def test_text_to_speech_long_audio_synthesize_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + 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_text_to_speech_long_audio_synthesize_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport( + 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.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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_text_to_speech_long_audio_synthesize_grpc_lro_client(): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_text_to_speech_long_audio_synthesize_grpc_lro_async_client(): + client = TextToSpeechLongAudioSynthesizeAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_model_path(): + project = "squid" + location = "clam" + model = "whelk" + expected = "projects/{project}/locations/{location}/models/{model}".format( + project=project, + location=location, + model=model, + ) + actual = TextToSpeechLongAudioSynthesizeClient.model_path(project, location, model) + assert expected == actual + + +def test_parse_model_path(): + expected = { + "project": "octopus", + "location": "oyster", + "model": "nudibranch", + } + path = TextToSpeechLongAudioSynthesizeClient.model_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_model_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = TextToSpeechLongAudioSynthesizeClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_billing_account_path( + path + ) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = TextToSpeechLongAudioSynthesizeClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_organization_path( + organization + ) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = TextToSpeechLongAudioSynthesizeClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = TextToSpeechLongAudioSynthesizeClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_location_path( + project, location + ) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = TextToSpeechLongAudioSynthesizeClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.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.TextToSpeechLongAudioSynthesizeTransport, "_prep_wrapped_messages" + ) as prep: + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.TextToSpeechLongAudioSynthesizeTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = TextToSpeechLongAudioSynthesizeClient.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 = TextToSpeechLongAudioSynthesizeAsyncClient( + 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 = TextToSpeechLongAudioSynthesizeClient( + 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 = TextToSpeechLongAudioSynthesizeClient( + 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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ), + ], +) +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/texttospeech_v1beta1/test_text_to_speech.py b/tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech.py index 96807af6..2e5cfa94 100644 --- a/tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech.py +++ b/tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech.py @@ -30,6 +30,7 @@ import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 from google.oauth2 import service_account import grpc from grpc.experimental import aio diff --git a/tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech_long_audio_synthesize.py b/tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech_long_audio_synthesize.py new file mode 100644 index 00000000..006a86f4 --- /dev/null +++ b/tests/unit/gapic/texttospeech_v1beta1/test_text_to_speech_long_audio_synthesize.py @@ -0,0 +1,1662 @@ +# -*- 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 + +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 +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 google.cloud.texttospeech_v1beta1.services.text_to_speech_long_audio_synthesize import ( + TextToSpeechLongAudioSynthesizeAsyncClient, + TextToSpeechLongAudioSynthesizeClient, + transports, +) +from google.cloud.texttospeech_v1beta1.types import cloud_tts, cloud_tts_lrs + + +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 ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint(None) is None + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + TextToSpeechLongAudioSynthesizeClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (TextToSpeechLongAudioSynthesizeClient, "grpc"), + (TextToSpeechLongAudioSynthesizeAsyncClient, "grpc_asyncio"), + ], +) +def test_text_to_speech_long_audio_synthesize_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 == ("texttospeech.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.TextToSpeechLongAudioSynthesizeGrpcTransport, "grpc"), + ( + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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", + [ + (TextToSpeechLongAudioSynthesizeClient, "grpc"), + (TextToSpeechLongAudioSynthesizeAsyncClient, "grpc_asyncio"), + ], +) +def test_text_to_speech_long_audio_synthesize_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 == ("texttospeech.googleapis.com:443") + + +def test_text_to_speech_long_audio_synthesize_client_get_transport_class(): + transport = TextToSpeechLongAudioSynthesizeClient.get_transport_class() + available_transports = [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + ] + assert transport in available_transports + + transport = TextToSpeechLongAudioSynthesizeClient.get_transport_class("grpc") + assert transport == transports.TextToSpeechLongAudioSynthesizeGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeClient), +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeAsyncClient), +) +def test_text_to_speech_long_audio_synthesize_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( + TextToSpeechLongAudioSynthesizeClient, "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( + TextToSpeechLongAudioSynthesizeClient, "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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + "true", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + "false", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeClient), +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_text_to_speech_long_audio_synthesize_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", + [TextToSpeechLongAudioSynthesizeClient, TextToSpeechLongAudioSynthesizeAsyncClient], +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeClient), +) +@mock.patch.object( + TextToSpeechLongAudioSynthesizeAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TextToSpeechLongAudioSynthesizeAsyncClient), +) +def test_text_to_speech_long_audio_synthesize_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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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_text_to_speech_long_audio_synthesize_client_client_options_from_dict(): + with mock.patch( + "google.cloud.texttospeech_v1beta1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = TextToSpeechLongAudioSynthesizeClient( + 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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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( + "texttospeech.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="texttospeech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_tts_lrs.SynthesizeLongAudioRequest, + dict, + ], +) +def test_synthesize_long_audio(request_type, transport: str = "grpc"): + client = TextToSpeechLongAudioSynthesizeClient( + 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.synthesize_long_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tts_lrs.SynthesizeLongAudioRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_synthesize_long_audio_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 = TextToSpeechLongAudioSynthesizeClient( + 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.synthesize_long_audio), "__call__" + ) as call: + client.synthesize_long_audio() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tts_lrs.SynthesizeLongAudioRequest() + + +@pytest.mark.asyncio +async def test_synthesize_long_audio_async( + transport: str = "grpc_asyncio", + request_type=cloud_tts_lrs.SynthesizeLongAudioRequest, +): + client = TextToSpeechLongAudioSynthesizeAsyncClient( + 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.synthesize_long_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == cloud_tts_lrs.SynthesizeLongAudioRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_synthesize_long_audio_async_from_dict(): + await test_synthesize_long_audio_async(request_type=dict) + + +def test_synthesize_long_audio_field_headers(): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloud_tts_lrs.SynthesizeLongAudioRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.synthesize_long_audio), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_synthesize_long_audio_field_headers_async(): + client = TextToSpeechLongAudioSynthesizeAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloud_tts_lrs.SynthesizeLongAudioRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.synthesize_long_audio), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.synthesize_long_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + 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 = TextToSpeechLongAudioSynthesizeClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TextToSpeechLongAudioSynthesizeClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TextToSpeechLongAudioSynthesizeClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +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", + ], +) +def test_transport_kind(transport_name): + transport = TextToSpeechLongAudioSynthesizeClient.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 = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + ) + + +def test_text_to_speech_long_audio_synthesize_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TextToSpeechLongAudioSynthesizeTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_text_to_speech_long_audio_synthesize_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.texttospeech_v1beta1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TextToSpeechLongAudioSynthesizeTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("synthesize_long_audio",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_text_to_speech_long_audio_synthesize_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.texttospeech_v1beta1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TextToSpeechLongAudioSynthesizeTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_text_to_speech_long_audio_synthesize_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.texttospeech_v1beta1.services.text_to_speech_long_audio_synthesize.transports.TextToSpeechLongAudioSynthesizeTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TextToSpeechLongAudioSynthesizeTransport() + adc.assert_called_once() + + +def test_text_to_speech_long_audio_synthesize_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) + TextToSpeechLongAudioSynthesizeClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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.TextToSpeechLongAudioSynthesizeGrpcTransport, grpc_helpers), + ( + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_text_to_speech_long_audio_synthesize_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( + "texttospeech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="texttospeech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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 + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_text_to_speech_long_audio_synthesize_host_no_port(transport_name): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="texttospeech.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ("texttospeech.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_text_to_speech_long_audio_synthesize_host_with_port(transport_name): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="texttospeech.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ("texttospeech.googleapis.com:8000") + + +def test_text_to_speech_long_audio_synthesize_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcTransport( + 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_text_to_speech_long_audio_synthesize_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport( + 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.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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.TextToSpeechLongAudioSynthesizeGrpcTransport, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ], +) +def test_text_to_speech_long_audio_synthesize_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_text_to_speech_long_audio_synthesize_grpc_lro_client(): + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_text_to_speech_long_audio_synthesize_grpc_lro_async_client(): + client = TextToSpeechLongAudioSynthesizeAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_model_path(): + project = "squid" + location = "clam" + model = "whelk" + expected = "projects/{project}/locations/{location}/models/{model}".format( + project=project, + location=location, + model=model, + ) + actual = TextToSpeechLongAudioSynthesizeClient.model_path(project, location, model) + assert expected == actual + + +def test_parse_model_path(): + expected = { + "project": "octopus", + "location": "oyster", + "model": "nudibranch", + } + path = TextToSpeechLongAudioSynthesizeClient.model_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_model_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = TextToSpeechLongAudioSynthesizeClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_billing_account_path( + path + ) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = TextToSpeechLongAudioSynthesizeClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_organization_path( + organization + ) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = TextToSpeechLongAudioSynthesizeClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = TextToSpeechLongAudioSynthesizeClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = TextToSpeechLongAudioSynthesizeClient.common_location_path( + project, location + ) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = TextToSpeechLongAudioSynthesizeClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TextToSpeechLongAudioSynthesizeClient.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.TextToSpeechLongAudioSynthesizeTransport, "_prep_wrapped_messages" + ) as prep: + client = TextToSpeechLongAudioSynthesizeClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.TextToSpeechLongAudioSynthesizeTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = TextToSpeechLongAudioSynthesizeClient.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 = TextToSpeechLongAudioSynthesizeAsyncClient( + 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 = TextToSpeechLongAudioSynthesizeClient( + 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 = TextToSpeechLongAudioSynthesizeClient( + 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", + [ + ( + TextToSpeechLongAudioSynthesizeClient, + transports.TextToSpeechLongAudioSynthesizeGrpcTransport, + ), + ( + TextToSpeechLongAudioSynthesizeAsyncClient, + transports.TextToSpeechLongAudioSynthesizeGrpcAsyncIOTransport, + ), + ], +) +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, + )