structure saas with tools

This commit is contained in:
Davidson Gomes
2025-04-25 15:30:54 -03:00
commit 1aef473937
16434 changed files with 6584257 additions and 0 deletions

View File

@@ -0,0 +1,112 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.cloud.speech_v1p1beta1 import gapic_version as package_version
__version__ = package_version.__version__
from .services.adaptation import AdaptationAsyncClient, AdaptationClient
from .services.speech import SpeechAsyncClient, SpeechClient
from .types.cloud_speech import (
LongRunningRecognizeMetadata,
LongRunningRecognizeRequest,
LongRunningRecognizeResponse,
RecognitionAudio,
RecognitionConfig,
RecognitionMetadata,
RecognizeRequest,
RecognizeResponse,
SpeakerDiarizationConfig,
SpeechAdaptationInfo,
SpeechContext,
SpeechRecognitionAlternative,
SpeechRecognitionResult,
StreamingRecognitionConfig,
StreamingRecognitionResult,
StreamingRecognizeRequest,
StreamingRecognizeResponse,
TranscriptOutputConfig,
WordInfo,
)
from .types.cloud_speech_adaptation import (
CreateCustomClassRequest,
CreatePhraseSetRequest,
DeleteCustomClassRequest,
DeletePhraseSetRequest,
GetCustomClassRequest,
GetPhraseSetRequest,
ListCustomClassesRequest,
ListCustomClassesResponse,
ListPhraseSetRequest,
ListPhraseSetResponse,
UpdateCustomClassRequest,
UpdatePhraseSetRequest,
)
from .types.resource import (
CustomClass,
PhraseSet,
SpeechAdaptation,
TranscriptNormalization,
)
from google.cloud.speech_v1.helpers import SpeechHelpers
class SpeechClient(SpeechHelpers, SpeechClient):
__doc__ = SpeechClient.__doc__
__all__ = (
"AdaptationAsyncClient",
"SpeechAsyncClient",
"AdaptationClient",
"CreateCustomClassRequest",
"CreatePhraseSetRequest",
"CustomClass",
"DeleteCustomClassRequest",
"DeletePhraseSetRequest",
"GetCustomClassRequest",
"GetPhraseSetRequest",
"ListCustomClassesRequest",
"ListCustomClassesResponse",
"ListPhraseSetRequest",
"ListPhraseSetResponse",
"LongRunningRecognizeMetadata",
"LongRunningRecognizeRequest",
"LongRunningRecognizeResponse",
"PhraseSet",
"RecognitionAudio",
"RecognitionConfig",
"RecognitionMetadata",
"RecognizeRequest",
"RecognizeResponse",
"SpeakerDiarizationConfig",
"SpeechAdaptation",
"SpeechAdaptationInfo",
"SpeechClient",
"SpeechContext",
"SpeechRecognitionAlternative",
"SpeechRecognitionResult",
"StreamingRecognitionConfig",
"StreamingRecognitionResult",
"StreamingRecognizeRequest",
"StreamingRecognizeResponse",
"TranscriptNormalization",
"TranscriptOutputConfig",
"UpdateCustomClassRequest",
"UpdatePhraseSetRequest",
"WordInfo",
)

View File

@@ -0,0 +1,242 @@
{
"comment": "This file maps proto services/RPCs to the corresponding library clients/methods",
"language": "python",
"libraryPackage": "google.cloud.speech_v1p1beta1",
"protoPackage": "google.cloud.speech.v1p1beta1",
"schema": "1.0",
"services": {
"Adaptation": {
"clients": {
"grpc": {
"libraryClient": "AdaptationClient",
"rpcs": {
"CreateCustomClass": {
"methods": [
"create_custom_class"
]
},
"CreatePhraseSet": {
"methods": [
"create_phrase_set"
]
},
"DeleteCustomClass": {
"methods": [
"delete_custom_class"
]
},
"DeletePhraseSet": {
"methods": [
"delete_phrase_set"
]
},
"GetCustomClass": {
"methods": [
"get_custom_class"
]
},
"GetPhraseSet": {
"methods": [
"get_phrase_set"
]
},
"ListCustomClasses": {
"methods": [
"list_custom_classes"
]
},
"ListPhraseSet": {
"methods": [
"list_phrase_set"
]
},
"UpdateCustomClass": {
"methods": [
"update_custom_class"
]
},
"UpdatePhraseSet": {
"methods": [
"update_phrase_set"
]
}
}
},
"grpc-async": {
"libraryClient": "AdaptationAsyncClient",
"rpcs": {
"CreateCustomClass": {
"methods": [
"create_custom_class"
]
},
"CreatePhraseSet": {
"methods": [
"create_phrase_set"
]
},
"DeleteCustomClass": {
"methods": [
"delete_custom_class"
]
},
"DeletePhraseSet": {
"methods": [
"delete_phrase_set"
]
},
"GetCustomClass": {
"methods": [
"get_custom_class"
]
},
"GetPhraseSet": {
"methods": [
"get_phrase_set"
]
},
"ListCustomClasses": {
"methods": [
"list_custom_classes"
]
},
"ListPhraseSet": {
"methods": [
"list_phrase_set"
]
},
"UpdateCustomClass": {
"methods": [
"update_custom_class"
]
},
"UpdatePhraseSet": {
"methods": [
"update_phrase_set"
]
}
}
},
"rest": {
"libraryClient": "AdaptationClient",
"rpcs": {
"CreateCustomClass": {
"methods": [
"create_custom_class"
]
},
"CreatePhraseSet": {
"methods": [
"create_phrase_set"
]
},
"DeleteCustomClass": {
"methods": [
"delete_custom_class"
]
},
"DeletePhraseSet": {
"methods": [
"delete_phrase_set"
]
},
"GetCustomClass": {
"methods": [
"get_custom_class"
]
},
"GetPhraseSet": {
"methods": [
"get_phrase_set"
]
},
"ListCustomClasses": {
"methods": [
"list_custom_classes"
]
},
"ListPhraseSet": {
"methods": [
"list_phrase_set"
]
},
"UpdateCustomClass": {
"methods": [
"update_custom_class"
]
},
"UpdatePhraseSet": {
"methods": [
"update_phrase_set"
]
}
}
}
}
},
"Speech": {
"clients": {
"grpc": {
"libraryClient": "SpeechClient",
"rpcs": {
"LongRunningRecognize": {
"methods": [
"long_running_recognize"
]
},
"Recognize": {
"methods": [
"recognize"
]
},
"StreamingRecognize": {
"methods": [
"streaming_recognize"
]
}
}
},
"grpc-async": {
"libraryClient": "SpeechAsyncClient",
"rpcs": {
"LongRunningRecognize": {
"methods": [
"long_running_recognize"
]
},
"Recognize": {
"methods": [
"recognize"
]
},
"StreamingRecognize": {
"methods": [
"streaming_recognize"
]
}
}
},
"rest": {
"libraryClient": "SpeechClient",
"rpcs": {
"LongRunningRecognize": {
"methods": [
"long_running_recognize"
]
},
"Recognize": {
"methods": [
"recognize"
]
},
"StreamingRecognize": {
"methods": [
"streaming_recognize"
]
}
}
}
}
}
}
}

View File

@@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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.32.0" # {x-release-please-version}

View File

@@ -0,0 +1,2 @@
# Marker file for PEP 561.
# The google-cloud-speech package uses inline types.

View File

@@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

View File

@@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 AdaptationAsyncClient
from .client import AdaptationClient
__all__ = (
"AdaptationClient",
"AdaptationAsyncClient",
)

View File

@@ -0,0 +1,359 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Iterator,
Optional,
Sequence,
Tuple,
Union,
)
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.api_core import retry_async as retries_async
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
OptionalAsyncRetry = Union[
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource
class ListPhraseSetPager:
"""A pager for iterating through ``list_phrase_set`` requests.
This class thinly wraps an initial
:class:`google.cloud.speech_v1p1beta1.types.ListPhraseSetResponse` object, and
provides an ``__iter__`` method to iterate through its
``phrase_sets`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListPhraseSet`` requests and continue to iterate
through the ``phrase_sets`` field on the
corresponding responses.
All the usual :class:`google.cloud.speech_v1p1beta1.types.ListPhraseSetResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[..., cloud_speech_adaptation.ListPhraseSetResponse],
request: cloud_speech_adaptation.ListPhraseSetRequest,
response: cloud_speech_adaptation.ListPhraseSetResponse,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.speech_v1p1beta1.types.ListPhraseSetRequest):
The initial request object.
response (google.cloud.speech_v1p1beta1.types.ListPhraseSetResponse):
The initial response object.
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, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = cloud_speech_adaptation.ListPhraseSetRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[cloud_speech_adaptation.ListPhraseSetResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(
self._request,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __iter__(self) -> Iterator[resource.PhraseSet]:
for page in self.pages:
yield from page.phrase_sets
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
class ListPhraseSetAsyncPager:
"""A pager for iterating through ``list_phrase_set`` requests.
This class thinly wraps an initial
:class:`google.cloud.speech_v1p1beta1.types.ListPhraseSetResponse` object, and
provides an ``__aiter__`` method to iterate through its
``phrase_sets`` field.
If there are more pages, the ``__aiter__`` method will make additional
``ListPhraseSet`` requests and continue to iterate
through the ``phrase_sets`` field on the
corresponding responses.
All the usual :class:`google.cloud.speech_v1p1beta1.types.ListPhraseSetResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[..., Awaitable[cloud_speech_adaptation.ListPhraseSetResponse]],
request: cloud_speech_adaptation.ListPhraseSetRequest,
response: cloud_speech_adaptation.ListPhraseSetResponse,
*,
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.speech_v1p1beta1.types.ListPhraseSetRequest):
The initial request object.
response (google.cloud.speech_v1p1beta1.types.ListPhraseSetResponse):
The initial response object.
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = cloud_speech_adaptation.ListPhraseSetRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
async def pages(
self,
) -> AsyncIterator[cloud_speech_adaptation.ListPhraseSetResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = await self._method(
self._request,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __aiter__(self) -> AsyncIterator[resource.PhraseSet]:
async def async_generator():
async for page in self.pages:
for response in page.phrase_sets:
yield response
return async_generator()
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
class ListCustomClassesPager:
"""A pager for iterating through ``list_custom_classes`` requests.
This class thinly wraps an initial
:class:`google.cloud.speech_v1p1beta1.types.ListCustomClassesResponse` object, and
provides an ``__iter__`` method to iterate through its
``custom_classes`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListCustomClasses`` requests and continue to iterate
through the ``custom_classes`` field on the
corresponding responses.
All the usual :class:`google.cloud.speech_v1p1beta1.types.ListCustomClassesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[..., cloud_speech_adaptation.ListCustomClassesResponse],
request: cloud_speech_adaptation.ListCustomClassesRequest,
response: cloud_speech_adaptation.ListCustomClassesResponse,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.speech_v1p1beta1.types.ListCustomClassesRequest):
The initial request object.
response (google.cloud.speech_v1p1beta1.types.ListCustomClassesResponse):
The initial response object.
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, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = cloud_speech_adaptation.ListCustomClassesRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[cloud_speech_adaptation.ListCustomClassesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(
self._request,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __iter__(self) -> Iterator[resource.CustomClass]:
for page in self.pages:
yield from page.custom_classes
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
class ListCustomClassesAsyncPager:
"""A pager for iterating through ``list_custom_classes`` requests.
This class thinly wraps an initial
:class:`google.cloud.speech_v1p1beta1.types.ListCustomClassesResponse` object, and
provides an ``__aiter__`` method to iterate through its
``custom_classes`` field.
If there are more pages, the ``__aiter__`` method will make additional
``ListCustomClasses`` requests and continue to iterate
through the ``custom_classes`` field on the
corresponding responses.
All the usual :class:`google.cloud.speech_v1p1beta1.types.ListCustomClassesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[
..., Awaitable[cloud_speech_adaptation.ListCustomClassesResponse]
],
request: cloud_speech_adaptation.ListCustomClassesRequest,
response: cloud_speech_adaptation.ListCustomClassesResponse,
*,
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
):
"""Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.speech_v1p1beta1.types.ListCustomClassesRequest):
The initial request object.
response (google.cloud.speech_v1p1beta1.types.ListCustomClassesResponse):
The initial response object.
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
"""
self._method = method
self._request = cloud_speech_adaptation.ListCustomClassesRequest(request)
self._response = response
self._retry = retry
self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
async def pages(
self,
) -> AsyncIterator[cloud_speech_adaptation.ListCustomClassesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = await self._method(
self._request,
retry=self._retry,
timeout=self._timeout,
metadata=self._metadata,
)
yield self._response
def __aiter__(self) -> AsyncIterator[resource.CustomClass]:
async def async_generator():
async for page in self.pages:
for response in page.custom_classes:
yield response
return async_generator()
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)

View File

@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 AdaptationTransport
from .grpc import AdaptationGrpcTransport
from .grpc_asyncio import AdaptationGrpcAsyncIOTransport
from .rest import AdaptationRestInterceptor, AdaptationRestTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[AdaptationTransport]]
_transport_registry["grpc"] = AdaptationGrpcTransport
_transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport
_transport_registry["rest"] = AdaptationRestTransport
__all__ = (
"AdaptationTransport",
"AdaptationGrpcTransport",
"AdaptationGrpcAsyncIOTransport",
"AdaptationRestTransport",
"AdaptationRestInterceptor",
)

View File

@@ -0,0 +1,326 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import google.api_core
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.cloud.speech_v1p1beta1 import gapic_version as package_version
from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=package_version.__version__
)
class AdaptationTransport(abc.ABC):
"""Abstract transport class for Adaptation."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
DEFAULT_HOST: str = "speech.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 (default: 'speech.googleapis.com').
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 not hasattr(self, "_ignore_credentials"):
self._ignore_credentials: bool = False
# 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 and not self._ignore_credentials:
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
@property
def host(self):
return self._host
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.create_phrase_set: gapic_v1.method.wrap_method(
self.create_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.get_phrase_set: gapic_v1.method.wrap_method(
self.get_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.list_phrase_set: gapic_v1.method.wrap_method(
self.list_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.update_phrase_set: gapic_v1.method.wrap_method(
self.update_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.delete_phrase_set: gapic_v1.method.wrap_method(
self.delete_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.create_custom_class: gapic_v1.method.wrap_method(
self.create_custom_class,
default_timeout=None,
client_info=client_info,
),
self.get_custom_class: gapic_v1.method.wrap_method(
self.get_custom_class,
default_timeout=None,
client_info=client_info,
),
self.list_custom_classes: gapic_v1.method.wrap_method(
self.list_custom_classes,
default_timeout=None,
client_info=client_info,
),
self.update_custom_class: gapic_v1.method.wrap_method(
self.update_custom_class,
default_timeout=None,
client_info=client_info,
),
self.delete_custom_class: gapic_v1.method.wrap_method(
self.delete_custom_class,
default_timeout=None,
client_info=client_info,
),
self.get_operation: gapic_v1.method.wrap_method(
self.get_operation,
default_timeout=None,
client_info=client_info,
),
self.list_operations: gapic_v1.method.wrap_method(
self.list_operations,
default_timeout=None,
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 create_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.CreatePhraseSetRequest],
Union[resource.PhraseSet, Awaitable[resource.PhraseSet]],
]:
raise NotImplementedError()
@property
def get_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.GetPhraseSetRequest],
Union[resource.PhraseSet, Awaitable[resource.PhraseSet]],
]:
raise NotImplementedError()
@property
def list_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.ListPhraseSetRequest],
Union[
cloud_speech_adaptation.ListPhraseSetResponse,
Awaitable[cloud_speech_adaptation.ListPhraseSetResponse],
],
]:
raise NotImplementedError()
@property
def update_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.UpdatePhraseSetRequest],
Union[resource.PhraseSet, Awaitable[resource.PhraseSet]],
]:
raise NotImplementedError()
@property
def delete_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.DeletePhraseSetRequest],
Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def create_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.CreateCustomClassRequest],
Union[resource.CustomClass, Awaitable[resource.CustomClass]],
]:
raise NotImplementedError()
@property
def get_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.GetCustomClassRequest],
Union[resource.CustomClass, Awaitable[resource.CustomClass]],
]:
raise NotImplementedError()
@property
def list_custom_classes(
self,
) -> Callable[
[cloud_speech_adaptation.ListCustomClassesRequest],
Union[
cloud_speech_adaptation.ListCustomClassesResponse,
Awaitable[cloud_speech_adaptation.ListCustomClassesResponse],
],
]:
raise NotImplementedError()
@property
def update_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.UpdateCustomClassRequest],
Union[resource.CustomClass, Awaitable[resource.CustomClass]],
]:
raise NotImplementedError()
@property
def delete_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.DeleteCustomClassRequest],
Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_operations(
self,
) -> Callable[
[operations_pb2.ListOperationsRequest],
Union[
operations_pb2.ListOperationsResponse,
Awaitable[operations_pb2.ListOperationsResponse],
],
]:
raise NotImplementedError()
@property
def get_operation(
self,
) -> Callable[
[operations_pb2.GetOperationRequest],
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def kind(self) -> str:
raise NotImplementedError()
__all__ = ("AdaptationTransport",)

View File

@@ -0,0 +1,644 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import logging as std_logging
import pickle
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
from google.api_core import gapic_v1, grpc_helpers
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf.json_format import MessageToJson
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource
from .base import DEFAULT_CLIENT_INFO, AdaptationTransport
try:
from google.api_core import client_logging # type: ignore
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
except ImportError: # pragma: NO COVER
CLIENT_LOGGING_SUPPORTED = False
_LOGGER = std_logging.getLogger(__name__)
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
def intercept_unary_unary(self, continuation, client_call_details, request):
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
std_logging.DEBUG
)
if logging_enabled: # pragma: NO COVER
request_metadata = client_call_details.metadata
if isinstance(request, proto.Message):
request_payload = type(request).to_json(request)
elif isinstance(request, google.protobuf.message.Message):
request_payload = MessageToJson(request)
else:
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
request_metadata = {
key: value.decode("utf-8") if isinstance(value, bytes) else value
for key, value in request_metadata
}
grpc_request = {
"payload": request_payload,
"requestMethod": "grpc",
"metadata": dict(request_metadata),
}
_LOGGER.debug(
f"Sending request for {client_call_details.method}",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Adaptation",
"rpcName": client_call_details.method,
"request": grpc_request,
"metadata": grpc_request["metadata"],
},
)
response = continuation(client_call_details, request)
if logging_enabled: # pragma: NO COVER
response_metadata = response.trailing_metadata()
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
metadata = (
dict([(k, str(v)) for k, v in response_metadata])
if response_metadata
else None
)
result = response.result()
if isinstance(result, proto.Message):
response_payload = type(result).to_json(result)
elif isinstance(result, google.protobuf.message.Message):
response_payload = MessageToJson(result)
else:
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
grpc_response = {
"payload": response_payload,
"metadata": metadata,
"status": "OK",
}
_LOGGER.debug(
f"Received response for {client_call_details.method}.",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Adaptation",
"rpcName": client_call_details.method,
"response": grpc_response,
"metadata": grpc_response["metadata"],
},
)
return response
class AdaptationGrpcTransport(AdaptationTransport):
"""gRPC backend transport for Adaptation.
Service that implements Google Cloud Speech Adaptation 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 = "speech.googleapis.com",
credentials: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: Optional[Union[grpc.Channel, Callable[..., 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 (default: 'speech.googleapis.com').
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 a ``channel`` instance 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 a ``channel`` instance is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if a ``channel`` instance is provided.
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
A ``Channel`` instance through which to make calls, or a Callable
that constructs and returns one. If set to None, ``self.create_channel``
is used to create the channel. If a Callable is given, it will be called
with the same arguments as used in ``self.create_channel``.
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 a ``channel`` instance 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 a ``channel`` instance or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
credentials = None
self._ignore_credentials = True
# 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:
# initialize with the provided callable or the default channel
channel_init = channel or type(self).create_channel
self._grpc_channel = channel_init(
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),
],
)
self._interceptor = _LoggingClientInterceptor()
self._logged_channel = grpc.intercept_channel(
self._grpc_channel, self._interceptor
)
# Wrap messages. This must be done after self._logged_channel exists
self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "speech.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 create_phrase_set(
self,
) -> Callable[[cloud_speech_adaptation.CreatePhraseSetRequest], resource.PhraseSet]:
r"""Return a callable for the create phrase set method over gRPC.
Create a set of phrase hints. Each item in the set
can be a single word or a multi-word phrase. The items
in the PhraseSet are favored by the recognition model
when you send a call that includes the PhraseSet.
Returns:
Callable[[~.CreatePhraseSetRequest],
~.PhraseSet]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_phrase_set" not in self._stubs:
self._stubs["create_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/CreatePhraseSet",
request_serializer=cloud_speech_adaptation.CreatePhraseSetRequest.serialize,
response_deserializer=resource.PhraseSet.deserialize,
)
return self._stubs["create_phrase_set"]
@property
def get_phrase_set(
self,
) -> Callable[[cloud_speech_adaptation.GetPhraseSetRequest], resource.PhraseSet]:
r"""Return a callable for the get phrase set method over gRPC.
Get a phrase set.
Returns:
Callable[[~.GetPhraseSetRequest],
~.PhraseSet]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_phrase_set" not in self._stubs:
self._stubs["get_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/GetPhraseSet",
request_serializer=cloud_speech_adaptation.GetPhraseSetRequest.serialize,
response_deserializer=resource.PhraseSet.deserialize,
)
return self._stubs["get_phrase_set"]
@property
def list_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.ListPhraseSetRequest],
cloud_speech_adaptation.ListPhraseSetResponse,
]:
r"""Return a callable for the list phrase set method over gRPC.
List phrase sets.
Returns:
Callable[[~.ListPhraseSetRequest],
~.ListPhraseSetResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_phrase_set" not in self._stubs:
self._stubs["list_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/ListPhraseSet",
request_serializer=cloud_speech_adaptation.ListPhraseSetRequest.serialize,
response_deserializer=cloud_speech_adaptation.ListPhraseSetResponse.deserialize,
)
return self._stubs["list_phrase_set"]
@property
def update_phrase_set(
self,
) -> Callable[[cloud_speech_adaptation.UpdatePhraseSetRequest], resource.PhraseSet]:
r"""Return a callable for the update phrase set method over gRPC.
Update a phrase set.
Returns:
Callable[[~.UpdatePhraseSetRequest],
~.PhraseSet]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_phrase_set" not in self._stubs:
self._stubs["update_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/UpdatePhraseSet",
request_serializer=cloud_speech_adaptation.UpdatePhraseSetRequest.serialize,
response_deserializer=resource.PhraseSet.deserialize,
)
return self._stubs["update_phrase_set"]
@property
def delete_phrase_set(
self,
) -> Callable[[cloud_speech_adaptation.DeletePhraseSetRequest], empty_pb2.Empty]:
r"""Return a callable for the delete phrase set method over gRPC.
Delete a phrase set.
Returns:
Callable[[~.DeletePhraseSetRequest],
~.Empty]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_phrase_set" not in self._stubs:
self._stubs["delete_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/DeletePhraseSet",
request_serializer=cloud_speech_adaptation.DeletePhraseSetRequest.serialize,
response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_phrase_set"]
@property
def create_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.CreateCustomClassRequest], resource.CustomClass
]:
r"""Return a callable for the create custom class method over gRPC.
Create a custom class.
Returns:
Callable[[~.CreateCustomClassRequest],
~.CustomClass]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_custom_class" not in self._stubs:
self._stubs["create_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/CreateCustomClass",
request_serializer=cloud_speech_adaptation.CreateCustomClassRequest.serialize,
response_deserializer=resource.CustomClass.deserialize,
)
return self._stubs["create_custom_class"]
@property
def get_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.GetCustomClassRequest], resource.CustomClass
]:
r"""Return a callable for the get custom class method over gRPC.
Get a custom class.
Returns:
Callable[[~.GetCustomClassRequest],
~.CustomClass]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_custom_class" not in self._stubs:
self._stubs["get_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/GetCustomClass",
request_serializer=cloud_speech_adaptation.GetCustomClassRequest.serialize,
response_deserializer=resource.CustomClass.deserialize,
)
return self._stubs["get_custom_class"]
@property
def list_custom_classes(
self,
) -> Callable[
[cloud_speech_adaptation.ListCustomClassesRequest],
cloud_speech_adaptation.ListCustomClassesResponse,
]:
r"""Return a callable for the list custom classes method over gRPC.
List custom classes.
Returns:
Callable[[~.ListCustomClassesRequest],
~.ListCustomClassesResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_custom_classes" not in self._stubs:
self._stubs["list_custom_classes"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/ListCustomClasses",
request_serializer=cloud_speech_adaptation.ListCustomClassesRequest.serialize,
response_deserializer=cloud_speech_adaptation.ListCustomClassesResponse.deserialize,
)
return self._stubs["list_custom_classes"]
@property
def update_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.UpdateCustomClassRequest], resource.CustomClass
]:
r"""Return a callable for the update custom class method over gRPC.
Update a custom class.
Returns:
Callable[[~.UpdateCustomClassRequest],
~.CustomClass]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_custom_class" not in self._stubs:
self._stubs["update_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/UpdateCustomClass",
request_serializer=cloud_speech_adaptation.UpdateCustomClassRequest.serialize,
response_deserializer=resource.CustomClass.deserialize,
)
return self._stubs["update_custom_class"]
@property
def delete_custom_class(
self,
) -> Callable[[cloud_speech_adaptation.DeleteCustomClassRequest], empty_pb2.Empty]:
r"""Return a callable for the delete custom class method over gRPC.
Delete a custom class.
Returns:
Callable[[~.DeleteCustomClassRequest],
~.Empty]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_custom_class" not in self._stubs:
self._stubs["delete_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/DeleteCustomClass",
request_serializer=cloud_speech_adaptation.DeleteCustomClassRequest.serialize,
response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_custom_class"]
def close(self):
self._logged_channel.close()
@property
def get_operation(
self,
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
r"""Return a callable for the get_operation method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_operation" not in self._stubs:
self._stubs["get_operation"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/GetOperation",
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["get_operation"]
@property
def list_operations(
self,
) -> Callable[
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
]:
r"""Return a callable for the list_operations method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_operations" not in self._stubs:
self._stubs["list_operations"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/ListOperations",
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
)
return self._stubs["list_operations"]
@property
def kind(self) -> str:
return "grpc"
__all__ = ("AdaptationGrpcTransport",)

View File

@@ -0,0 +1,733 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 inspect
import json
import logging as std_logging
import pickle
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, grpc_helpers_async
from google.api_core import retry_async as retries
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
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf.json_format import MessageToJson
import google.protobuf.message
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
import proto # type: ignore
from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource
from .base import DEFAULT_CLIENT_INFO, AdaptationTransport
from .grpc import AdaptationGrpcTransport
try:
from google.api_core import client_logging # type: ignore
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
except ImportError: # pragma: NO COVER
CLIENT_LOGGING_SUPPORTED = False
_LOGGER = std_logging.getLogger(__name__)
class _LoggingClientAIOInterceptor(
grpc.aio.UnaryUnaryClientInterceptor
): # pragma: NO COVER
async def intercept_unary_unary(self, continuation, client_call_details, request):
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
std_logging.DEBUG
)
if logging_enabled: # pragma: NO COVER
request_metadata = client_call_details.metadata
if isinstance(request, proto.Message):
request_payload = type(request).to_json(request)
elif isinstance(request, google.protobuf.message.Message):
request_payload = MessageToJson(request)
else:
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
request_metadata = {
key: value.decode("utf-8") if isinstance(value, bytes) else value
for key, value in request_metadata
}
grpc_request = {
"payload": request_payload,
"requestMethod": "grpc",
"metadata": dict(request_metadata),
}
_LOGGER.debug(
f"Sending request for {client_call_details.method}",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Adaptation",
"rpcName": str(client_call_details.method),
"request": grpc_request,
"metadata": grpc_request["metadata"],
},
)
response = await continuation(client_call_details, request)
if logging_enabled: # pragma: NO COVER
response_metadata = await response.trailing_metadata()
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
metadata = (
dict([(k, str(v)) for k, v in response_metadata])
if response_metadata
else None
)
result = await response
if isinstance(result, proto.Message):
response_payload = type(result).to_json(result)
elif isinstance(result, google.protobuf.message.Message):
response_payload = MessageToJson(result)
else:
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
grpc_response = {
"payload": response_payload,
"metadata": metadata,
"status": "OK",
}
_LOGGER.debug(
f"Received response to rpc {client_call_details.method}.",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Adaptation",
"rpcName": str(client_call_details.method),
"response": grpc_response,
"metadata": grpc_response["metadata"],
},
)
return response
class AdaptationGrpcAsyncIOTransport(AdaptationTransport):
"""gRPC AsyncIO backend transport for Adaptation.
Service that implements Google Cloud Speech Adaptation 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 = "speech.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`.
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 = "speech.googleapis.com",
credentials: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: Optional[Union[aio.Channel, Callable[..., 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 (default: 'speech.googleapis.com').
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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]):
A ``Channel`` instance through which to make calls, or a Callable
that constructs and returns one. If set to None, ``self.create_channel``
is used to create the channel. If a Callable is given, it will be called
with the same arguments as used in ``self.create_channel``.
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 a ``channel`` instance 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 a ``channel`` instance or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
credentials = None
self._ignore_credentials = True
# 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:
# initialize with the provided callable or the default channel
channel_init = channel or type(self).create_channel
self._grpc_channel = channel_init(
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),
],
)
self._interceptor = _LoggingClientAIOInterceptor()
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
self._logged_channel = self._grpc_channel
self._wrap_with_kind = (
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
)
# Wrap messages. This must be done after self._logged_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 create_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.CreatePhraseSetRequest], Awaitable[resource.PhraseSet]
]:
r"""Return a callable for the create phrase set method over gRPC.
Create a set of phrase hints. Each item in the set
can be a single word or a multi-word phrase. The items
in the PhraseSet are favored by the recognition model
when you send a call that includes the PhraseSet.
Returns:
Callable[[~.CreatePhraseSetRequest],
Awaitable[~.PhraseSet]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_phrase_set" not in self._stubs:
self._stubs["create_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/CreatePhraseSet",
request_serializer=cloud_speech_adaptation.CreatePhraseSetRequest.serialize,
response_deserializer=resource.PhraseSet.deserialize,
)
return self._stubs["create_phrase_set"]
@property
def get_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.GetPhraseSetRequest], Awaitable[resource.PhraseSet]
]:
r"""Return a callable for the get phrase set method over gRPC.
Get a phrase set.
Returns:
Callable[[~.GetPhraseSetRequest],
Awaitable[~.PhraseSet]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_phrase_set" not in self._stubs:
self._stubs["get_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/GetPhraseSet",
request_serializer=cloud_speech_adaptation.GetPhraseSetRequest.serialize,
response_deserializer=resource.PhraseSet.deserialize,
)
return self._stubs["get_phrase_set"]
@property
def list_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.ListPhraseSetRequest],
Awaitable[cloud_speech_adaptation.ListPhraseSetResponse],
]:
r"""Return a callable for the list phrase set method over gRPC.
List phrase sets.
Returns:
Callable[[~.ListPhraseSetRequest],
Awaitable[~.ListPhraseSetResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_phrase_set" not in self._stubs:
self._stubs["list_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/ListPhraseSet",
request_serializer=cloud_speech_adaptation.ListPhraseSetRequest.serialize,
response_deserializer=cloud_speech_adaptation.ListPhraseSetResponse.deserialize,
)
return self._stubs["list_phrase_set"]
@property
def update_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.UpdatePhraseSetRequest], Awaitable[resource.PhraseSet]
]:
r"""Return a callable for the update phrase set method over gRPC.
Update a phrase set.
Returns:
Callable[[~.UpdatePhraseSetRequest],
Awaitable[~.PhraseSet]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_phrase_set" not in self._stubs:
self._stubs["update_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/UpdatePhraseSet",
request_serializer=cloud_speech_adaptation.UpdatePhraseSetRequest.serialize,
response_deserializer=resource.PhraseSet.deserialize,
)
return self._stubs["update_phrase_set"]
@property
def delete_phrase_set(
self,
) -> Callable[
[cloud_speech_adaptation.DeletePhraseSetRequest], Awaitable[empty_pb2.Empty]
]:
r"""Return a callable for the delete phrase set method over gRPC.
Delete a phrase set.
Returns:
Callable[[~.DeletePhraseSetRequest],
Awaitable[~.Empty]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_phrase_set" not in self._stubs:
self._stubs["delete_phrase_set"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/DeletePhraseSet",
request_serializer=cloud_speech_adaptation.DeletePhraseSetRequest.serialize,
response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_phrase_set"]
@property
def create_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.CreateCustomClassRequest],
Awaitable[resource.CustomClass],
]:
r"""Return a callable for the create custom class method over gRPC.
Create a custom class.
Returns:
Callable[[~.CreateCustomClassRequest],
Awaitable[~.CustomClass]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_custom_class" not in self._stubs:
self._stubs["create_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/CreateCustomClass",
request_serializer=cloud_speech_adaptation.CreateCustomClassRequest.serialize,
response_deserializer=resource.CustomClass.deserialize,
)
return self._stubs["create_custom_class"]
@property
def get_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.GetCustomClassRequest], Awaitable[resource.CustomClass]
]:
r"""Return a callable for the get custom class method over gRPC.
Get a custom class.
Returns:
Callable[[~.GetCustomClassRequest],
Awaitable[~.CustomClass]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_custom_class" not in self._stubs:
self._stubs["get_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/GetCustomClass",
request_serializer=cloud_speech_adaptation.GetCustomClassRequest.serialize,
response_deserializer=resource.CustomClass.deserialize,
)
return self._stubs["get_custom_class"]
@property
def list_custom_classes(
self,
) -> Callable[
[cloud_speech_adaptation.ListCustomClassesRequest],
Awaitable[cloud_speech_adaptation.ListCustomClassesResponse],
]:
r"""Return a callable for the list custom classes method over gRPC.
List custom classes.
Returns:
Callable[[~.ListCustomClassesRequest],
Awaitable[~.ListCustomClassesResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_custom_classes" not in self._stubs:
self._stubs["list_custom_classes"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/ListCustomClasses",
request_serializer=cloud_speech_adaptation.ListCustomClassesRequest.serialize,
response_deserializer=cloud_speech_adaptation.ListCustomClassesResponse.deserialize,
)
return self._stubs["list_custom_classes"]
@property
def update_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.UpdateCustomClassRequest],
Awaitable[resource.CustomClass],
]:
r"""Return a callable for the update custom class method over gRPC.
Update a custom class.
Returns:
Callable[[~.UpdateCustomClassRequest],
Awaitable[~.CustomClass]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_custom_class" not in self._stubs:
self._stubs["update_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/UpdateCustomClass",
request_serializer=cloud_speech_adaptation.UpdateCustomClassRequest.serialize,
response_deserializer=resource.CustomClass.deserialize,
)
return self._stubs["update_custom_class"]
@property
def delete_custom_class(
self,
) -> Callable[
[cloud_speech_adaptation.DeleteCustomClassRequest], Awaitable[empty_pb2.Empty]
]:
r"""Return a callable for the delete custom class method over gRPC.
Delete a custom class.
Returns:
Callable[[~.DeleteCustomClassRequest],
Awaitable[~.Empty]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_custom_class" not in self._stubs:
self._stubs["delete_custom_class"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Adaptation/DeleteCustomClass",
request_serializer=cloud_speech_adaptation.DeleteCustomClassRequest.serialize,
response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_custom_class"]
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
self.create_phrase_set: self._wrap_method(
self.create_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.get_phrase_set: self._wrap_method(
self.get_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.list_phrase_set: self._wrap_method(
self.list_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.update_phrase_set: self._wrap_method(
self.update_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.delete_phrase_set: self._wrap_method(
self.delete_phrase_set,
default_timeout=None,
client_info=client_info,
),
self.create_custom_class: self._wrap_method(
self.create_custom_class,
default_timeout=None,
client_info=client_info,
),
self.get_custom_class: self._wrap_method(
self.get_custom_class,
default_timeout=None,
client_info=client_info,
),
self.list_custom_classes: self._wrap_method(
self.list_custom_classes,
default_timeout=None,
client_info=client_info,
),
self.update_custom_class: self._wrap_method(
self.update_custom_class,
default_timeout=None,
client_info=client_info,
),
self.delete_custom_class: self._wrap_method(
self.delete_custom_class,
default_timeout=None,
client_info=client_info,
),
self.get_operation: self._wrap_method(
self.get_operation,
default_timeout=None,
client_info=client_info,
),
self.list_operations: self._wrap_method(
self.list_operations,
default_timeout=None,
client_info=client_info,
),
}
def _wrap_method(self, func, *args, **kwargs):
if self._wrap_with_kind: # pragma: NO COVER
kwargs["kind"] = self.kind
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
def close(self):
return self._logged_channel.close()
@property
def kind(self) -> str:
return "grpc_asyncio"
@property
def get_operation(
self,
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
r"""Return a callable for the get_operation method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_operation" not in self._stubs:
self._stubs["get_operation"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/GetOperation",
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["get_operation"]
@property
def list_operations(
self,
) -> Callable[
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
]:
r"""Return a callable for the list_operations method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_operations" not in self._stubs:
self._stubs["list_operations"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/ListOperations",
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
)
return self._stubs["list_operations"]
__all__ = ("AdaptationGrpcAsyncIOTransport",)

View File

@@ -0,0 +1,653 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json # type: ignore
import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1, path_template
from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource
from .base import DEFAULT_CLIENT_INFO, AdaptationTransport
class _BaseAdaptationRestTransport(AdaptationTransport):
"""Base REST backend transport for Adaptation.
Note: This class is not meant to be used directly. Use its sync and
async sub-classes instead.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
"""
def __init__(
self,
*,
host: str = "speech.googleapis.com",
credentials: Optional[Any] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
url_scheme: str = "https",
api_audience: Optional[str] = None,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to (default: 'speech.googleapis.com').
credentials (Optional[Any]): 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.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you are developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
url_scheme: the protocol scheme for the API endpoint. Normally
"https", but for testing or local servers,
"http" can be specified.
"""
# Run the base constructor
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
if maybe_url_match is None:
raise ValueError(
f"Unexpected hostname structure: {host}"
) # pragma: NO COVER
url_match_items = maybe_url_match.groupdict()
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
api_audience=api_audience,
)
class _BaseCreateCustomClass:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1p1beta1/{parent=projects/*/locations/*}/customClasses",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.CreateCustomClassRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseCreateCustomClass._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseCreatePhraseSet:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1p1beta1/{parent=projects/*/locations/*}/phraseSets",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.CreatePhraseSetRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseCreatePhraseSet._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseDeleteCustomClass:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "delete",
"uri": "/v1p1beta1/{name=projects/*/locations/*/customClasses/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.DeleteCustomClassRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseDeleteCustomClass._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseDeletePhraseSet:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "delete",
"uri": "/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.DeletePhraseSetRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseDeletePhraseSet._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseGetCustomClass:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/{name=projects/*/locations/*/customClasses/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.GetCustomClassRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseGetCustomClass._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseGetPhraseSet:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.GetPhraseSetRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseGetPhraseSet._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseListCustomClasses:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/{parent=projects/*/locations/*}/customClasses",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.ListCustomClassesRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseListCustomClasses._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseListPhraseSet:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/{parent=projects/*/locations/*}/phraseSets",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.ListPhraseSetRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseListPhraseSet._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseUpdateCustomClass:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "patch",
"uri": "/v1p1beta1/{custom_class.name=projects/*/locations/*/customClasses/*}",
"body": "custom_class",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.UpdateCustomClassRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseUpdateCustomClass._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseUpdatePhraseSet:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "patch",
"uri": "/v1p1beta1/{phrase_set.name=projects/*/locations/*/phraseSets/*}",
"body": "phrase_set",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech_adaptation.UpdatePhraseSetRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseGetOperation:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/operations/{name=**}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
request_kwargs = json_format.MessageToDict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
return query_params
class _BaseListOperations:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/operations",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
request_kwargs = json_format.MessageToDict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
return query_params
__all__ = ("_BaseAdaptationRestTransport",)

View File

@@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 SpeechAsyncClient
from .client import SpeechClient
__all__ = (
"SpeechClient",
"SpeechAsyncClient",
)

View File

@@ -0,0 +1,844 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 logging as std_logging
import re
from typing import (
AsyncIterable,
AsyncIterator,
Awaitable,
Callable,
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_async 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.speech_v1p1beta1 import gapic_version as package_version
try:
OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.AsyncRetry, object, None] # 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 # type: ignore
from google.protobuf import duration_pb2 # type: ignore
from google.rpc import status_pb2 # type: ignore
from google.cloud.speech_v1p1beta1.types import cloud_speech
from .client import SpeechClient
from .transports.base import DEFAULT_CLIENT_INFO, SpeechTransport
from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport
try:
from google.api_core import client_logging # type: ignore
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
except ImportError: # pragma: NO COVER
CLIENT_LOGGING_SUPPORTED = False
_LOGGER = std_logging.getLogger(__name__)
class SpeechAsyncClient:
"""Service that implements Google Cloud Speech API."""
_client: SpeechClient
# Copy defaults from the synchronous client for use here.
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = SpeechClient.DEFAULT_ENDPOINT
DEFAULT_MTLS_ENDPOINT = SpeechClient.DEFAULT_MTLS_ENDPOINT
_DEFAULT_ENDPOINT_TEMPLATE = SpeechClient._DEFAULT_ENDPOINT_TEMPLATE
_DEFAULT_UNIVERSE = SpeechClient._DEFAULT_UNIVERSE
crypto_key_path = staticmethod(SpeechClient.crypto_key_path)
parse_crypto_key_path = staticmethod(SpeechClient.parse_crypto_key_path)
crypto_key_version_path = staticmethod(SpeechClient.crypto_key_version_path)
parse_crypto_key_version_path = staticmethod(
SpeechClient.parse_crypto_key_version_path
)
custom_class_path = staticmethod(SpeechClient.custom_class_path)
parse_custom_class_path = staticmethod(SpeechClient.parse_custom_class_path)
phrase_set_path = staticmethod(SpeechClient.phrase_set_path)
parse_phrase_set_path = staticmethod(SpeechClient.parse_phrase_set_path)
common_billing_account_path = staticmethod(SpeechClient.common_billing_account_path)
parse_common_billing_account_path = staticmethod(
SpeechClient.parse_common_billing_account_path
)
common_folder_path = staticmethod(SpeechClient.common_folder_path)
parse_common_folder_path = staticmethod(SpeechClient.parse_common_folder_path)
common_organization_path = staticmethod(SpeechClient.common_organization_path)
parse_common_organization_path = staticmethod(
SpeechClient.parse_common_organization_path
)
common_project_path = staticmethod(SpeechClient.common_project_path)
parse_common_project_path = staticmethod(SpeechClient.parse_common_project_path)
common_location_path = staticmethod(SpeechClient.common_location_path)
parse_common_location_path = staticmethod(SpeechClient.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:
SpeechAsyncClient: The constructed client.
"""
return SpeechClient.from_service_account_info.__func__(SpeechAsyncClient, 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:
SpeechAsyncClient: The constructed client.
"""
return SpeechClient.from_service_account_file.__func__(SpeechAsyncClient, filename, *args, **kwargs) # type: ignore
from_service_account_json = from_service_account_file
@classmethod
def get_mtls_endpoint_and_cert_source(
cls, client_options: Optional[ClientOptions] = None
):
"""Return the API endpoint and client cert source for mutual TLS.
The client cert source is determined in the following order:
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
client cert source is None.
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
default client cert source exists, use the default one; otherwise the client cert
source is None.
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
default mTLS endpoint; if the environment variable is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
More details can be found at https://google.aip.dev/auth/4114.
Args:
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. Only the `api_endpoint` and `client_cert_source` properties may be used
in this method.
Returns:
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
client cert source to use.
Raises:
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
"""
return SpeechClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
@property
def transport(self) -> SpeechTransport:
"""Returns the transport used by the client instance.
Returns:
SpeechTransport: The transport used by the client instance.
"""
return self._client.transport
@property
def api_endpoint(self):
"""Return the API endpoint used by the client instance.
Returns:
str: The API endpoint used by the client instance.
"""
return self._client._api_endpoint
@property
def universe_domain(self) -> str:
"""Return the universe domain used by the client instance.
Returns:
str: The universe domain used
by the client instance.
"""
return self._client._universe_domain
get_transport_class = SpeechClient.get_transport_class
def __init__(
self,
*,
credentials: Optional[ga_credentials.Credentials] = None,
transport: Optional[
Union[str, SpeechTransport, Callable[..., SpeechTransport]]
] = "grpc_asyncio",
client_options: Optional[ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the speech async 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 (Optional[Union[str,SpeechTransport,Callable[..., SpeechTransport]]]):
The transport to use, or a Callable that constructs and returns a new transport to use.
If a Callable is given, it will be called with the same set of initialization
arguments as used in the SpeechTransport constructor.
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.
1. The ``api_endpoint`` property can be used to override the
default endpoint provided by the client when ``transport`` is
not explicitly provided. Only if this property is not set and
``transport`` was not explicitly provided, the endpoint is
determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
variable, which have one of the following values:
"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).
2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide a client certificate for mTLS 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.
3. The ``universe_domain`` property can be used to override the
default "googleapis.com" universe. Note that ``api_endpoint``
property still takes precedence; and ``universe_domain`` is
currently not supported for mTLS.
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.
"""
self._client = SpeechClient(
credentials=credentials,
transport=transport,
client_options=client_options,
client_info=client_info,
)
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
std_logging.DEBUG
): # pragma: NO COVER
_LOGGER.debug(
"Created client `google.cloud.speech_v1p1beta1.SpeechAsyncClient`.",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Speech",
"universeDomain": getattr(
self._client._transport._credentials, "universe_domain", ""
),
"credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
"credentialsInfo": getattr(
self.transport._credentials, "get_cred_info", lambda: None
)(),
}
if hasattr(self._client._transport, "_credentials")
else {
"serviceName": "google.cloud.speech.v1p1beta1.Speech",
"credentialsType": None,
},
)
async def recognize(
self,
request: Optional[Union[cloud_speech.RecognizeRequest, dict]] = None,
*,
config: Optional[cloud_speech.RecognitionConfig] = None,
audio: Optional[cloud_speech.RecognitionAudio] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> cloud_speech.RecognizeResponse:
r"""Performs synchronous speech recognition: receive
results after all audio has been sent and processed.
.. 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 speech_v1p1beta1
async def sample_recognize():
# Create a client
client = speech_v1p1beta1.SpeechAsyncClient()
# Initialize request argument(s)
config = speech_v1p1beta1.RecognitionConfig()
config.language_code = "language_code_value"
audio = speech_v1p1beta1.RecognitionAudio()
audio.content = b'content_blob'
request = speech_v1p1beta1.RecognizeRequest(
config=config,
audio=audio,
)
# Make the request
response = await client.recognize(request=request)
# Handle the response
print(response)
Args:
request (Optional[Union[google.cloud.speech_v1p1beta1.types.RecognizeRequest, dict]]):
The request object. The top-level message sent by the client for the
``Recognize`` method.
config (:class:`google.cloud.speech_v1p1beta1.types.RecognitionConfig`):
Required. Provides information to the
recognizer that specifies how to process
the request.
This corresponds to the ``config`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
audio (:class:`google.cloud.speech_v1p1beta1.types.RecognitionAudio`):
Required. The audio data to be
recognized.
This corresponds to the ``audio`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
Returns:
google.cloud.speech_v1p1beta1.types.RecognizeResponse:
The only message returned to the client by the Recognize method. It
contains the result as zero or more sequential
SpeechRecognitionResult messages.
"""
# Create or coerce a protobuf request object.
# - Quick check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
flattened_params = [config, audio]
has_flattened_params = (
len([param for param in flattened_params if param is not None]) > 0
)
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# - Use the request object if provided (there's no risk of modifying the input as
# there are no flattened fields), or create one.
if not isinstance(request, cloud_speech.RecognizeRequest):
request = cloud_speech.RecognizeRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if config is not None:
request.config = config
if audio is not None:
request.audio = audio
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._client._transport._wrapped_methods[
self._client._transport.recognize
]
# Validate the universe domain.
self._client._validate_universe_domain()
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def long_running_recognize(
self,
request: Optional[Union[cloud_speech.LongRunningRecognizeRequest, dict]] = None,
*,
config: Optional[cloud_speech.RecognitionConfig] = None,
audio: Optional[cloud_speech.RecognitionAudio] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> operation_async.AsyncOperation:
r"""Performs asynchronous speech recognition: receive results via
the google.longrunning.Operations interface. Returns either an
``Operation.error`` or an ``Operation.response`` which contains
a ``LongRunningRecognizeResponse`` message. For more information
on asynchronous speech recognition, see the
`how-to <https://cloud.google.com/speech-to-text/docs/async-recognize>`__.
.. 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 speech_v1p1beta1
async def sample_long_running_recognize():
# Create a client
client = speech_v1p1beta1.SpeechAsyncClient()
# Initialize request argument(s)
config = speech_v1p1beta1.RecognitionConfig()
config.language_code = "language_code_value"
audio = speech_v1p1beta1.RecognitionAudio()
audio.content = b'content_blob'
request = speech_v1p1beta1.LongRunningRecognizeRequest(
config=config,
audio=audio,
)
# Make the request
operation = client.long_running_recognize(request=request)
print("Waiting for operation to complete...")
response = (await operation).result()
# Handle the response
print(response)
Args:
request (Optional[Union[google.cloud.speech_v1p1beta1.types.LongRunningRecognizeRequest, dict]]):
The request object. The top-level message sent by the client for the
``LongRunningRecognize`` method.
config (:class:`google.cloud.speech_v1p1beta1.types.RecognitionConfig`):
Required. Provides information to the
recognizer that specifies how to process
the request.
This corresponds to the ``config`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
audio (:class:`google.cloud.speech_v1p1beta1.types.RecognitionAudio`):
Required. The audio data to be
recognized.
This corresponds to the ``audio`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
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.speech_v1p1beta1.types.LongRunningRecognizeResponse` The only message returned to the client by the LongRunningRecognize method.
It contains the result as zero or more sequential
SpeechRecognitionResult messages. It is included in
the result.response field of the Operation returned
by the GetOperation call of the
google::longrunning::Operations service.
"""
# Create or coerce a protobuf request object.
# - Quick check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
flattened_params = [config, audio]
has_flattened_params = (
len([param for param in flattened_params if param is not None]) > 0
)
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# - Use the request object if provided (there's no risk of modifying the input as
# there are no flattened fields), or create one.
if not isinstance(request, cloud_speech.LongRunningRecognizeRequest):
request = cloud_speech.LongRunningRecognizeRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if config is not None:
request.config = config
if audio is not None:
request.audio = audio
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._client._transport._wrapped_methods[
self._client._transport.long_running_recognize
]
# Validate the universe domain.
self._client._validate_universe_domain()
# 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_speech.LongRunningRecognizeResponse,
metadata_type=cloud_speech.LongRunningRecognizeMetadata,
)
# Done; return the response.
return response
def streaming_recognize(
self,
requests: Optional[
AsyncIterator[cloud_speech.StreamingRecognizeRequest]
] = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> Awaitable[AsyncIterable[cloud_speech.StreamingRecognizeResponse]]:
r"""Performs bidirectional streaming speech recognition:
receive results while sending audio. This method is only
available via the gRPC API (not REST).
.. 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 speech_v1p1beta1
async def sample_streaming_recognize():
# Create a client
client = speech_v1p1beta1.SpeechAsyncClient()
# Initialize request argument(s)
streaming_config = speech_v1p1beta1.StreamingRecognitionConfig()
streaming_config.config.language_code = "language_code_value"
request = speech_v1p1beta1.StreamingRecognizeRequest(
streaming_config=streaming_config,
)
# This method expects an iterator which contains
# 'speech_v1p1beta1.StreamingRecognizeRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
def request_generator():
for request in requests:
yield request
# Make the request
stream = await client.streaming_recognize(requests=request_generator())
# Handle the response
async for response in stream:
print(response)
Args:
requests (AsyncIterator[`google.cloud.speech_v1p1beta1.types.StreamingRecognizeRequest`]):
The request object AsyncIterator. The top-level message sent by the client for the
``StreamingRecognize`` method. Multiple
``StreamingRecognizeRequest`` messages are sent. The
first message must contain a ``streaming_config``
message and must not contain ``audio_content``. All
subsequent messages must contain ``audio_content`` and
must not contain a ``streaming_config`` message.
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
Returns:
AsyncIterable[google.cloud.speech_v1p1beta1.types.StreamingRecognizeResponse]:
StreamingRecognizeResponse is the only message returned to the client by
StreamingRecognize. A series of zero or more
StreamingRecognizeResponse messages are streamed back
to the client. If there is no recognizable audio, and
single_utterance is set to false, then no messages
are streamed back to the client.
Here's an example of a series of
StreamingRecognizeResponses that might be returned
while processing audio:
1. results { alternatives { transcript: "tube" }
stability: 0.01 }
2. results { alternatives { transcript: "to be a" }
stability: 0.01 }
3. results { alternatives { transcript: "to be" }
stability: 0.9 } results { alternatives {
transcript: " or not to be" } stability: 0.01 }
4.
results { alternatives { transcript: "to be or not to be"
confidence: 0.92 }
alternatives { transcript: "to bee or not to bee" }
is_final: true }
5. results { alternatives { transcript: " that's" }
stability: 0.01 }
6. results { alternatives { transcript: " that is" }
stability: 0.9 } results { alternatives {
transcript: " the question" } stability: 0.01 }
7.
results { alternatives { transcript: " that is the question"
confidence: 0.98 }
alternatives { transcript: " that was the question" }
is_final: true }
Notes:
- Only two of the above responses #4 and #7 contain
final results; they are indicated by
is_final: true. Concatenating these together
generates the full transcript: "to be or not to be
that is the question".
- The others contain interim results. #3 and #6
contain two interim \`results`: the first portion
has a high stability and is less likely to change;
the second portion has a low stability and is very
likely to change. A UI designer might choose to
show only high stability results.
- The specific stability and confidence values shown
above are only for illustrative purposes. Actual
values may vary.
-
In each response, only one of these fields will be set:
error, speech_event_type, or one or more
(repeated) results.
"""
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._client._transport._wrapped_methods[
self._client._transport.streaming_recognize
]
# Validate the universe domain.
self._client._validate_universe_domain()
# Send the request.
response = rpc(
requests,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def list_operations(
self,
request: Optional[operations_pb2.ListOperationsRequest] = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> operations_pb2.ListOperationsResponse:
r"""Lists operations that match the specified filter in the request.
Args:
request (:class:`~.operations_pb2.ListOperationsRequest`):
The request object. Request message for
`ListOperations` method.
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
Returns:
~.operations_pb2.ListOperationsResponse:
Response message for ``ListOperations`` method.
"""
# Create or coerce a protobuf request object.
# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = operations_pb2.ListOperationsRequest(**request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Validate the universe domain.
self._client._validate_universe_domain()
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def get_operation(
self,
request: Optional[operations_pb2.GetOperationRequest] = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> operations_pb2.Operation:
r"""Gets the latest state of a long-running operation.
Args:
request (:class:`~.operations_pb2.GetOperationRequest`):
The request object. Request message for
`GetOperation` method.
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
sent along with the request as metadata. Normally, each value must be of type `str`,
but for metadata keys ending with the suffix `-bin`, the corresponding values must
be of type `bytes`.
Returns:
~.operations_pb2.Operation:
An ``Operation`` object.
"""
# Create or coerce a protobuf request object.
# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = operations_pb2.GetOperationRequest(**request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Validate the universe domain.
self._client._validate_universe_domain()
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def __aenter__(self) -> "SpeechAsyncClient":
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__ = ("SpeechAsyncClient",)

View File

@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 SpeechTransport
from .grpc import SpeechGrpcTransport
from .grpc_asyncio import SpeechGrpcAsyncIOTransport
from .rest import SpeechRestInterceptor, SpeechRestTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]]
_transport_registry["grpc"] = SpeechGrpcTransport
_transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport
_transport_registry["rest"] = SpeechRestTransport
__all__ = (
"SpeechTransport",
"SpeechGrpcTransport",
"SpeechGrpcAsyncIOTransport",
"SpeechRestTransport",
"SpeechRestInterceptor",
)

View File

@@ -0,0 +1,251 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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.speech_v1p1beta1 import gapic_version as package_version
from google.cloud.speech_v1p1beta1.types import cloud_speech
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=package_version.__version__
)
class SpeechTransport(abc.ABC):
"""Abstract transport class for Speech."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
DEFAULT_HOST: str = "speech.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 (default: 'speech.googleapis.com').
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 not hasattr(self, "_ignore_credentials"):
self._ignore_credentials: bool = False
# 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 and not self._ignore_credentials:
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
@property
def host(self):
return self._host
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.recognize: gapic_v1.method.wrap_method(
self.recognize,
default_retry=retries.Retry(
initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=5000.0,
),
default_timeout=5000.0,
client_info=client_info,
),
self.long_running_recognize: gapic_v1.method.wrap_method(
self.long_running_recognize,
default_timeout=5000.0,
client_info=client_info,
),
self.streaming_recognize: gapic_v1.method.wrap_method(
self.streaming_recognize,
default_retry=retries.Retry(
initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=5000.0,
),
default_timeout=5000.0,
client_info=client_info,
),
self.get_operation: gapic_v1.method.wrap_method(
self.get_operation,
default_timeout=None,
client_info=client_info,
),
self.list_operations: gapic_v1.method.wrap_method(
self.list_operations,
default_timeout=None,
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 recognize(
self,
) -> Callable[
[cloud_speech.RecognizeRequest],
Union[
cloud_speech.RecognizeResponse, Awaitable[cloud_speech.RecognizeResponse]
],
]:
raise NotImplementedError()
@property
def long_running_recognize(
self,
) -> Callable[
[cloud_speech.LongRunningRecognizeRequest],
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def streaming_recognize(
self,
) -> Callable[
[cloud_speech.StreamingRecognizeRequest],
Union[
cloud_speech.StreamingRecognizeResponse,
Awaitable[cloud_speech.StreamingRecognizeResponse],
],
]:
raise NotImplementedError()
@property
def list_operations(
self,
) -> Callable[
[operations_pb2.ListOperationsRequest],
Union[
operations_pb2.ListOperationsResponse,
Awaitable[operations_pb2.ListOperationsResponse],
],
]:
raise NotImplementedError()
@property
def get_operation(
self,
) -> Callable[
[operations_pb2.GetOperationRequest],
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def kind(self) -> str:
raise NotImplementedError()
__all__ = ("SpeechTransport",)

View File

@@ -0,0 +1,474 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import logging as std_logging
import pickle
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
from google.protobuf.json_format import MessageToJson
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
from google.cloud.speech_v1p1beta1.types import cloud_speech
from .base import DEFAULT_CLIENT_INFO, SpeechTransport
try:
from google.api_core import client_logging # type: ignore
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
except ImportError: # pragma: NO COVER
CLIENT_LOGGING_SUPPORTED = False
_LOGGER = std_logging.getLogger(__name__)
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
def intercept_unary_unary(self, continuation, client_call_details, request):
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
std_logging.DEBUG
)
if logging_enabled: # pragma: NO COVER
request_metadata = client_call_details.metadata
if isinstance(request, proto.Message):
request_payload = type(request).to_json(request)
elif isinstance(request, google.protobuf.message.Message):
request_payload = MessageToJson(request)
else:
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
request_metadata = {
key: value.decode("utf-8") if isinstance(value, bytes) else value
for key, value in request_metadata
}
grpc_request = {
"payload": request_payload,
"requestMethod": "grpc",
"metadata": dict(request_metadata),
}
_LOGGER.debug(
f"Sending request for {client_call_details.method}",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Speech",
"rpcName": client_call_details.method,
"request": grpc_request,
"metadata": grpc_request["metadata"],
},
)
response = continuation(client_call_details, request)
if logging_enabled: # pragma: NO COVER
response_metadata = response.trailing_metadata()
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
metadata = (
dict([(k, str(v)) for k, v in response_metadata])
if response_metadata
else None
)
result = response.result()
if isinstance(result, proto.Message):
response_payload = type(result).to_json(result)
elif isinstance(result, google.protobuf.message.Message):
response_payload = MessageToJson(result)
else:
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
grpc_response = {
"payload": response_payload,
"metadata": metadata,
"status": "OK",
}
_LOGGER.debug(
f"Received response for {client_call_details.method}.",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Speech",
"rpcName": client_call_details.method,
"response": grpc_response,
"metadata": grpc_response["metadata"],
},
)
return response
class SpeechGrpcTransport(SpeechTransport):
"""gRPC backend transport for Speech.
Service that implements Google Cloud 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 = "speech.googleapis.com",
credentials: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: Optional[Union[grpc.Channel, Callable[..., 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 (default: 'speech.googleapis.com').
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 a ``channel`` instance 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 a ``channel`` instance is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if a ``channel`` instance is provided.
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
A ``Channel`` instance through which to make calls, or a Callable
that constructs and returns one. If set to None, ``self.create_channel``
is used to create the channel. If a Callable is given, it will be called
with the same arguments as used in ``self.create_channel``.
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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
credentials = None
self._ignore_credentials = True
# 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:
# initialize with the provided callable or the default channel
channel_init = channel or type(self).create_channel
self._grpc_channel = channel_init(
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),
],
)
self._interceptor = _LoggingClientInterceptor()
self._logged_channel = grpc.intercept_channel(
self._grpc_channel, self._interceptor
)
# Wrap messages. This must be done after self._logged_channel exists
self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "speech.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._logged_channel
)
# Return the client from cache.
return self._operations_client
@property
def recognize(
self,
) -> Callable[[cloud_speech.RecognizeRequest], cloud_speech.RecognizeResponse]:
r"""Return a callable for the recognize method over gRPC.
Performs synchronous speech recognition: receive
results after all audio has been sent and processed.
Returns:
Callable[[~.RecognizeRequest],
~.RecognizeResponse]:
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 "recognize" not in self._stubs:
self._stubs["recognize"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Speech/Recognize",
request_serializer=cloud_speech.RecognizeRequest.serialize,
response_deserializer=cloud_speech.RecognizeResponse.deserialize,
)
return self._stubs["recognize"]
@property
def long_running_recognize(
self,
) -> Callable[[cloud_speech.LongRunningRecognizeRequest], operations_pb2.Operation]:
r"""Return a callable for the long running recognize method over gRPC.
Performs asynchronous speech recognition: receive results via
the google.longrunning.Operations interface. Returns either an
``Operation.error`` or an ``Operation.response`` which contains
a ``LongRunningRecognizeResponse`` message. For more information
on asynchronous speech recognition, see the
`how-to <https://cloud.google.com/speech-to-text/docs/async-recognize>`__.
Returns:
Callable[[~.LongRunningRecognizeRequest],
~.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 "long_running_recognize" not in self._stubs:
self._stubs["long_running_recognize"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Speech/LongRunningRecognize",
request_serializer=cloud_speech.LongRunningRecognizeRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["long_running_recognize"]
@property
def streaming_recognize(
self,
) -> Callable[
[cloud_speech.StreamingRecognizeRequest],
cloud_speech.StreamingRecognizeResponse,
]:
r"""Return a callable for the streaming recognize method over gRPC.
Performs bidirectional streaming speech recognition:
receive results while sending audio. This method is only
available via the gRPC API (not REST).
Returns:
Callable[[~.StreamingRecognizeRequest],
~.StreamingRecognizeResponse]:
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 "streaming_recognize" not in self._stubs:
self._stubs["streaming_recognize"] = self._logged_channel.stream_stream(
"/google.cloud.speech.v1p1beta1.Speech/StreamingRecognize",
request_serializer=cloud_speech.StreamingRecognizeRequest.serialize,
response_deserializer=cloud_speech.StreamingRecognizeResponse.deserialize,
)
return self._stubs["streaming_recognize"]
def close(self):
self._logged_channel.close()
@property
def get_operation(
self,
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
r"""Return a callable for the get_operation method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_operation" not in self._stubs:
self._stubs["get_operation"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/GetOperation",
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["get_operation"]
@property
def list_operations(
self,
) -> Callable[
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
]:
r"""Return a callable for the list_operations method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_operations" not in self._stubs:
self._stubs["list_operations"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/ListOperations",
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
)
return self._stubs["list_operations"]
@property
def kind(self) -> str:
return "grpc"
__all__ = ("SpeechGrpcTransport",)

View File

@@ -0,0 +1,540 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 inspect
import json
import logging as std_logging
import pickle
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, grpc_helpers_async, operations_v1
from google.api_core import retry_async as retries
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
from google.protobuf.json_format import MessageToJson
import google.protobuf.message
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
import proto # type: ignore
from google.cloud.speech_v1p1beta1.types import cloud_speech
from .base import DEFAULT_CLIENT_INFO, SpeechTransport
from .grpc import SpeechGrpcTransport
try:
from google.api_core import client_logging # type: ignore
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
except ImportError: # pragma: NO COVER
CLIENT_LOGGING_SUPPORTED = False
_LOGGER = std_logging.getLogger(__name__)
class _LoggingClientAIOInterceptor(
grpc.aio.UnaryUnaryClientInterceptor
): # pragma: NO COVER
async def intercept_unary_unary(self, continuation, client_call_details, request):
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
std_logging.DEBUG
)
if logging_enabled: # pragma: NO COVER
request_metadata = client_call_details.metadata
if isinstance(request, proto.Message):
request_payload = type(request).to_json(request)
elif isinstance(request, google.protobuf.message.Message):
request_payload = MessageToJson(request)
else:
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
request_metadata = {
key: value.decode("utf-8") if isinstance(value, bytes) else value
for key, value in request_metadata
}
grpc_request = {
"payload": request_payload,
"requestMethod": "grpc",
"metadata": dict(request_metadata),
}
_LOGGER.debug(
f"Sending request for {client_call_details.method}",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Speech",
"rpcName": str(client_call_details.method),
"request": grpc_request,
"metadata": grpc_request["metadata"],
},
)
response = await continuation(client_call_details, request)
if logging_enabled: # pragma: NO COVER
response_metadata = await response.trailing_metadata()
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
metadata = (
dict([(k, str(v)) for k, v in response_metadata])
if response_metadata
else None
)
result = await response
if isinstance(result, proto.Message):
response_payload = type(result).to_json(result)
elif isinstance(result, google.protobuf.message.Message):
response_payload = MessageToJson(result)
else:
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
grpc_response = {
"payload": response_payload,
"metadata": metadata,
"status": "OK",
}
_LOGGER.debug(
f"Received response to rpc {client_call_details.method}.",
extra={
"serviceName": "google.cloud.speech.v1p1beta1.Speech",
"rpcName": str(client_call_details.method),
"response": grpc_response,
"metadata": grpc_response["metadata"],
},
)
return response
class SpeechGrpcAsyncIOTransport(SpeechTransport):
"""gRPC AsyncIO backend transport for Speech.
Service that implements Google Cloud 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 = "speech.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`.
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 = "speech.googleapis.com",
credentials: Optional[ga_credentials.Credentials] = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: Optional[Union[aio.Channel, Callable[..., 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 (default: 'speech.googleapis.com').
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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]):
A ``Channel`` instance through which to make calls, or a Callable
that constructs and returns one. If set to None, ``self.create_channel``
is used to create the channel. If a Callable is given, it will be called
with the same arguments as used in ``self.create_channel``.
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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
credentials = None
self._ignore_credentials = True
# 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:
# initialize with the provided callable or the default channel
channel_init = channel or type(self).create_channel
self._grpc_channel = channel_init(
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),
],
)
self._interceptor = _LoggingClientAIOInterceptor()
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
self._logged_channel = self._grpc_channel
self._wrap_with_kind = (
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
)
# Wrap messages. This must be done after self._logged_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._logged_channel
)
# Return the client from cache.
return self._operations_client
@property
def recognize(
self,
) -> Callable[
[cloud_speech.RecognizeRequest], Awaitable[cloud_speech.RecognizeResponse]
]:
r"""Return a callable for the recognize method over gRPC.
Performs synchronous speech recognition: receive
results after all audio has been sent and processed.
Returns:
Callable[[~.RecognizeRequest],
Awaitable[~.RecognizeResponse]]:
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 "recognize" not in self._stubs:
self._stubs["recognize"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Speech/Recognize",
request_serializer=cloud_speech.RecognizeRequest.serialize,
response_deserializer=cloud_speech.RecognizeResponse.deserialize,
)
return self._stubs["recognize"]
@property
def long_running_recognize(
self,
) -> Callable[
[cloud_speech.LongRunningRecognizeRequest], Awaitable[operations_pb2.Operation]
]:
r"""Return a callable for the long running recognize method over gRPC.
Performs asynchronous speech recognition: receive results via
the google.longrunning.Operations interface. Returns either an
``Operation.error`` or an ``Operation.response`` which contains
a ``LongRunningRecognizeResponse`` message. For more information
on asynchronous speech recognition, see the
`how-to <https://cloud.google.com/speech-to-text/docs/async-recognize>`__.
Returns:
Callable[[~.LongRunningRecognizeRequest],
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 "long_running_recognize" not in self._stubs:
self._stubs["long_running_recognize"] = self._logged_channel.unary_unary(
"/google.cloud.speech.v1p1beta1.Speech/LongRunningRecognize",
request_serializer=cloud_speech.LongRunningRecognizeRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["long_running_recognize"]
@property
def streaming_recognize(
self,
) -> Callable[
[cloud_speech.StreamingRecognizeRequest],
Awaitable[cloud_speech.StreamingRecognizeResponse],
]:
r"""Return a callable for the streaming recognize method over gRPC.
Performs bidirectional streaming speech recognition:
receive results while sending audio. This method is only
available via the gRPC API (not REST).
Returns:
Callable[[~.StreamingRecognizeRequest],
Awaitable[~.StreamingRecognizeResponse]]:
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 "streaming_recognize" not in self._stubs:
self._stubs["streaming_recognize"] = self._logged_channel.stream_stream(
"/google.cloud.speech.v1p1beta1.Speech/StreamingRecognize",
request_serializer=cloud_speech.StreamingRecognizeRequest.serialize,
response_deserializer=cloud_speech.StreamingRecognizeResponse.deserialize,
)
return self._stubs["streaming_recognize"]
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
self.recognize: self._wrap_method(
self.recognize,
default_retry=retries.AsyncRetry(
initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=5000.0,
),
default_timeout=5000.0,
client_info=client_info,
),
self.long_running_recognize: self._wrap_method(
self.long_running_recognize,
default_timeout=5000.0,
client_info=client_info,
),
self.streaming_recognize: self._wrap_method(
self.streaming_recognize,
default_retry=retries.AsyncRetry(
initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=5000.0,
),
default_timeout=5000.0,
client_info=client_info,
),
self.get_operation: self._wrap_method(
self.get_operation,
default_timeout=None,
client_info=client_info,
),
self.list_operations: self._wrap_method(
self.list_operations,
default_timeout=None,
client_info=client_info,
),
}
def _wrap_method(self, func, *args, **kwargs):
if self._wrap_with_kind: # pragma: NO COVER
kwargs["kind"] = self.kind
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
def close(self):
return self._logged_channel.close()
@property
def kind(self) -> str:
return "grpc_asyncio"
@property
def get_operation(
self,
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
r"""Return a callable for the get_operation method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_operation" not in self._stubs:
self._stubs["get_operation"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/GetOperation",
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["get_operation"]
@property
def list_operations(
self,
) -> Callable[
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
]:
r"""Return a callable for the list_operations method over gRPC."""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_operations" not in self._stubs:
self._stubs["list_operations"] = self._logged_channel.unary_unary(
"/google.longrunning.Operations/ListOperations",
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
)
return self._stubs["list_operations"]
__all__ = ("SpeechGrpcAsyncIOTransport",)

View File

@@ -0,0 +1,260 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json # type: ignore
import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1, path_template
from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import json_format
from google.cloud.speech_v1p1beta1.types import cloud_speech
from .base import DEFAULT_CLIENT_INFO, SpeechTransport
class _BaseSpeechRestTransport(SpeechTransport):
"""Base REST backend transport for Speech.
Note: This class is not meant to be used directly. Use its sync and
async sub-classes instead.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
"""
def __init__(
self,
*,
host: str = "speech.googleapis.com",
credentials: Optional[Any] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
url_scheme: str = "https",
api_audience: Optional[str] = None,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to (default: 'speech.googleapis.com').
credentials (Optional[Any]): 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.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you are developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
url_scheme: the protocol scheme for the API endpoint. Normally
"https", but for testing or local servers,
"http" can be specified.
"""
# Run the base constructor
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
if maybe_url_match is None:
raise ValueError(
f"Unexpected hostname structure: {host}"
) # pragma: NO COVER
url_match_items = maybe_url_match.groupdict()
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
api_audience=api_audience,
)
class _BaseLongRunningRecognize:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1p1beta1/speech:longrunningrecognize",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech.LongRunningRecognizeRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSpeechRestTransport._BaseLongRunningRecognize._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseRecognize:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/v1p1beta1/speech:recognize",
"body": "*",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
pb_request = cloud_speech.RecognizeRequest.pb(request)
transcoded_request = path_template.transcode(http_options, pb_request)
return transcoded_request
@staticmethod
def _get_request_body_json(transcoded_request):
# Jsonify the request body
body = json_format.MessageToJson(
transcoded_request["body"], use_integers_for_enums=True
)
return body
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(
json_format.MessageToJson(
transcoded_request["query_params"],
use_integers_for_enums=True,
)
)
query_params.update(
_BaseSpeechRestTransport._BaseRecognize._get_unset_required_fields(
query_params
)
)
query_params["$alt"] = "json;enum-encoding=int"
return query_params
class _BaseStreamingRecognize:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
class _BaseGetOperation:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/operations/{name=**}",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
request_kwargs = json_format.MessageToDict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
return query_params
class _BaseListOperations:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@staticmethod
def _get_http_options():
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/v1p1beta1/operations",
},
]
return http_options
@staticmethod
def _get_transcoded_request(http_options, request):
request_kwargs = json_format.MessageToDict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
return transcoded_request
@staticmethod
def _get_query_params_json(transcoded_request):
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
return query_params
__all__ = ("_BaseSpeechRestTransport",)

View File

@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT 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 .cloud_speech import (
LongRunningRecognizeMetadata,
LongRunningRecognizeRequest,
LongRunningRecognizeResponse,
RecognitionAudio,
RecognitionConfig,
RecognitionMetadata,
RecognizeRequest,
RecognizeResponse,
SpeakerDiarizationConfig,
SpeechAdaptationInfo,
SpeechContext,
SpeechRecognitionAlternative,
SpeechRecognitionResult,
StreamingRecognitionConfig,
StreamingRecognitionResult,
StreamingRecognizeRequest,
StreamingRecognizeResponse,
TranscriptOutputConfig,
WordInfo,
)
from .cloud_speech_adaptation import (
CreateCustomClassRequest,
CreatePhraseSetRequest,
DeleteCustomClassRequest,
DeletePhraseSetRequest,
GetCustomClassRequest,
GetPhraseSetRequest,
ListCustomClassesRequest,
ListCustomClassesResponse,
ListPhraseSetRequest,
ListPhraseSetResponse,
UpdateCustomClassRequest,
UpdatePhraseSetRequest,
)
from .resource import CustomClass, PhraseSet, SpeechAdaptation, TranscriptNormalization
__all__ = (
"LongRunningRecognizeMetadata",
"LongRunningRecognizeRequest",
"LongRunningRecognizeResponse",
"RecognitionAudio",
"RecognitionConfig",
"RecognitionMetadata",
"RecognizeRequest",
"RecognizeResponse",
"SpeakerDiarizationConfig",
"SpeechAdaptationInfo",
"SpeechContext",
"SpeechRecognitionAlternative",
"SpeechRecognitionResult",
"StreamingRecognitionConfig",
"StreamingRecognitionResult",
"StreamingRecognizeRequest",
"StreamingRecognizeResponse",
"TranscriptOutputConfig",
"WordInfo",
"CreateCustomClassRequest",
"CreatePhraseSetRequest",
"DeleteCustomClassRequest",
"DeletePhraseSetRequest",
"GetCustomClassRequest",
"GetPhraseSetRequest",
"ListCustomClassesRequest",
"ListCustomClassesResponse",
"ListPhraseSetRequest",
"ListPhraseSetResponse",
"UpdateCustomClassRequest",
"UpdatePhraseSetRequest",
"CustomClass",
"PhraseSet",
"SpeechAdaptation",
"TranscriptNormalization",
)

View File

@@ -0,0 +1,422 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
from typing import MutableMapping, MutableSequence
from google.protobuf import field_mask_pb2 # type: ignore
import proto # type: ignore
from google.cloud.speech_v1p1beta1.types import resource
__protobuf__ = proto.module(
package="google.cloud.speech.v1p1beta1",
manifest={
"CreatePhraseSetRequest",
"UpdatePhraseSetRequest",
"GetPhraseSetRequest",
"ListPhraseSetRequest",
"ListPhraseSetResponse",
"DeletePhraseSetRequest",
"CreateCustomClassRequest",
"UpdateCustomClassRequest",
"GetCustomClassRequest",
"ListCustomClassesRequest",
"ListCustomClassesResponse",
"DeleteCustomClassRequest",
},
)
class CreatePhraseSetRequest(proto.Message):
r"""Message sent by the client for the ``CreatePhraseSet`` method.
Attributes:
parent (str):
Required. The parent resource where this phrase set will be
created. Format:
``projects/{project}/locations/{location}``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
phrase_set_id (str):
Required. The ID to use for the phrase set,
which will become the final component of the
phrase set's resource name.
This value should restrict to letters, numbers,
and hyphens, with the first character a letter,
the last a letter or a number, and be 4-63
characters.
phrase_set (google.cloud.speech_v1p1beta1.types.PhraseSet):
Required. The phrase set to create.
"""
parent: str = proto.Field(
proto.STRING,
number=1,
)
phrase_set_id: str = proto.Field(
proto.STRING,
number=2,
)
phrase_set: resource.PhraseSet = proto.Field(
proto.MESSAGE,
number=3,
message=resource.PhraseSet,
)
class UpdatePhraseSetRequest(proto.Message):
r"""Message sent by the client for the ``UpdatePhraseSet`` method.
Attributes:
phrase_set (google.cloud.speech_v1p1beta1.types.PhraseSet):
Required. The phrase set to update.
The phrase set's ``name`` field is used to identify the set
to be updated. Format:
``projects/{project}/locations/{location}/phraseSets/{phrase_set}``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
The list of fields to be updated.
"""
phrase_set: resource.PhraseSet = proto.Field(
proto.MESSAGE,
number=1,
message=resource.PhraseSet,
)
update_mask: field_mask_pb2.FieldMask = proto.Field(
proto.MESSAGE,
number=2,
message=field_mask_pb2.FieldMask,
)
class GetPhraseSetRequest(proto.Message):
r"""Message sent by the client for the ``GetPhraseSet`` method.
Attributes:
name (str):
Required. The name of the phrase set to retrieve. Format:
``projects/{project}/locations/{location}/phraseSets/{phrase_set}``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
"""
name: str = proto.Field(
proto.STRING,
number=1,
)
class ListPhraseSetRequest(proto.Message):
r"""Message sent by the client for the ``ListPhraseSet`` method.
Attributes:
parent (str):
Required. The parent, which owns this collection of phrase
set. Format:
``projects/{project}/locations/{location}``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
page_size (int):
The maximum number of phrase sets to return.
The service may return fewer than this value. If
unspecified, at most 50 phrase sets will be
returned. The maximum value is 1000; values
above 1000 will be coerced to 1000.
page_token (str):
A page token, received from a previous ``ListPhraseSet``
call. Provide this to retrieve the subsequent page.
When paginating, all other parameters provided to
``ListPhraseSet`` must match the call that provided the page
token.
"""
parent: str = proto.Field(
proto.STRING,
number=1,
)
page_size: int = proto.Field(
proto.INT32,
number=2,
)
page_token: str = proto.Field(
proto.STRING,
number=3,
)
class ListPhraseSetResponse(proto.Message):
r"""Message returned to the client by the ``ListPhraseSet`` method.
Attributes:
phrase_sets (MutableSequence[google.cloud.speech_v1p1beta1.types.PhraseSet]):
The phrase set.
next_page_token (str):
A token, which can be sent as ``page_token`` to retrieve the
next page. If this field is omitted, there are no subsequent
pages.
"""
@property
def raw_page(self):
return self
phrase_sets: MutableSequence[resource.PhraseSet] = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=resource.PhraseSet,
)
next_page_token: str = proto.Field(
proto.STRING,
number=2,
)
class DeletePhraseSetRequest(proto.Message):
r"""Message sent by the client for the ``DeletePhraseSet`` method.
Attributes:
name (str):
Required. The name of the phrase set to delete. Format:
``projects/{project}/locations/{location}/phraseSets/{phrase_set}``
"""
name: str = proto.Field(
proto.STRING,
number=1,
)
class CreateCustomClassRequest(proto.Message):
r"""Message sent by the client for the ``CreateCustomClass`` method.
Attributes:
parent (str):
Required. The parent resource where this custom class will
be created. Format:
``projects/{project}/locations/{location}/customClasses``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
custom_class_id (str):
Required. The ID to use for the custom class,
which will become the final component of the
custom class' resource name.
This value should restrict to letters, numbers,
and hyphens, with the first character a letter,
the last a letter or a number, and be 4-63
characters.
custom_class (google.cloud.speech_v1p1beta1.types.CustomClass):
Required. The custom class to create.
"""
parent: str = proto.Field(
proto.STRING,
number=1,
)
custom_class_id: str = proto.Field(
proto.STRING,
number=2,
)
custom_class: resource.CustomClass = proto.Field(
proto.MESSAGE,
number=3,
message=resource.CustomClass,
)
class UpdateCustomClassRequest(proto.Message):
r"""Message sent by the client for the ``UpdateCustomClass`` method.
Attributes:
custom_class (google.cloud.speech_v1p1beta1.types.CustomClass):
Required. The custom class to update.
The custom class's ``name`` field is used to identify the
custom class to be updated. Format:
``projects/{project}/locations/{location}/customClasses/{custom_class}``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
The list of fields to be updated.
"""
custom_class: resource.CustomClass = proto.Field(
proto.MESSAGE,
number=1,
message=resource.CustomClass,
)
update_mask: field_mask_pb2.FieldMask = proto.Field(
proto.MESSAGE,
number=2,
message=field_mask_pb2.FieldMask,
)
class GetCustomClassRequest(proto.Message):
r"""Message sent by the client for the ``GetCustomClass`` method.
Attributes:
name (str):
Required. The name of the custom class to retrieve. Format:
``projects/{project}/locations/{location}/customClasses/{custom_class}``
"""
name: str = proto.Field(
proto.STRING,
number=1,
)
class ListCustomClassesRequest(proto.Message):
r"""Message sent by the client for the ``ListCustomClasses`` method.
Attributes:
parent (str):
Required. The parent, which owns this collection of custom
classes. Format:
``projects/{project}/locations/{location}/customClasses``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
page_size (int):
The maximum number of custom classes to
return. The service may return fewer than this
value. If unspecified, at most 50 custom classes
will be returned. The maximum value is 1000;
values above 1000 will be coerced to 1000.
page_token (str):
A page token, received from a previous ``ListCustomClass``
call. Provide this to retrieve the subsequent page.
When paginating, all other parameters provided to
``ListCustomClass`` must match the call that provided the
page token.
"""
parent: str = proto.Field(
proto.STRING,
number=1,
)
page_size: int = proto.Field(
proto.INT32,
number=2,
)
page_token: str = proto.Field(
proto.STRING,
number=3,
)
class ListCustomClassesResponse(proto.Message):
r"""Message returned to the client by the ``ListCustomClasses`` method.
Attributes:
custom_classes (MutableSequence[google.cloud.speech_v1p1beta1.types.CustomClass]):
The custom classes.
next_page_token (str):
A token, which can be sent as ``page_token`` to retrieve the
next page. If this field is omitted, there are no subsequent
pages.
"""
@property
def raw_page(self):
return self
custom_classes: MutableSequence[resource.CustomClass] = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=resource.CustomClass,
)
next_page_token: str = proto.Field(
proto.STRING,
number=2,
)
class DeleteCustomClassRequest(proto.Message):
r"""Message sent by the client for the ``DeleteCustomClass`` method.
Attributes:
name (str):
Required. The name of the custom class to delete. Format:
``projects/{project}/locations/{location}/customClasses/{custom_class}``
Speech-to-Text supports three locations: ``global``, ``us``
(US North America), and ``eu`` (Europe). If you are calling
the ``speech.googleapis.com`` endpoint, use the ``global``
location. To specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
"""
name: str = proto.Field(
proto.STRING,
number=1,
)
__all__ = tuple(sorted(__protobuf__.manifest))

View File

@@ -0,0 +1,495 @@
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
from typing import MutableMapping, MutableSequence
from google.protobuf import timestamp_pb2 # type: ignore
import proto # type: ignore
__protobuf__ = proto.module(
package="google.cloud.speech.v1p1beta1",
manifest={
"CustomClass",
"PhraseSet",
"SpeechAdaptation",
"TranscriptNormalization",
},
)
class CustomClass(proto.Message):
r"""A set of words or phrases that represents a common concept
likely to appear in your audio, for example a list of passenger
ship names. CustomClass items can be substituted into
placeholders that you set in PhraseSet phrases.
Attributes:
name (str):
The resource name of the custom class.
custom_class_id (str):
If this custom class is a resource, the custom_class_id is
the resource id of the CustomClass. Case sensitive.
items (MutableSequence[google.cloud.speech_v1p1beta1.types.CustomClass.ClassItem]):
A collection of class items.
kms_key_name (str):
Output only. The `KMS key
name <https://cloud.google.com/kms/docs/resource-hierarchy#keys>`__
with which the content of the ClassItem is encrypted. The
expected format is
``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``.
kms_key_version_name (str):
Output only. The `KMS key version
name <https://cloud.google.com/kms/docs/resource-hierarchy#key_versions>`__
with which content of the ClassItem is encrypted. The
expected format is
``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}``.
uid (str):
Output only. System-assigned unique
identifier for the CustomClass. This field is
not used.
display_name (str):
Output only. User-settable, human-readable
name for the CustomClass. Must be 63 characters
or less. This field is not used.
state (google.cloud.speech_v1p1beta1.types.CustomClass.State):
Output only. The CustomClass lifecycle state.
This field is not used.
delete_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time at which this resource
was requested for deletion. This field is not
used.
expire_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time at which this resource
will be purged. This field is not used.
annotations (MutableMapping[str, str]):
Output only. Allows users to store small
amounts of arbitrary data. Both the key and the
value must be 63 characters or less each. At
most 100 annotations.
This field is not used.
etag (str):
Output only. This checksum is computed by the
server based on the value of other fields. This
may be sent on update, undelete, and delete
requests to ensure the client has an up-to-date
value before proceeding. This field is not used.
reconciling (bool):
Output only. Whether or not this CustomClass
is in the process of being updated. This field
is not used.
"""
class State(proto.Enum):
r"""Set of states that define the lifecycle of a CustomClass.
Values:
STATE_UNSPECIFIED (0):
Unspecified state. This is only used/useful
for distinguishing unset values.
ACTIVE (2):
The normal and active state.
DELETED (4):
This CustomClass has been deleted.
"""
STATE_UNSPECIFIED = 0
ACTIVE = 2
DELETED = 4
class ClassItem(proto.Message):
r"""An item of the class.
Attributes:
value (str):
The class item's value.
"""
value: str = proto.Field(
proto.STRING,
number=1,
)
name: str = proto.Field(
proto.STRING,
number=1,
)
custom_class_id: str = proto.Field(
proto.STRING,
number=2,
)
items: MutableSequence[ClassItem] = proto.RepeatedField(
proto.MESSAGE,
number=3,
message=ClassItem,
)
kms_key_name: str = proto.Field(
proto.STRING,
number=6,
)
kms_key_version_name: str = proto.Field(
proto.STRING,
number=7,
)
uid: str = proto.Field(
proto.STRING,
number=8,
)
display_name: str = proto.Field(
proto.STRING,
number=9,
)
state: State = proto.Field(
proto.ENUM,
number=10,
enum=State,
)
delete_time: timestamp_pb2.Timestamp = proto.Field(
proto.MESSAGE,
number=11,
message=timestamp_pb2.Timestamp,
)
expire_time: timestamp_pb2.Timestamp = proto.Field(
proto.MESSAGE,
number=12,
message=timestamp_pb2.Timestamp,
)
annotations: MutableMapping[str, str] = proto.MapField(
proto.STRING,
proto.STRING,
number=13,
)
etag: str = proto.Field(
proto.STRING,
number=14,
)
reconciling: bool = proto.Field(
proto.BOOL,
number=15,
)
class PhraseSet(proto.Message):
r"""Provides "hints" to the speech recognizer to favor specific
words and phrases in the results.
Attributes:
name (str):
The resource name of the phrase set.
phrases (MutableSequence[google.cloud.speech_v1p1beta1.types.PhraseSet.Phrase]):
A list of word and phrases.
boost (float):
Hint Boost. Positive value will increase the probability
that a specific phrase will be recognized over other similar
sounding phrases. The higher the boost, the higher the
chance of false positive recognition as well. Negative boost
values would correspond to anti-biasing. Anti-biasing is not
enabled, so negative boost will simply be ignored. Though
``boost`` can accept a wide range of positive values, most
use cases are best served with values between 0 (exclusive)
and 20. We recommend using a binary search approach to
finding the optimal value for your use case as well as
adding phrases both with and without boost to your requests.
kms_key_name (str):
Output only. The `KMS key
name <https://cloud.google.com/kms/docs/resource-hierarchy#keys>`__
with which the content of the PhraseSet is encrypted. The
expected format is
``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``.
kms_key_version_name (str):
Output only. The `KMS key version
name <https://cloud.google.com/kms/docs/resource-hierarchy#key_versions>`__
with which content of the PhraseSet is encrypted. The
expected format is
``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}``.
uid (str):
Output only. System-assigned unique
identifier for the PhraseSet. This field is not
used.
display_name (str):
Output only. User-settable, human-readable
name for the PhraseSet. Must be 63 characters or
less. This field is not used.
state (google.cloud.speech_v1p1beta1.types.PhraseSet.State):
Output only. The CustomClass lifecycle state.
This field is not used.
delete_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time at which this resource
was requested for deletion. This field is not
used.
expire_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time at which this resource
will be purged. This field is not used.
annotations (MutableMapping[str, str]):
Output only. Allows users to store small
amounts of arbitrary data. Both the key and the
value must be 63 characters or less each. At
most 100 annotations.
This field is not used.
etag (str):
Output only. This checksum is computed by the
server based on the value of other fields. This
may be sent on update, undelete, and delete
requests to ensure the client has an up-to-date
value before proceeding. This field is not used.
reconciling (bool):
Output only. Whether or not this PhraseSet is
in the process of being updated. This field is
not used.
"""
class State(proto.Enum):
r"""Set of states that define the lifecycle of a CustomClass.
Values:
STATE_UNSPECIFIED (0):
Unspecified state. This is only used/useful
for distinguishing unset values.
ACTIVE (2):
The normal and active state.
DELETED (4):
This CustomClass has been deleted.
"""
STATE_UNSPECIFIED = 0
ACTIVE = 2
DELETED = 4
class Phrase(proto.Message):
r"""A phrases containing words and phrase "hints" so that the speech
recognition is more likely to recognize them. This can be used to
improve the accuracy for specific words and phrases, for example, if
specific commands are typically spoken by the user. This can also be
used to add additional words to the vocabulary of the recognizer.
See `usage
limits <https://cloud.google.com/speech-to-text/quotas#content>`__.
List items can also include pre-built or custom classes containing
groups of words that represent common concepts that occur in natural
language. For example, rather than providing a phrase hint for every
month of the year (e.g. "i was born in january", "i was born in
febuary", ...), use the pre-built ``$MONTH`` class improves the
likelihood of correctly transcribing audio that includes months
(e.g. "i was born in $month"). To refer to pre-built classes, use
the class' symbol prepended with ``$`` e.g. ``$MONTH``. To refer to
custom classes that were defined inline in the request, set the
class's ``custom_class_id`` to a string unique to all class
resources and inline classes. Then use the class' id wrapped in
$\ ``{...}`` e.g. "${my-months}". To refer to custom classes
resources, use the class' id wrapped in ``${}`` (e.g.
``${my-months}``).
Speech-to-Text supports three locations: ``global``, ``us`` (US
North America), and ``eu`` (Europe). If you are calling the
``speech.googleapis.com`` endpoint, use the ``global`` location. To
specify a region, use a `regional
endpoint <https://cloud.google.com/speech-to-text/docs/endpoints>`__
with matching ``us`` or ``eu`` location value.
Attributes:
value (str):
The phrase itself.
boost (float):
Hint Boost. Overrides the boost set at the phrase set level.
Positive value will increase the probability that a specific
phrase will be recognized over other similar sounding
phrases. The higher the boost, the higher the chance of
false positive recognition as well. Negative boost will
simply be ignored. Though ``boost`` can accept a wide range
of positive values, most use cases are best served with
values between 0 and 20. We recommend using a binary search
approach to finding the optimal value for your use case as
well as adding phrases both with and without boost to your
requests.
"""
value: str = proto.Field(
proto.STRING,
number=1,
)
boost: float = proto.Field(
proto.FLOAT,
number=2,
)
name: str = proto.Field(
proto.STRING,
number=1,
)
phrases: MutableSequence[Phrase] = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=Phrase,
)
boost: float = proto.Field(
proto.FLOAT,
number=4,
)
kms_key_name: str = proto.Field(
proto.STRING,
number=7,
)
kms_key_version_name: str = proto.Field(
proto.STRING,
number=8,
)
uid: str = proto.Field(
proto.STRING,
number=9,
)
display_name: str = proto.Field(
proto.STRING,
number=10,
)
state: State = proto.Field(
proto.ENUM,
number=11,
enum=State,
)
delete_time: timestamp_pb2.Timestamp = proto.Field(
proto.MESSAGE,
number=12,
message=timestamp_pb2.Timestamp,
)
expire_time: timestamp_pb2.Timestamp = proto.Field(
proto.MESSAGE,
number=13,
message=timestamp_pb2.Timestamp,
)
annotations: MutableMapping[str, str] = proto.MapField(
proto.STRING,
proto.STRING,
number=14,
)
etag: str = proto.Field(
proto.STRING,
number=15,
)
reconciling: bool = proto.Field(
proto.BOOL,
number=16,
)
class SpeechAdaptation(proto.Message):
r"""Speech adaptation configuration.
Attributes:
phrase_sets (MutableSequence[google.cloud.speech_v1p1beta1.types.PhraseSet]):
A collection of phrase sets. To specify the hints inline,
leave the phrase set's ``name`` blank and fill in the rest
of its fields. Any phrase set can use any custom class.
phrase_set_references (MutableSequence[str]):
A collection of phrase set resource names to
use.
custom_classes (MutableSequence[google.cloud.speech_v1p1beta1.types.CustomClass]):
A collection of custom classes. To specify the classes
inline, leave the class' ``name`` blank and fill in the rest
of its fields, giving it a unique ``custom_class_id``. Refer
to the inline defined class in phrase hints by its
``custom_class_id``.
abnf_grammar (google.cloud.speech_v1p1beta1.types.SpeechAdaptation.ABNFGrammar):
Augmented Backus-Naur form (ABNF) is a
standardized grammar notation comprised by a set
of derivation rules. See specifications:
https://www.w3.org/TR/speech-grammar
"""
class ABNFGrammar(proto.Message):
r"""
Attributes:
abnf_strings (MutableSequence[str]):
All declarations and rules of an ABNF grammar
broken up into multiple strings that will end up
concatenated.
"""
abnf_strings: MutableSequence[str] = proto.RepeatedField(
proto.STRING,
number=1,
)
phrase_sets: MutableSequence["PhraseSet"] = proto.RepeatedField(
proto.MESSAGE,
number=1,
message="PhraseSet",
)
phrase_set_references: MutableSequence[str] = proto.RepeatedField(
proto.STRING,
number=2,
)
custom_classes: MutableSequence["CustomClass"] = proto.RepeatedField(
proto.MESSAGE,
number=3,
message="CustomClass",
)
abnf_grammar: ABNFGrammar = proto.Field(
proto.MESSAGE,
number=4,
message=ABNFGrammar,
)
class TranscriptNormalization(proto.Message):
r"""Transcription normalization configuration. Use transcription
normalization to automatically replace parts of the transcript
with phrases of your choosing. For StreamingRecognize, this
normalization only applies to stable partial transcripts
(stability > 0.8) and final transcripts.
Attributes:
entries (MutableSequence[google.cloud.speech_v1p1beta1.types.TranscriptNormalization.Entry]):
A list of replacement entries. We will perform replacement
with one entry at a time. For example, the second entry in
["cat" => "dog", "mountain cat" => "mountain dog"] will
never be applied because we will always process the first
entry before it. At most 100 entries.
"""
class Entry(proto.Message):
r"""A single replacement configuration.
Attributes:
search (str):
What to replace. Max length is 100
characters.
replace (str):
What to replace with. Max length is 100
characters.
case_sensitive (bool):
Whether the search is case sensitive.
"""
search: str = proto.Field(
proto.STRING,
number=1,
)
replace: str = proto.Field(
proto.STRING,
number=2,
)
case_sensitive: bool = proto.Field(
proto.BOOL,
number=3,
)
entries: MutableSequence[Entry] = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=Entry,
)
__all__ = tuple(sorted(__protobuf__.manifest))