diff --git a/.gitattributes b/.gitattributes index 54dee2eb7aaf7a80cc32c5ae26e98f4e09fbb77b..804414352feffd368697a10a629e6462931da8d5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -424,3 +424,7 @@ loan-advisor-agent/.venv/Lib/site-packages/google/cloud/aiplatform_v1beta1/servi loan-advisor-agent/.venv/Lib/site-packages/google/cloud/aiplatform_v1beta1/types/__pycache__/evaluation_service.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text loan-advisor-agent/.venv/Lib/site-packages/google/cloud/resourcemanager_v3/services/folders/transports/__pycache__/rest.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text loan-advisor-agent/.venv/Lib/site-packages/google/cloud/resourcemanager_v3/services/projects/transports/__pycache__/rest.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/blob.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/bucket.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/models.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/types.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7251a3b061c92de867ebbdadc989a40acfeab8fb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..b90cf895608b994ca51253259d4e4e713793dd81 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/base.py @@ -0,0 +1,340 @@ +# -*- 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 +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.speech_v1 import gapic_version as package_version +from google.cloud.speech_v1.types import cloud_speech_adaptation, resource + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b4f06622a7e6c4267fcc6aa57fc274e59b5da5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/grpc.py @@ -0,0 +1,649 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +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 + +from google.cloud.speech_v1.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)!r}" + + 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.v1.Adaptation", + "rpcName": str(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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.speech.v1.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..3176348d4b99734bebd2faecc9a739de0763b2a8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/grpc_asyncio.py @@ -0,0 +1,739 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.speech_v1.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)!r}" + + 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.v1.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 `` 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)!r}" + 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.v1.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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.v1.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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..78507f7459aeb497adc857804d70c0af2900e661 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/rest.py @@ -0,0 +1,2575 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.speech_v1.types import cloud_speech_adaptation, resource + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAdaptationRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AdaptationRestInterceptor: + """Interceptor for Adaptation. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AdaptationRestTransport. + + .. code-block:: python + class MyCustomAdaptationInterceptor(AdaptationRestInterceptor): + def pre_create_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_classes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_classes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AdaptationRestTransport(interceptor=MyCustomAdaptationInterceptor()) + client = AdaptationClient(transport=transport) + + + """ + + def pre_create_custom_class( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.CreateCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for create_custom_class + + DEPRECATED. Please use the `post_create_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_create_custom_class` interceptor runs + before the `post_create_custom_class_with_metadata` interceptor. + """ + return response + + def post_create_custom_class_with_metadata( + self, + response: resource.CustomClass, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.CustomClass, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_create_custom_class_with_metadata` + interceptor in new development instead of the `post_create_custom_class` interceptor. + When both interceptors are used, this `post_create_custom_class_with_metadata` interceptor runs after the + `post_create_custom_class` interceptor. The (possibly modified) response returned by + `post_create_custom_class` will be passed to + `post_create_custom_class_with_metadata`. + """ + return response, metadata + + def pre_create_phrase_set( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.CreatePhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for create_phrase_set + + DEPRECATED. Please use the `post_create_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_create_phrase_set` interceptor runs + before the `post_create_phrase_set_with_metadata` interceptor. + """ + return response + + def post_create_phrase_set_with_metadata( + self, + response: resource.PhraseSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.PhraseSet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_create_phrase_set_with_metadata` + interceptor in new development instead of the `post_create_phrase_set` interceptor. + When both interceptors are used, this `post_create_phrase_set_with_metadata` interceptor runs after the + `post_create_phrase_set` interceptor. The (possibly modified) response returned by + `post_create_phrase_set` will be passed to + `post_create_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_delete_custom_class( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.DeleteCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_delete_phrase_set( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.DeletePhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_get_custom_class( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.GetCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for get_custom_class + + DEPRECATED. Please use the `post_get_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_get_custom_class` interceptor runs + before the `post_get_custom_class_with_metadata` interceptor. + """ + return response + + def post_get_custom_class_with_metadata( + self, + response: resource.CustomClass, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.CustomClass, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_get_custom_class_with_metadata` + interceptor in new development instead of the `post_get_custom_class` interceptor. + When both interceptors are used, this `post_get_custom_class_with_metadata` interceptor runs after the + `post_get_custom_class` interceptor. The (possibly modified) response returned by + `post_get_custom_class` will be passed to + `post_get_custom_class_with_metadata`. + """ + return response, metadata + + def pre_get_phrase_set( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.GetPhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_phrase_set(self, response: resource.PhraseSet) -> resource.PhraseSet: + """Post-rpc interceptor for get_phrase_set + + DEPRECATED. Please use the `post_get_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_get_phrase_set` interceptor runs + before the `post_get_phrase_set_with_metadata` interceptor. + """ + return response + + def post_get_phrase_set_with_metadata( + self, + response: resource.PhraseSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.PhraseSet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_get_phrase_set_with_metadata` + interceptor in new development instead of the `post_get_phrase_set` interceptor. + When both interceptors are used, this `post_get_phrase_set_with_metadata` interceptor runs after the + `post_get_phrase_set` interceptor. The (possibly modified) response returned by + `post_get_phrase_set` will be passed to + `post_get_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_list_custom_classes( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListCustomClassesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_custom_classes( + self, response: cloud_speech_adaptation.ListCustomClassesResponse + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + """Post-rpc interceptor for list_custom_classes + + DEPRECATED. Please use the `post_list_custom_classes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_list_custom_classes` interceptor runs + before the `post_list_custom_classes_with_metadata` interceptor. + """ + return response + + def post_list_custom_classes_with_metadata( + self, + response: cloud_speech_adaptation.ListCustomClassesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListCustomClassesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_custom_classes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_list_custom_classes_with_metadata` + interceptor in new development instead of the `post_list_custom_classes` interceptor. + When both interceptors are used, this `post_list_custom_classes_with_metadata` interceptor runs after the + `post_list_custom_classes` interceptor. The (possibly modified) response returned by + `post_list_custom_classes` will be passed to + `post_list_custom_classes_with_metadata`. + """ + return response, metadata + + def pre_list_phrase_set( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListPhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_phrase_set( + self, response: cloud_speech_adaptation.ListPhraseSetResponse + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + """Post-rpc interceptor for list_phrase_set + + DEPRECATED. Please use the `post_list_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_list_phrase_set` interceptor runs + before the `post_list_phrase_set_with_metadata` interceptor. + """ + return response + + def post_list_phrase_set_with_metadata( + self, + response: cloud_speech_adaptation.ListPhraseSetResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListPhraseSetResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_list_phrase_set_with_metadata` + interceptor in new development instead of the `post_list_phrase_set` interceptor. + When both interceptors are used, this `post_list_phrase_set_with_metadata` interceptor runs after the + `post_list_phrase_set` interceptor. The (possibly modified) response returned by + `post_list_phrase_set` will be passed to + `post_list_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_update_custom_class( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.UpdateCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for update_custom_class + + DEPRECATED. Please use the `post_update_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_update_custom_class` interceptor runs + before the `post_update_custom_class_with_metadata` interceptor. + """ + return response + + def post_update_custom_class_with_metadata( + self, + response: resource.CustomClass, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.CustomClass, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_update_custom_class_with_metadata` + interceptor in new development instead of the `post_update_custom_class` interceptor. + When both interceptors are used, this `post_update_custom_class_with_metadata` interceptor runs after the + `post_update_custom_class` interceptor. The (possibly modified) response returned by + `post_update_custom_class` will be passed to + `post_update_custom_class_with_metadata`. + """ + return response, metadata + + def pre_update_phrase_set( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.UpdatePhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for update_phrase_set + + DEPRECATED. Please use the `post_update_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_update_phrase_set` interceptor runs + before the `post_update_phrase_set_with_metadata` interceptor. + """ + return response + + def post_update_phrase_set_with_metadata( + self, + response: resource.PhraseSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.PhraseSet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_update_phrase_set_with_metadata` + interceptor in new development instead of the `post_update_phrase_set` interceptor. + When both interceptors are used, this `post_update_phrase_set_with_metadata` interceptor runs after the + `post_update_phrase_set` interceptor. The (possibly modified) response returned by + `post_update_phrase_set` will be passed to + `post_update_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AdaptationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AdaptationRestInterceptor + + +class AdaptationRestTransport(_BaseAdaptationRestTransport): + """REST backend synchronous 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 JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AdaptationRestInterceptor] = None, + 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. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AdaptationRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AdaptationRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCustomClass( + _BaseAdaptationRestTransport._BaseCreateCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.CreateCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Call the create custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreateCustomClassRequest): + The request object. Message sent by the client for the ``CreateCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.CustomClass: + 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. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseCreateCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseCreateCustomClass._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseCreateCustomClass._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseCreateCustomClass._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.CreateCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "CreateCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._CreateCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.CustomClass.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.create_custom_class", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "CreateCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreatePhraseSet( + _BaseAdaptationRestTransport._BaseCreatePhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.CreatePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Call the create phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreatePhraseSetRequest): + The request object. Message sent by the client for the ``CreatePhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_phrase_set( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.CreatePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "CreatePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._CreatePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.PhraseSet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.create_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "CreatePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteCustomClass( + _BaseAdaptationRestTransport._BaseDeleteCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.DeleteCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeleteCustomClassRequest): + The request object. Message sent by the client for the ``DeleteCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseDeleteCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseDeleteCustomClass._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseDeleteCustomClass._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.DeleteCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "DeleteCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._DeleteCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeletePhraseSet( + _BaseAdaptationRestTransport._BaseDeletePhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.DeletePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeletePhraseSetRequest): + The request object. Message sent by the client for the ``DeletePhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseDeletePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_phrase_set( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseDeletePhraseSet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseDeletePhraseSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.DeletePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "DeletePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._DeletePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetCustomClass( + _BaseAdaptationRestTransport._BaseGetCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.GetCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Call the get custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetCustomClassRequest): + The request object. Message sent by the client for the ``GetCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.CustomClass: + 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. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseGetCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseGetCustomClass._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseGetCustomClass._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.GetCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "GetCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._GetCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.CustomClass.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.get_custom_class", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "GetCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPhraseSet( + _BaseAdaptationRestTransport._BaseGetPhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.GetPhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Call the get phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetPhraseSetRequest): + The request object. Message sent by the client for the ``GetPhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseGetPhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_phrase_set(request, metadata) + transcoded_request = ( + _BaseAdaptationRestTransport._BaseGetPhraseSet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseGetPhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.GetPhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "GetPhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._GetPhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.PhraseSet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.get_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "GetPhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListCustomClasses( + _BaseAdaptationRestTransport._BaseListCustomClasses, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.ListCustomClasses") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + r"""Call the list custom classes method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListCustomClassesRequest): + The request object. Message sent by the client for the ``ListCustomClasses`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech_adaptation.ListCustomClassesResponse: + Message returned to the client by the + ``ListCustomClasses`` method. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseListCustomClasses._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_custom_classes( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseListCustomClasses._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseListCustomClasses._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.ListCustomClasses", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "ListCustomClasses", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._ListCustomClasses._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech_adaptation.ListCustomClassesResponse() + pb_resp = cloud_speech_adaptation.ListCustomClassesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_custom_classes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_custom_classes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cloud_speech_adaptation.ListCustomClassesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.list_custom_classes", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "ListCustomClasses", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPhraseSet( + _BaseAdaptationRestTransport._BaseListPhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.ListPhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + r"""Call the list phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListPhraseSetRequest): + The request object. Message sent by the client for the ``ListPhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech_adaptation.ListPhraseSetResponse: + Message returned to the client by the ``ListPhraseSet`` + method. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseListPhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_phrase_set(request, metadata) + transcoded_request = ( + _BaseAdaptationRestTransport._BaseListPhraseSet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseListPhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.ListPhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "ListPhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._ListPhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech_adaptation.ListPhraseSetResponse() + pb_resp = cloud_speech_adaptation.ListPhraseSetResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cloud_speech_adaptation.ListPhraseSetResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.list_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "ListPhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCustomClass( + _BaseAdaptationRestTransport._BaseUpdateCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.UpdateCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Call the update custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdateCustomClassRequest): + The request object. Message sent by the client for the ``UpdateCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.CustomClass: + 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. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.UpdateCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "UpdateCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._UpdateCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.CustomClass.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.update_custom_class", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "UpdateCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePhraseSet( + _BaseAdaptationRestTransport._BaseUpdatePhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.UpdatePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Call the update phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdatePhraseSetRequest): + The request object. Message sent by the client for the ``UpdatePhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_phrase_set( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.UpdatePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "UpdatePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._UpdatePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.PhraseSet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationClient.update_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "UpdatePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.CreateCustomClassRequest], resource.CustomClass + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.CreatePhraseSetRequest], resource.PhraseSet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_custom_class( + self, + ) -> Callable[[cloud_speech_adaptation.DeleteCustomClassRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.DeletePhraseSetRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.GetCustomClassRequest], resource.CustomClass + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.GetPhraseSetRequest], resource.PhraseSet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListCustomClassesRequest], + cloud_speech_adaptation.ListCustomClassesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCustomClasses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_phrase_set( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListPhraseSetRequest], + cloud_speech_adaptation.ListPhraseSetResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.UpdateCustomClassRequest], resource.CustomClass + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.UpdatePhraseSetRequest], resource.PhraseSet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseAdaptationRestTransport._BaseGetOperation, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: Response from GetOperation method. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseAdaptationRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseAdaptationRestTransport._BaseListOperations, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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 from ListOperations method. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseAdaptationRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.AdaptationClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.AdaptationAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1.Adaptation", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AdaptationRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..05172bed6774a7374afc726b5f1dc34df8c9da7a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/adaptation/transports/rest_base.py @@ -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 + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +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_v1.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("^(?Phttp(?:s)?://)?(?P.*)$", 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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/{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": "/v1/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": "/v1/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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46fd4742bf9bf09f5d77f5b776940109094160b2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e4d1717bbdd98ad850986e27b11ba0167935dc0b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/async_client.py @@ -0,0 +1,860 @@ +# -*- 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +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_v1 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 + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.speech_v1.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 + + 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. + """ + sa_info_func = ( + SpeechClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SpeechAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SpeechAsyncClient: The constructed client. + """ + sa_file_func = ( + SpeechClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(SpeechAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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) -> str: + """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_v1.SpeechAsyncClient`.", + extra={ + "serviceName": "google.cloud.speech.v1.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.v1.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_v1 + + async def sample_recognize(): + # Create a client + client = speech_v1.SpeechAsyncClient() + + # Initialize request argument(s) + config = speech_v1.RecognitionConfig() + config.language_code = "language_code_value" + + audio = speech_v1.RecognitionAudio() + audio.content = b'content_blob' + + request = speech_v1.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_v1.types.RecognizeRequest, dict]]): + The request object. The top-level message sent by the client for the + ``Recognize`` method. + config (:class:`google.cloud.speech_v1.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_v1.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_v1.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 `__. + + .. 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_v1 + + async def sample_long_running_recognize(): + # Create a client + client = speech_v1.SpeechAsyncClient() + + # Initialize request argument(s) + config = speech_v1.RecognitionConfig() + config.language_code = "language_code_value" + + audio = speech_v1.RecognitionAudio() + audio.content = b'content_blob' + + request = speech_v1.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_v1.types.LongRunningRecognizeRequest, dict]]): + The request object. The top-level message sent by the client for the + ``LongRunningRecognize`` method. + config (:class:`google.cloud.speech_v1.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_v1.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_v1.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_v1 + + async def sample_streaming_recognize(): + # Create a client + client = speech_v1.SpeechAsyncClient() + + # Initialize request argument(s) + streaming_config = speech_v1.StreamingRecognitionConfig() + streaming_config.config.language_code = "language_code_value" + + request = speech_v1.StreamingRecognizeRequest( + streaming_config=streaming_config, + ) + + # This method expects an iterator which contains + # 'speech_v1.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_v1.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_v1.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 + \`StreamingRecognizeResponse`s 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[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SpeechAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/client.py new file mode 100644 index 0000000000000000000000000000000000000000..74a6e588753722b7e1f3b827b14d8d627fbaa0a6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/client.py @@ -0,0 +1,1324 @@ +# -*- 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 os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.speech_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.speech_v1.types import cloud_speech + +from .transports.base import DEFAULT_CLIENT_INFO, SpeechTransport +from .transports.grpc import SpeechGrpcTransport +from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport +from .transports.rest import SpeechRestTransport + + +class SpeechClientMeta(type): + """Metaclass for the Speech client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] + _transport_registry["grpc"] = SpeechGrpcTransport + _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport + _transport_registry["rest"] = SpeechRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SpeechTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SpeechClient(metaclass=SpeechClientMeta): + """Service that implements Google Cloud Speech API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "speech.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "speech.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + SpeechClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SpeechClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SpeechTransport: + """Returns the transport used by the client instance. + + Returns: + SpeechTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def custom_class_path( + project: str, + location: str, + custom_class: str, + ) -> str: + """Returns a fully-qualified custom_class string.""" + return "projects/{project}/locations/{location}/customClasses/{custom_class}".format( + project=project, + location=location, + custom_class=custom_class, + ) + + @staticmethod + def parse_custom_class_path(path: str) -> Dict[str, str]: + """Parses a custom_class path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/customClasses/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def phrase_set_path( + project: str, + location: str, + phrase_set: str, + ) -> str: + """Returns a fully-qualified phrase_set string.""" + return "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( + project=project, + location=location, + phrase_set=phrase_set, + ) + + @staticmethod + def parse_phrase_set_path(path: str) -> Dict[str, str]: + """Parses a phrase_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/phraseSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. 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. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = SpeechClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = SpeechClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SpeechClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SpeechClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SpeechClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SpeechClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._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._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SpeechTransport, Callable[..., SpeechTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the speech 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. + 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 the ``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_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + SpeechClient._read_environment_variables() + ) + self._client_cert_source = SpeechClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SpeechClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SpeechTransport) + if transport_provided: + # transport is a SpeechTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(SpeechTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or SpeechClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SpeechTransport], Callable[..., SpeechTransport] + ] = ( + SpeechClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SpeechTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.speech_v1.SpeechClient`.", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.speech.v1.Speech", + "credentialsType": None, + }, + ) + + 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_v1 + + def sample_recognize(): + # Create a client + client = speech_v1.SpeechClient() + + # Initialize request argument(s) + config = speech_v1.RecognitionConfig() + config.language_code = "language_code_value" + + audio = speech_v1.RecognitionAudio() + audio.content = b'content_blob' + + request = speech_v1.RecognizeRequest( + config=config, + audio=audio, + ) + + # Make the request + response = client.recognize(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1.types.RecognizeRequest, dict]): + The request object. The top-level message sent by the client for the + ``Recognize`` method. + config (google.cloud.speech_v1.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 (google.cloud.speech_v1.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.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`. + + Returns: + google.cloud.speech_v1.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._transport._wrapped_methods[self._transport.recognize] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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.Operation: + 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 `__. + + .. 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_v1 + + def sample_long_running_recognize(): + # Create a client + client = speech_v1.SpeechClient() + + # Initialize request argument(s) + config = speech_v1.RecognitionConfig() + config.language_code = "language_code_value" + + audio = speech_v1.RecognitionAudio() + audio.content = b'content_blob' + + request = speech_v1.LongRunningRecognizeRequest( + config=config, + audio=audio, + ) + + # Make the request + operation = client.long_running_recognize(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1.types.LongRunningRecognizeRequest, dict]): + The request object. The top-level message sent by the client for the + ``LongRunningRecognize`` method. + config (google.cloud.speech_v1.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 (google.cloud.speech_v1.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.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`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v1.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._transport._wrapped_methods[self._transport.long_running_recognize] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.LongRunningRecognizeResponse, + metadata_type=cloud_speech.LongRunningRecognizeMetadata, + ) + + # Done; return the response. + return response + + def streaming_recognize( + self, + requests: Optional[Iterator[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]]] = (), + ) -> Iterable[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_v1 + + def sample_streaming_recognize(): + # Create a client + client = speech_v1.SpeechClient() + + # Initialize request argument(s) + streaming_config = speech_v1.StreamingRecognitionConfig() + streaming_config.config.language_code = "language_code_value" + + request = speech_v1.StreamingRecognizeRequest( + streaming_config=streaming_config, + ) + + # This method expects an iterator which contains + # 'speech_v1.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 = client.streaming_recognize(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.speech_v1.types.StreamingRecognizeRequest]): + The request object iterator. 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.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`. + + Returns: + Iterable[google.cloud.speech_v1.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 + \`StreamingRecognizeResponse`s 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._transport._wrapped_methods[self._transport.streaming_recognize] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SpeechClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SpeechClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5150a365b2d2d5454e96bdaf2968ca4dc59ba6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1f93025596745c5c654f1ce4c2ae95aeca3b92 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/base.py @@ -0,0 +1,265 @@ +# -*- 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 +import google.auth # type: ignore +import google.protobuf +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 +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_v1 import gapic_version as package_version +from google.cloud.speech_v1.types import cloud_speech + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff898585e789bca62562985e3bd84009c760d38 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/grpc.py @@ -0,0 +1,479 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.speech_v1.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)!r}" + + 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.v1.Speech", + "rpcName": str(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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.speech.v1.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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.v1.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 `__. + + 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.v1.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.v1.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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..60cf4177af933ae77530de7212affd19af953a00 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py @@ -0,0 +1,546 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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 +from grpc.experimental import aio # type: ignore + +from google.cloud.speech_v1.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)!r}" + + 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.v1.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 `` 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)!r}" + 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.v1.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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.v1.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 `__. + + 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.v1.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.v1.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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..a2340d073f9f7b604912263c993ca42750d91dff --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/rest.py @@ -0,0 +1,1023 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.speech_v1.types import cloud_speech + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSpeechRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SpeechRestInterceptor: + """Interceptor for Speech. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SpeechRestTransport. + + .. code-block:: python + class MyCustomSpeechInterceptor(SpeechRestInterceptor): + def pre_long_running_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_long_running_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SpeechRestTransport(interceptor=MyCustomSpeechInterceptor()) + client = SpeechClient(transport=transport) + + + """ + + def pre_long_running_recognize( + self, + request: cloud_speech.LongRunningRecognizeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.LongRunningRecognizeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for long_running_recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_long_running_recognize( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for long_running_recognize + + DEPRECATED. Please use the `post_long_running_recognize_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_long_running_recognize` interceptor runs + before the `post_long_running_recognize_with_metadata` interceptor. + """ + return response + + def post_long_running_recognize_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for long_running_recognize + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_long_running_recognize_with_metadata` + interceptor in new development instead of the `post_long_running_recognize` interceptor. + When both interceptors are used, this `post_long_running_recognize_with_metadata` interceptor runs after the + `post_long_running_recognize` interceptor. The (possibly modified) response returned by + `post_long_running_recognize` will be passed to + `post_long_running_recognize_with_metadata`. + """ + return response, metadata + + def pre_recognize( + self, + request: cloud_speech.RecognizeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.RecognizeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_recognize( + self, response: cloud_speech.RecognizeResponse + ) -> cloud_speech.RecognizeResponse: + """Post-rpc interceptor for recognize + + DEPRECATED. Please use the `post_recognize_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_recognize` interceptor runs + before the `post_recognize_with_metadata` interceptor. + """ + return response + + def post_recognize_with_metadata( + self, + response: cloud_speech.RecognizeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.RecognizeResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for recognize + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_recognize_with_metadata` + interceptor in new development instead of the `post_recognize` interceptor. + When both interceptors are used, this `post_recognize_with_metadata` interceptor runs after the + `post_recognize` interceptor. The (possibly modified) response returned by + `post_recognize` will be passed to + `post_recognize_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SpeechRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SpeechRestInterceptor + + +class SpeechRestTransport(_BaseSpeechRestTransport): + """REST backend synchronous 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 JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SpeechRestInterceptor] = None, + 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. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[SpeechRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SpeechRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/operations/{name=**}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _LongRunningRecognize( + _BaseSpeechRestTransport._BaseLongRunningRecognize, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.LongRunningRecognize") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.LongRunningRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the long running recognize method over HTTP. + + Args: + request (~.cloud_speech.LongRunningRecognizeRequest): + The request object. The top-level message sent by the client for the + ``LongRunningRecognize`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseLongRunningRecognize._get_http_options() + ) + + request, metadata = self._interceptor.pre_long_running_recognize( + request, metadata + ) + transcoded_request = _BaseSpeechRestTransport._BaseLongRunningRecognize._get_transcoded_request( + http_options, request + ) + + body = _BaseSpeechRestTransport._BaseLongRunningRecognize._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSpeechRestTransport._BaseLongRunningRecognize._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.SpeechClient.LongRunningRecognize", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "LongRunningRecognize", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._LongRunningRecognize._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_long_running_recognize(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_long_running_recognize_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.SpeechClient.long_running_recognize", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "LongRunningRecognize", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Recognize(_BaseSpeechRestTransport._BaseRecognize, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.Recognize") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.RecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.RecognizeResponse: + r"""Call the recognize method over HTTP. + + Args: + request (~.cloud_speech.RecognizeRequest): + The request object. The top-level message sent by the client for the + ``Recognize`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.RecognizeResponse: + The only message returned to the client by the + ``Recognize`` method. It contains the result as zero or + more sequential ``SpeechRecognitionResult`` messages. + + """ + + http_options = _BaseSpeechRestTransport._BaseRecognize._get_http_options() + + request, metadata = self._interceptor.pre_recognize(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseRecognize._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseRecognize._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseRecognize._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.SpeechClient.Recognize", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "Recognize", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._Recognize._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.RecognizeResponse() + pb_resp = cloud_speech.RecognizeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_recognize(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_recognize_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.RecognizeResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.SpeechClient.recognize", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "Recognize", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StreamingRecognize( + _BaseSpeechRestTransport._BaseStreamingRecognize, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.StreamingRecognize") + + def __call__( + self, + request: cloud_speech.StreamingRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamingRecognize is not available over REST transport" + ) + + @property + def long_running_recognize( + self, + ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._LongRunningRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def recognize( + self, + ) -> Callable[[cloud_speech.RecognizeRequest], cloud_speech.RecognizeResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Recognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def streaming_recognize( + self, + ) -> Callable[ + [cloud_speech.StreamingRecognizeRequest], + cloud_speech.StreamingRecognizeResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StreamingRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseSpeechRestTransport._BaseGetOperation, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: Response from GetOperation method. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.SpeechClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.SpeechAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseSpeechRestTransport._BaseListOperations, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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 from ListOperations method. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1.SpeechClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1.SpeechAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1.Speech", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SpeechRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..62eeaded63b47850ac5e8478b251fc6d48e9ed81 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/services/speech/transports/rest_base.py @@ -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_v1.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("^(?Phttp(?:s)?://)?(?P.*)$", 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": "/v1/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": "/v1/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": "/v1/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": "/v1/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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9be07ebb5897000fc532bdfa0af40ba709af0d28 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/__init__.py @@ -0,0 +1,94 @@ +# -*- 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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/cloud_speech.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/cloud_speech.py new file mode 100644 index 0000000000000000000000000000000000000000..d53880a0d01d7cbbcd77dbe70cf2378011087188 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/cloud_speech.py @@ -0,0 +1,1560 @@ +# -*- 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 + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.speech_v1.types import resource + +__protobuf__ = proto.module( + package="google.cloud.speech.v1", + manifest={ + "RecognizeRequest", + "LongRunningRecognizeRequest", + "TranscriptOutputConfig", + "StreamingRecognizeRequest", + "StreamingRecognitionConfig", + "RecognitionConfig", + "SpeakerDiarizationConfig", + "RecognitionMetadata", + "SpeechContext", + "RecognitionAudio", + "RecognizeResponse", + "LongRunningRecognizeResponse", + "LongRunningRecognizeMetadata", + "StreamingRecognizeResponse", + "StreamingRecognitionResult", + "SpeechRecognitionResult", + "SpeechRecognitionAlternative", + "WordInfo", + "SpeechAdaptationInfo", + }, +) + + +class RecognizeRequest(proto.Message): + r"""The top-level message sent by the client for the ``Recognize`` + method. + + Attributes: + config (google.cloud.speech_v1.types.RecognitionConfig): + Required. Provides information to the + recognizer that specifies how to process the + request. + audio (google.cloud.speech_v1.types.RecognitionAudio): + Required. The audio data to be recognized. + """ + + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + audio: "RecognitionAudio" = proto.Field( + proto.MESSAGE, + number=2, + message="RecognitionAudio", + ) + + +class LongRunningRecognizeRequest(proto.Message): + r"""The top-level message sent by the client for the + ``LongRunningRecognize`` method. + + Attributes: + config (google.cloud.speech_v1.types.RecognitionConfig): + Required. Provides information to the + recognizer that specifies how to process the + request. + audio (google.cloud.speech_v1.types.RecognitionAudio): + Required. The audio data to be recognized. + output_config (google.cloud.speech_v1.types.TranscriptOutputConfig): + Optional. Specifies an optional destination + for the recognition results. + """ + + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + audio: "RecognitionAudio" = proto.Field( + proto.MESSAGE, + number=2, + message="RecognitionAudio", + ) + output_config: "TranscriptOutputConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="TranscriptOutputConfig", + ) + + +class TranscriptOutputConfig(proto.Message): + r"""Specifies an optional destination for the recognition + results. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_uri (str): + Specifies a Cloud Storage URI for the recognition results. + Must be specified in the format: + ``gs://bucket_name/object_name``, and the bucket must + already exist. + + This field is a member of `oneof`_ ``output_type``. + """ + + gcs_uri: str = proto.Field( + proto.STRING, + number=1, + oneof="output_type", + ) + + +class StreamingRecognizeRequest(proto.Message): + r"""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. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + streaming_config (google.cloud.speech_v1.types.StreamingRecognitionConfig): + Provides information to the recognizer that specifies how to + process the request. The first ``StreamingRecognizeRequest`` + message must contain a ``streaming_config`` message. + + This field is a member of `oneof`_ ``streaming_request``. + audio_content (bytes): + The audio data to be recognized. Sequential chunks of audio + data are sent in sequential ``StreamingRecognizeRequest`` + messages. The first ``StreamingRecognizeRequest`` message + must not contain ``audio_content`` data and all subsequent + ``StreamingRecognizeRequest`` messages must contain + ``audio_content`` data. The audio bytes must be encoded as + specified in ``RecognitionConfig``. Note: as with all bytes + fields, proto buffers use a pure binary representation (not + base64). See `content + limits `__. + + This field is a member of `oneof`_ ``streaming_request``. + """ + + streaming_config: "StreamingRecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="streaming_request", + message="StreamingRecognitionConfig", + ) + audio_content: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="streaming_request", + ) + + +class StreamingRecognitionConfig(proto.Message): + r"""Provides information to the recognizer that specifies how to + process the request. + + Attributes: + config (google.cloud.speech_v1.types.RecognitionConfig): + Required. Provides information to the + recognizer that specifies how to process the + request. + single_utterance (bool): + If ``false`` or omitted, the recognizer will perform + continuous recognition (continuing to wait for and process + audio even if the user pauses speaking) until the client + closes the input stream (gRPC API) or until the maximum time + limit has been reached. May return multiple + ``StreamingRecognitionResult``\ s with the ``is_final`` flag + set to ``true``. + + If ``true``, the recognizer will detect a single spoken + utterance. When it detects that the user has paused or + stopped speaking, it will return an + ``END_OF_SINGLE_UTTERANCE`` event and cease recognition. It + will return no more than one ``StreamingRecognitionResult`` + with the ``is_final`` flag set to ``true``. + + The ``single_utterance`` field can only be used with + specified models, otherwise an error is thrown. The + ``model`` field in [``RecognitionConfig``][] must be set to: + + - ``command_and_search`` + - ``phone_call`` AND additional field + ``useEnhanced``\ =\ ``true`` + - The ``model`` field is left undefined. In this case the + API auto-selects a model based on any other parameters + that you set in ``RecognitionConfig``. + interim_results (bool): + If ``true``, interim results (tentative hypotheses) may be + returned as they become available (these interim results are + indicated with the ``is_final=false`` flag). If ``false`` or + omitted, only ``is_final=true`` result(s) are returned. + enable_voice_activity_events (bool): + If ``true``, responses with voice activity speech events + will be returned as they are detected. + voice_activity_timeout (google.cloud.speech_v1.types.StreamingRecognitionConfig.VoiceActivityTimeout): + If set, the server will automatically close the stream after + the specified duration has elapsed after the last + VOICE_ACTIVITY speech event has been sent. The field + ``voice_activity_events`` must also be set to true. + """ + + class VoiceActivityTimeout(proto.Message): + r"""Events that a timeout can be set on for voice activity. + + Attributes: + speech_start_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream if no speech + begins. + speech_end_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream after speech + ends. + """ + + speech_start_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + speech_end_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + single_utterance: bool = proto.Field( + proto.BOOL, + number=2, + ) + interim_results: bool = proto.Field( + proto.BOOL, + number=3, + ) + enable_voice_activity_events: bool = proto.Field( + proto.BOOL, + number=5, + ) + voice_activity_timeout: VoiceActivityTimeout = proto.Field( + proto.MESSAGE, + number=6, + message=VoiceActivityTimeout, + ) + + +class RecognitionConfig(proto.Message): + r"""Provides information to the recognizer that specifies how to + process the request. + + Attributes: + encoding (google.cloud.speech_v1.types.RecognitionConfig.AudioEncoding): + Encoding of audio data sent in all ``RecognitionAudio`` + messages. This field is optional for ``FLAC`` and ``WAV`` + audio files and required for all other audio formats. For + details, see + [AudioEncoding][google.cloud.speech.v1.RecognitionConfig.AudioEncoding]. + sample_rate_hertz (int): + Sample rate in Hertz of the audio data sent in all + ``RecognitionAudio`` messages. Valid values are: 8000-48000. + 16000 is optimal. For best results, set the sampling rate of + the audio source to 16000 Hz. If that's not possible, use + the native sample rate of the audio source (instead of + re-sampling). This field is optional for FLAC and WAV audio + files, but is required for all other audio formats. For + details, see + [AudioEncoding][google.cloud.speech.v1.RecognitionConfig.AudioEncoding]. + audio_channel_count (int): + The number of channels in the input audio data. ONLY set + this for MULTI-CHANNEL recognition. Valid values for + LINEAR16, OGG_OPUS and FLAC are ``1``-``8``. Valid value for + MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only ``1``. + If ``0`` or omitted, defaults to one channel (mono). Note: + We only recognize the first channel by default. To perform + independent recognition on each channel set + ``enable_separate_recognition_per_channel`` to 'true'. + enable_separate_recognition_per_channel (bool): + This needs to be set to ``true`` explicitly and + ``audio_channel_count`` > 1 to get each channel recognized + separately. The recognition result will contain a + ``channel_tag`` field to state which channel that result + belongs to. If this is not true, we will only recognize the + first channel. The request is billed cumulatively for all + channels recognized: ``audio_channel_count`` multiplied by + the length of the audio. + language_code (str): + Required. The language of the supplied audio as a + `BCP-47 `__ + language tag. Example: "en-US". See `Language + Support `__ + for a list of the currently supported language codes. + alternative_language_codes (MutableSequence[str]): + A list of up to 3 additional + `BCP-47 `__ + language tags, listing possible alternative languages of the + supplied audio. See `Language + Support `__ + for a list of the currently supported language codes. If + alternative languages are listed, recognition result will + contain recognition in the most likely language detected + including the main language_code. The recognition result + will include the language tag of the language detected in + the audio. Note: This feature is only supported for Voice + Command and Voice Search use cases and performance may vary + for other use cases (e.g., phone call transcription). + max_alternatives (int): + Maximum number of recognition hypotheses to be returned. + Specifically, the maximum number of + ``SpeechRecognitionAlternative`` messages within each + ``SpeechRecognitionResult``. The server may return fewer + than ``max_alternatives``. Valid values are ``0``-``30``. A + value of ``0`` or ``1`` will return a maximum of one. If + omitted, will return a maximum of one. + profanity_filter (bool): + If set to ``true``, the server will attempt to filter out + profanities, replacing all but the initial character in each + filtered word with asterisks, e.g. "f**\*". If set to + ``false`` or omitted, profanities won't be filtered out. + adaptation (google.cloud.speech_v1.types.SpeechAdaptation): + Speech adaptation configuration improves the accuracy of + speech recognition. For more information, see the `speech + adaptation `__ + documentation. When speech adaptation is set it supersedes + the ``speech_contexts`` field. + transcript_normalization (google.cloud.speech_v1.types.TranscriptNormalization): + Optional. 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. + speech_contexts (MutableSequence[google.cloud.speech_v1.types.SpeechContext]): + Array of + [SpeechContext][google.cloud.speech.v1.SpeechContext]. A + means to provide context to assist the speech recognition. + For more information, see `speech + adaptation `__. + enable_word_time_offsets (bool): + If ``true``, the top result includes a list of words and the + start and end time offsets (timestamps) for those words. If + ``false``, no word-level time offset information is + returned. The default is ``false``. + enable_word_confidence (bool): + If ``true``, the top result includes a list of words and the + confidence for those words. If ``false``, no word-level + confidence information is returned. The default is + ``false``. + enable_automatic_punctuation (bool): + If 'true', adds punctuation to recognition + result hypotheses. This feature is only + available in select languages. Setting this for + requests in other languages has no effect at + all. The default 'false' value does not add + punctuation to result hypotheses. + enable_spoken_punctuation (google.protobuf.wrappers_pb2.BoolValue): + The spoken punctuation behavior for the call If not set, + uses default behavior based on model of choice e.g. + command_and_search will enable spoken punctuation by default + If 'true', replaces spoken punctuation with the + corresponding symbols in the request. For example, "how are + you question mark" becomes "how are you?". See + https://cloud.google.com/speech-to-text/docs/spoken-punctuation + for support. If 'false', spoken punctuation is not replaced. + enable_spoken_emojis (google.protobuf.wrappers_pb2.BoolValue): + The spoken emoji behavior for the call + If not set, uses default behavior based on model + of choice If 'true', adds spoken emoji + formatting for the request. This will replace + spoken emojis with the corresponding Unicode + symbols in the final transcript. If 'false', + spoken emojis are not replaced. + diarization_config (google.cloud.speech_v1.types.SpeakerDiarizationConfig): + Config to enable speaker diarization and set + additional parameters to make diarization better + suited for your application. Note: When this is + enabled, we send all the words from the + beginning of the audio for the top alternative + in every consecutive STREAMING responses. This + is done in order to improve our speaker tags as + our models learn to identify the speakers in the + conversation over time. For non-streaming + requests, the diarization results will be + provided only in the top alternative of the + FINAL SpeechRecognitionResult. + metadata (google.cloud.speech_v1.types.RecognitionMetadata): + Metadata regarding this request. + model (str): + Which model to select for the given request. Select the + model best suited to your domain to get best results. If a + model is not explicitly specified, then we auto-select a + model based on the parameters in the RecognitionConfig. + + .. raw:: html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelDescription
latest_longBest for long form content like media or conversation.
latest_shortBest for short form content like commands or single shot directed + speech.
command_and_searchBest for short queries such as voice commands or voice search.
phone_callBest for audio that originated from a phone call (typically + recorded at an 8khz sampling rate).
videoBest for audio that originated from video or includes multiple + speakers. Ideally the audio is recorded at a 16khz or greater + sampling rate. This is a premium model that costs more than the + standard rate.
defaultBest for audio that is not one of the specific audio models. + For example, long-form audio. Ideally the audio is high-fidelity, + recorded at a 16khz or greater sampling rate.
medical_conversationBest for audio that originated from a conversation between a + medical provider and patient.
medical_dictationBest for audio that originated from dictation notes by a medical + provider.
+ use_enhanced (bool): + Set to true to use an enhanced model for speech recognition. + If ``use_enhanced`` is set to true and the ``model`` field + is not set, then an appropriate enhanced model is chosen if + an enhanced model exists for the audio. + + If ``use_enhanced`` is true and an enhanced version of the + specified model does not exist, then the speech is + recognized using the standard version of the specified + model. + """ + + class AudioEncoding(proto.Enum): + r"""The encoding of the audio data sent in the request. + + All encodings support only 1 channel (mono) audio, unless the + ``audio_channel_count`` and + ``enable_separate_recognition_per_channel`` fields are set. + + For best results, the audio source should be captured and + transmitted using a lossless encoding (``FLAC`` or ``LINEAR16``). + The accuracy of the speech recognition can be reduced if lossy + codecs are used to capture or transmit audio, particularly if + background noise is present. Lossy codecs include ``MULAW``, + ``AMR``, ``AMR_WB``, ``OGG_OPUS``, ``SPEEX_WITH_HEADER_BYTE``, + ``MP3``, and ``WEBM_OPUS``. + + The ``FLAC`` and ``WAV`` audio file formats include a header that + describes the included audio content. You can request recognition + for ``WAV`` files that contain either ``LINEAR16`` or ``MULAW`` + encoded audio. If you send ``FLAC`` or ``WAV`` audio file format in + your request, you do not need to specify an ``AudioEncoding``; the + audio encoding format is determined from the file header. If you + specify an ``AudioEncoding`` when you send send ``FLAC`` or ``WAV`` + audio, the encoding configuration must match the encoding described + in the audio header; otherwise the request returns an + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] + error code. + + Values: + ENCODING_UNSPECIFIED (0): + Not specified. + LINEAR16 (1): + Uncompressed 16-bit signed little-endian + samples (Linear PCM). + FLAC (2): + ``FLAC`` (Free Lossless Audio Codec) is the recommended + encoding because it is lossless--therefore recognition is + not compromised--and requires only about half the bandwidth + of ``LINEAR16``. ``FLAC`` stream encoding supports 16-bit + and 24-bit samples, however, not all fields in + ``STREAMINFO`` are supported. + MULAW (3): + 8-bit samples that compand 14-bit audio + samples using G.711 PCMU/mu-law. + AMR (4): + Adaptive Multi-Rate Narrowband codec. ``sample_rate_hertz`` + must be 8000. + AMR_WB (5): + Adaptive Multi-Rate Wideband codec. ``sample_rate_hertz`` + must be 16000. + OGG_OPUS (6): + Opus encoded audio frames in Ogg container + (`OggOpus `__). + ``sample_rate_hertz`` must be one of 8000, 12000, 16000, + 24000, or 48000. + SPEEX_WITH_HEADER_BYTE (7): + Although the use of lossy encodings is not recommended, if a + very low bitrate encoding is required, ``OGG_OPUS`` is + highly preferred over Speex encoding. The + `Speex `__ encoding supported by Cloud + Speech API has a header byte in each block, as in MIME type + ``audio/x-speex-with-header-byte``. It is a variant of the + RTP Speex encoding defined in `RFC + 5574 `__. The stream is + a sequence of blocks, one block per RTP packet. Each block + starts with a byte containing the length of the block, in + bytes, followed by one or more frames of Speex data, padded + to an integral number of bytes (octets) as specified in RFC + 5574. In other words, each RTP header is replaced with a + single byte containing the block length. Only Speex wideband + is supported. ``sample_rate_hertz`` must be 16000. + MP3 (8): + MP3 audio. MP3 encoding is a Beta feature and only available + in v1p1beta1. Support all standard MP3 bitrates (which range + from 32-320 kbps). When using this encoding, + ``sample_rate_hertz`` has to match the sample rate of the + file being used. + WEBM_OPUS (9): + Opus encoded audio frames in WebM container + (`OggOpus `__). + ``sample_rate_hertz`` must be one of 8000, 12000, 16000, + 24000, or 48000. + """ + + ENCODING_UNSPECIFIED = 0 + LINEAR16 = 1 + FLAC = 2 + MULAW = 3 + AMR = 4 + AMR_WB = 5 + OGG_OPUS = 6 + SPEEX_WITH_HEADER_BYTE = 7 + MP3 = 8 + WEBM_OPUS = 9 + + encoding: AudioEncoding = proto.Field( + proto.ENUM, + number=1, + enum=AudioEncoding, + ) + sample_rate_hertz: int = proto.Field( + proto.INT32, + number=2, + ) + audio_channel_count: int = proto.Field( + proto.INT32, + number=7, + ) + enable_separate_recognition_per_channel: bool = proto.Field( + proto.BOOL, + number=12, + ) + language_code: str = proto.Field( + proto.STRING, + number=3, + ) + alternative_language_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=18, + ) + max_alternatives: int = proto.Field( + proto.INT32, + number=4, + ) + profanity_filter: bool = proto.Field( + proto.BOOL, + number=5, + ) + adaptation: resource.SpeechAdaptation = proto.Field( + proto.MESSAGE, + number=20, + message=resource.SpeechAdaptation, + ) + transcript_normalization: resource.TranscriptNormalization = proto.Field( + proto.MESSAGE, + number=24, + message=resource.TranscriptNormalization, + ) + speech_contexts: MutableSequence["SpeechContext"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="SpeechContext", + ) + enable_word_time_offsets: bool = proto.Field( + proto.BOOL, + number=8, + ) + enable_word_confidence: bool = proto.Field( + proto.BOOL, + number=15, + ) + enable_automatic_punctuation: bool = proto.Field( + proto.BOOL, + number=11, + ) + enable_spoken_punctuation: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=22, + message=wrappers_pb2.BoolValue, + ) + enable_spoken_emojis: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=23, + message=wrappers_pb2.BoolValue, + ) + diarization_config: "SpeakerDiarizationConfig" = proto.Field( + proto.MESSAGE, + number=19, + message="SpeakerDiarizationConfig", + ) + metadata: "RecognitionMetadata" = proto.Field( + proto.MESSAGE, + number=9, + message="RecognitionMetadata", + ) + model: str = proto.Field( + proto.STRING, + number=13, + ) + use_enhanced: bool = proto.Field( + proto.BOOL, + number=14, + ) + + +class SpeakerDiarizationConfig(proto.Message): + r"""Config to enable speaker diarization. + + Attributes: + enable_speaker_diarization (bool): + If 'true', enables speaker detection for each recognized + word in the top alternative of the recognition result using + a speaker_label provided in the WordInfo. + min_speaker_count (int): + Minimum number of speakers in the + conversation. This range gives you more + flexibility by allowing the system to + automatically determine the correct number of + speakers. If not set, the default value is 2. + max_speaker_count (int): + Maximum number of speakers in the + conversation. This range gives you more + flexibility by allowing the system to + automatically determine the correct number of + speakers. If not set, the default value is 6. + speaker_tag (int): + Output only. Unused. + """ + + enable_speaker_diarization: bool = proto.Field( + proto.BOOL, + number=1, + ) + min_speaker_count: int = proto.Field( + proto.INT32, + number=2, + ) + max_speaker_count: int = proto.Field( + proto.INT32, + number=3, + ) + speaker_tag: int = proto.Field( + proto.INT32, + number=5, + ) + + +class RecognitionMetadata(proto.Message): + r"""Description of audio data to be recognized. + + Attributes: + interaction_type (google.cloud.speech_v1.types.RecognitionMetadata.InteractionType): + The use case most closely describing the + audio content to be recognized. + industry_naics_code_of_audio (int): + The industry vertical to which this speech + recognition request most closely applies. This + is most indicative of the topics contained in + the audio. Use the 6-digit NAICS code to + identify the industry vertical - see + https://www.naics.com/search/. + microphone_distance (google.cloud.speech_v1.types.RecognitionMetadata.MicrophoneDistance): + The audio type that most closely describes + the audio being recognized. + original_media_type (google.cloud.speech_v1.types.RecognitionMetadata.OriginalMediaType): + The original media the speech was recorded + on. + recording_device_type (google.cloud.speech_v1.types.RecognitionMetadata.RecordingDeviceType): + The type of device the speech was recorded + with. + recording_device_name (str): + The device used to make the recording. + Examples 'Nexus 5X' or 'Polycom SoundStation IP + 6000' or 'POTS' or 'VoIP' or 'Cardioid + Microphone'. + original_mime_type (str): + Mime type of the original audio file. For example + ``audio/m4a``, ``audio/x-alaw-basic``, ``audio/mp3``, + ``audio/3gpp``. A list of possible audio mime types is + maintained at + http://www.iana.org/assignments/media-types/media-types.xhtml#audio + audio_topic (str): + Description of the content. Eg. "Recordings + of federal supreme court hearings from 2012". + """ + + class InteractionType(proto.Enum): + r"""Use case categories that the audio recognition request can be + described by. + + Values: + INTERACTION_TYPE_UNSPECIFIED (0): + Use case is either unknown or is something + other than one of the other values below. + DISCUSSION (1): + Multiple people in a conversation or discussion. For example + in a meeting with two or more people actively participating. + Typically all the primary people speaking would be in the + same room (if not, see PHONE_CALL) + PRESENTATION (2): + One or more persons lecturing or presenting + to others, mostly uninterrupted. + PHONE_CALL (3): + A phone-call or video-conference in which two + or more people, who are not in the same room, + are actively participating. + VOICEMAIL (4): + A recorded message intended for another + person to listen to. + PROFESSIONALLY_PRODUCED (5): + Professionally produced audio (eg. TV Show, + Podcast). + VOICE_SEARCH (6): + Transcribe spoken questions and queries into + text. + VOICE_COMMAND (7): + Transcribe voice commands, such as for + controlling a device. + DICTATION (8): + Transcribe speech to text to create a written + document, such as a text-message, email or + report. + """ + + INTERACTION_TYPE_UNSPECIFIED = 0 + DISCUSSION = 1 + PRESENTATION = 2 + PHONE_CALL = 3 + VOICEMAIL = 4 + PROFESSIONALLY_PRODUCED = 5 + VOICE_SEARCH = 6 + VOICE_COMMAND = 7 + DICTATION = 8 + + class MicrophoneDistance(proto.Enum): + r"""Enumerates the types of capture settings describing an audio + file. + + Values: + MICROPHONE_DISTANCE_UNSPECIFIED (0): + Audio type is not known. + NEARFIELD (1): + The audio was captured from a closely placed + microphone. Eg. phone, dictaphone, or handheld + microphone. Generally if there speaker is within + 1 meter of the microphone. + MIDFIELD (2): + The speaker if within 3 meters of the + microphone. + FARFIELD (3): + The speaker is more than 3 meters away from + the microphone. + """ + + MICROPHONE_DISTANCE_UNSPECIFIED = 0 + NEARFIELD = 1 + MIDFIELD = 2 + FARFIELD = 3 + + class OriginalMediaType(proto.Enum): + r"""The original media the speech was recorded on. + + Values: + ORIGINAL_MEDIA_TYPE_UNSPECIFIED (0): + Unknown original media type. + AUDIO (1): + The speech data is an audio recording. + VIDEO (2): + The speech data originally recorded on a + video. + """ + + ORIGINAL_MEDIA_TYPE_UNSPECIFIED = 0 + AUDIO = 1 + VIDEO = 2 + + class RecordingDeviceType(proto.Enum): + r"""The type of device the speech was recorded with. + + Values: + RECORDING_DEVICE_TYPE_UNSPECIFIED (0): + The recording device is unknown. + SMARTPHONE (1): + Speech was recorded on a smartphone. + PC (2): + Speech was recorded using a personal computer + or tablet. + PHONE_LINE (3): + Speech was recorded over a phone line. + VEHICLE (4): + Speech was recorded in a vehicle. + OTHER_OUTDOOR_DEVICE (5): + Speech was recorded outdoors. + OTHER_INDOOR_DEVICE (6): + Speech was recorded indoors. + """ + + RECORDING_DEVICE_TYPE_UNSPECIFIED = 0 + SMARTPHONE = 1 + PC = 2 + PHONE_LINE = 3 + VEHICLE = 4 + OTHER_OUTDOOR_DEVICE = 5 + OTHER_INDOOR_DEVICE = 6 + + interaction_type: InteractionType = proto.Field( + proto.ENUM, + number=1, + enum=InteractionType, + ) + industry_naics_code_of_audio: int = proto.Field( + proto.UINT32, + number=3, + ) + microphone_distance: MicrophoneDistance = proto.Field( + proto.ENUM, + number=4, + enum=MicrophoneDistance, + ) + original_media_type: OriginalMediaType = proto.Field( + proto.ENUM, + number=5, + enum=OriginalMediaType, + ) + recording_device_type: RecordingDeviceType = proto.Field( + proto.ENUM, + number=6, + enum=RecordingDeviceType, + ) + recording_device_name: str = proto.Field( + proto.STRING, + number=7, + ) + original_mime_type: str = proto.Field( + proto.STRING, + number=8, + ) + audio_topic: str = proto.Field( + proto.STRING, + number=10, + ) + + +class SpeechContext(proto.Message): + r"""Provides "hints" to the speech recognizer to favor specific + words and phrases in the results. + + Attributes: + phrases (MutableSequence[str]): + A list of strings containing words and phrases "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 `__. + + List items can also be set to classes for groups of words + that represent common concepts that occur in natural + language. For example, rather than providing phrase hints + for every month of the year, using the $MONTH class improves + the likelihood of correctly transcribing audio that includes + months. + 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 and 20. We + recommend using a binary search approach to finding the + optimal value for your use case. + """ + + phrases: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=4, + ) + + +class RecognitionAudio(proto.Message): + r"""Contains audio data in the encoding specified in the + ``RecognitionConfig``. Either ``content`` or ``uri`` must be + supplied. Supplying both or neither returns + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + See `content + limits `__. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + content (bytes): + The audio data bytes encoded as specified in + ``RecognitionConfig``. Note: as with all bytes fields, proto + buffers use a pure binary representation, whereas JSON + representations use base64. + + This field is a member of `oneof`_ ``audio_source``. + uri (str): + URI that points to a file that contains audio data bytes as + specified in ``RecognitionConfig``. The file must not be + compressed (for example, gzip). Currently, only Google Cloud + Storage URIs are supported, which must be specified in the + following format: ``gs://bucket_name/object_name`` (other + URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + + This field is a member of `oneof`_ ``audio_source``. + """ + + content: bytes = proto.Field( + proto.BYTES, + number=1, + oneof="audio_source", + ) + uri: str = proto.Field( + proto.STRING, + number=2, + oneof="audio_source", + ) + + +class RecognizeResponse(proto.Message): + r"""The only message returned to the client by the ``Recognize`` method. + It contains the result as zero or more sequential + ``SpeechRecognitionResult`` messages. + + Attributes: + results (MutableSequence[google.cloud.speech_v1.types.SpeechRecognitionResult]): + Sequential list of transcription results + corresponding to sequential portions of audio. + total_billed_time (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + corresponding request. + speech_adaptation_info (google.cloud.speech_v1.types.SpeechAdaptationInfo): + Provides information on adaptation behavior + in response + request_id (int): + The ID associated with the request. This is a + unique ID specific only to the given request. + """ + + results: MutableSequence["SpeechRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SpeechRecognitionResult", + ) + total_billed_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + speech_adaptation_info: "SpeechAdaptationInfo" = proto.Field( + proto.MESSAGE, + number=7, + message="SpeechAdaptationInfo", + ) + request_id: int = proto.Field( + proto.INT64, + number=8, + ) + + +class LongRunningRecognizeResponse(proto.Message): + r"""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. + + Attributes: + results (MutableSequence[google.cloud.speech_v1.types.SpeechRecognitionResult]): + Sequential list of transcription results + corresponding to sequential portions of audio. + total_billed_time (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + corresponding request. + output_config (google.cloud.speech_v1.types.TranscriptOutputConfig): + Original output config if present in the + request. + output_error (google.rpc.status_pb2.Status): + If the transcript output fails this field + contains the relevant error. + speech_adaptation_info (google.cloud.speech_v1.types.SpeechAdaptationInfo): + Provides information on speech adaptation + behavior in response + request_id (int): + The ID associated with the request. This is a + unique ID specific only to the given request. + """ + + results: MutableSequence["SpeechRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SpeechRecognitionResult", + ) + total_billed_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + output_config: "TranscriptOutputConfig" = proto.Field( + proto.MESSAGE, + number=6, + message="TranscriptOutputConfig", + ) + output_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=7, + message=status_pb2.Status, + ) + speech_adaptation_info: "SpeechAdaptationInfo" = proto.Field( + proto.MESSAGE, + number=8, + message="SpeechAdaptationInfo", + ) + request_id: int = proto.Field( + proto.INT64, + number=9, + ) + + +class LongRunningRecognizeMetadata(proto.Message): + r"""Describes the progress of a long-running ``LongRunningRecognize`` + call. It is included in the ``metadata`` field of the ``Operation`` + returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + progress_percent (int): + Approximate percentage of audio processed + thus far. Guaranteed to be 100 when the audio is + fully processed and the results are available. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent processing update. + uri (str): + Output only. The URI of the audio file being + transcribed. Empty if the audio was sent as byte + content. + """ + + progress_percent: int = proto.Field( + proto.INT32, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +class StreamingRecognizeResponse(proto.Message): + r"""``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 ``StreamingRecognizeResponse``\ s + 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``. + + Attributes: + error (google.rpc.status_pb2.Status): + If set, returns a [google.rpc.Status][google.rpc.Status] + message that specifies the error for the operation. + results (MutableSequence[google.cloud.speech_v1.types.StreamingRecognitionResult]): + This repeated list contains zero or more results that + correspond to consecutive portions of the audio currently + being processed. It contains zero or one ``is_final=true`` + result (the newly settled portion), followed by zero or more + ``is_final=false`` results (the interim results). + speech_event_type (google.cloud.speech_v1.types.StreamingRecognizeResponse.SpeechEventType): + Indicates the type of speech event. + speech_event_time (google.protobuf.duration_pb2.Duration): + Time offset between the beginning of the + audio and event emission. + total_billed_time (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + stream. Set only if this is the last response in + the stream. + speech_adaptation_info (google.cloud.speech_v1.types.SpeechAdaptationInfo): + Provides information on adaptation behavior + in response + request_id (int): + The ID associated with the request. This is a + unique ID specific only to the given request. + """ + + class SpeechEventType(proto.Enum): + r"""Indicates the type of speech event. + + Values: + SPEECH_EVENT_UNSPECIFIED (0): + No speech event specified. + END_OF_SINGLE_UTTERANCE (1): + This event indicates that the server has detected the end of + the user's speech utterance and expects no additional + speech. Therefore, the server will not process additional + audio (although it may subsequently return additional + results). The client should stop sending additional audio + data, half-close the gRPC connection, and wait for any + additional results until the server closes the gRPC + connection. This event is only sent if ``single_utterance`` + was set to ``true``, and is not used otherwise. + SPEECH_ACTIVITY_BEGIN (2): + This event indicates that the server has detected the + beginning of human voice activity in the stream. This event + can be returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_END (3): + This event indicates that the server has detected the end of + human voice activity in the stream. This event can be + returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_TIMEOUT (4): + This event indicates that the user-set + timeout for speech activity begin or end has + exceeded. Upon receiving this event, the client + is expected to send a half close. Further audio + will not be processed. + """ + + SPEECH_EVENT_UNSPECIFIED = 0 + END_OF_SINGLE_UTTERANCE = 1 + SPEECH_ACTIVITY_BEGIN = 2 + SPEECH_ACTIVITY_END = 3 + SPEECH_ACTIVITY_TIMEOUT = 4 + + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + results: MutableSequence["StreamingRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="StreamingRecognitionResult", + ) + speech_event_type: SpeechEventType = proto.Field( + proto.ENUM, + number=4, + enum=SpeechEventType, + ) + speech_event_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + total_billed_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + speech_adaptation_info: "SpeechAdaptationInfo" = proto.Field( + proto.MESSAGE, + number=9, + message="SpeechAdaptationInfo", + ) + request_id: int = proto.Field( + proto.INT64, + number=10, + ) + + +class StreamingRecognitionResult(proto.Message): + r"""A streaming speech recognition result corresponding to a + portion of the audio that is currently being processed. + + Attributes: + alternatives (MutableSequence[google.cloud.speech_v1.types.SpeechRecognitionAlternative]): + May contain one or more recognition hypotheses (up to the + maximum specified in ``max_alternatives``). These + alternatives are ordered in terms of accuracy, with the top + (first) alternative being the most probable, as ranked by + the recognizer. + is_final (bool): + If ``false``, this ``StreamingRecognitionResult`` represents + an interim result that may change. If ``true``, this is the + final time the speech service will return this particular + ``StreamingRecognitionResult``, the recognizer will not + return any further hypotheses for this portion of the + transcript and corresponding audio. + stability (float): + An estimate of the likelihood that the recognizer will not + change its guess about this interim result. Values range + from 0.0 (completely unstable) to 1.0 (completely stable). + This field is only provided for interim results + (``is_final=false``). The default of 0.0 is a sentinel value + indicating ``stability`` was not set. + result_end_time (google.protobuf.duration_pb2.Duration): + Time offset of the end of this result + relative to the beginning of the audio. + channel_tag (int): + For multi-channel audio, this is the channel number + corresponding to the recognized result for the audio from + that channel. For audio_channel_count = N, its output values + can range from '1' to 'N'. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives: MutableSequence["SpeechRecognitionAlternative"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SpeechRecognitionAlternative", + ) + is_final: bool = proto.Field( + proto.BOOL, + number=2, + ) + stability: float = proto.Field( + proto.FLOAT, + number=3, + ) + result_end_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + channel_tag: int = proto.Field( + proto.INT32, + number=5, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + + +class SpeechRecognitionResult(proto.Message): + r"""A speech recognition result corresponding to a portion of the + audio. + + Attributes: + alternatives (MutableSequence[google.cloud.speech_v1.types.SpeechRecognitionAlternative]): + May contain one or more recognition hypotheses (up to the + maximum specified in ``max_alternatives``). These + alternatives are ordered in terms of accuracy, with the top + (first) alternative being the most probable, as ranked by + the recognizer. + channel_tag (int): + For multi-channel audio, this is the channel number + corresponding to the recognized result for the audio from + that channel. For audio_channel_count = N, its output values + can range from '1' to 'N'. + result_end_time (google.protobuf.duration_pb2.Duration): + Time offset of the end of this result + relative to the beginning of the audio. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives: MutableSequence["SpeechRecognitionAlternative"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SpeechRecognitionAlternative", + ) + channel_tag: int = proto.Field( + proto.INT32, + number=2, + ) + result_end_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + language_code: str = proto.Field( + proto.STRING, + number=5, + ) + + +class SpeechRecognitionAlternative(proto.Message): + r"""Alternative hypotheses (a.k.a. n-best list). + + Attributes: + transcript (str): + Transcript text representing the words that + the user spoke. In languages that use spaces to + separate words, the transcript might have a + leading space if it isn't the first result. You + can concatenate each result to obtain the full + transcript without using a separator. + confidence (float): + The confidence estimate between 0.0 and 1.0. A higher number + indicates an estimated greater likelihood that the + recognized words are correct. This field is set only for the + top alternative of a non-streaming result or, of a streaming + result where ``is_final=true``. This field is not guaranteed + to be accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + words (MutableSequence[google.cloud.speech_v1.types.WordInfo]): + A list of word-specific information for each recognized + word. Note: When ``enable_speaker_diarization`` is true, you + will see all the words from the beginning of the audio. + """ + + transcript: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + words: MutableSequence["WordInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="WordInfo", + ) + + +class WordInfo(proto.Message): + r"""Word-specific information for recognized words. + + Attributes: + start_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the start of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + end_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the end of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + word (str): + The word corresponding to this set of + information. + confidence (float): + The confidence estimate between 0.0 and 1.0. A higher number + indicates an estimated greater likelihood that the + recognized words are correct. This field is set only for the + top alternative of a non-streaming result or, of a streaming + result where ``is_final=true``. This field is not guaranteed + to be accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + speaker_tag (int): + Output only. A distinct integer value is assigned for every + speaker within the audio. This field specifies which one of + those speakers was detected to have spoken this word. Value + ranges from '1' to diarization_speaker_count. speaker_tag is + set if enable_speaker_diarization = 'true' and only for the + top alternative. Note: Use speaker_label instead. + speaker_label (str): + Output only. A label value assigned for every unique speaker + within the audio. This field specifies which speaker was + detected to have spoken this word. For some models, like + medical_conversation this can be actual speaker role, for + example "patient" or "provider", but generally this would be + a number identifying a speaker. This field is only set if + enable_speaker_diarization = 'true' and only for the top + alternative. + """ + + start_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + word: str = proto.Field( + proto.STRING, + number=3, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=4, + ) + speaker_tag: int = proto.Field( + proto.INT32, + number=5, + ) + speaker_label: str = proto.Field( + proto.STRING, + number=6, + ) + + +class SpeechAdaptationInfo(proto.Message): + r"""Information on speech adaptation use in results + + Attributes: + adaptation_timeout (bool): + Whether there was a timeout when applying + speech adaptation. If true, adaptation had no + effect in the response transcript. + timeout_message (str): + If set, returns a message specifying which + part of the speech adaptation request timed out. + """ + + adaptation_timeout: bool = proto.Field( + proto.BOOL, + number=1, + ) + timeout_message: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/cloud_speech_adaptation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/cloud_speech_adaptation.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4f639cc1eb036b6af8769b2c2c663fa1112f6a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/cloud_speech_adaptation.py @@ -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 + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.speech_v1.types import resource + +__protobuf__ = proto.module( + package="google.cloud.speech.v1", + 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 `__ + 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_v1.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_v1.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 `__ + 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 `__ + 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 `__ + 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_v1.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 `__ + 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_v1.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_v1.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 `__ + 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 `__ + 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_v1.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 `__ + with matching ``us`` or ``eu`` location value. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/resource.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..2588bac30cbaf7b39660caa51a3f1650e5f1f96a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1/types/resource.py @@ -0,0 +1,282 @@ +# -*- 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 + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.speech.v1", + 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_v1.types.CustomClass.ClassItem]): + A collection of class items. + """ + + 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, + ) + + +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_v1.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. + """ + + 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 `__. + + 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 `__ + 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, + ) + + +class SpeechAdaptation(proto.Message): + r"""Speech adaptation configuration. + + Attributes: + phrase_sets (MutableSequence[google.cloud.speech_v1.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_v1.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_v1.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_v1.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)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33137be07058749b4d7a044024e2988a50f85dc3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/__init__.py @@ -0,0 +1,223 @@ +# -*- 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 sys + +import google.api_core as api_core + +from google.cloud.speech_v1p1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +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, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.speech_v1p1beta1") # type: ignore + api_core.check_dependency_versions("google.cloud.speech_v1p1beta1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.speech_v1p1beta1" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +from google.cloud.speech_v1.helpers import SpeechHelpers + + +# This class merges the auto-generated GAPIC client with handwritten helper methods. +# We ignore [misc] because mypy is flagging that both parent classes have a method +# named `streaming_recognize`, +# but their type signatures don't match. +# We ignore [no-redef] because of the name shadow with SpeechClient. We don't want +# to expose the GAPIC client without the helpers. +class SpeechClient(SpeechHelpers, SpeechClient): # type: ignore[no-redef, misc] + __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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..a1a3a774ffb58e122a0a817a256be59cd572b7f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/gapic_metadata.json @@ -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" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..d372d0b1db6f01f24c3657099b75881bf85c15d3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/gapic_version.py @@ -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.38.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..02081c09b9abb4d2d2a2c037d675d04eee51df20 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-speech package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/__init__.py @@ -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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59dba090b965017cfc59df64e048f8ac7be939af --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..f052638b31ce2691e4200f5930146ab9f6bd3b1c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py @@ -0,0 +1,1749 @@ +# -*- 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +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 + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.speech_v1p1beta1.services.adaptation import pagers +from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource + +from .client import AdaptationClient +from .transports.base import DEFAULT_CLIENT_INFO, AdaptationTransport +from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport + +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 AdaptationAsyncClient: + """Service that implements Google Cloud Speech Adaptation API.""" + + _client: AdaptationClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AdaptationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AdaptationClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AdaptationClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AdaptationClient._DEFAULT_UNIVERSE + + crypto_key_path = staticmethod(AdaptationClient.crypto_key_path) + parse_crypto_key_path = staticmethod(AdaptationClient.parse_crypto_key_path) + crypto_key_version_path = staticmethod(AdaptationClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod( + AdaptationClient.parse_crypto_key_version_path + ) + custom_class_path = staticmethod(AdaptationClient.custom_class_path) + parse_custom_class_path = staticmethod(AdaptationClient.parse_custom_class_path) + phrase_set_path = staticmethod(AdaptationClient.phrase_set_path) + parse_phrase_set_path = staticmethod(AdaptationClient.parse_phrase_set_path) + common_billing_account_path = staticmethod( + AdaptationClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AdaptationClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(AdaptationClient.common_folder_path) + parse_common_folder_path = staticmethod(AdaptationClient.parse_common_folder_path) + common_organization_path = staticmethod(AdaptationClient.common_organization_path) + parse_common_organization_path = staticmethod( + AdaptationClient.parse_common_organization_path + ) + common_project_path = staticmethod(AdaptationClient.common_project_path) + parse_common_project_path = staticmethod(AdaptationClient.parse_common_project_path) + common_location_path = staticmethod(AdaptationClient.common_location_path) + parse_common_location_path = staticmethod( + AdaptationClient.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: + AdaptationAsyncClient: The constructed client. + """ + sa_info_func = ( + AdaptationClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdaptationAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AdaptationAsyncClient: The constructed client. + """ + sa_file_func = ( + AdaptationClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AdaptationAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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 AdaptationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AdaptationTransport: + """Returns the transport used by the client instance. + + Returns: + AdaptationTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = AdaptationClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AdaptationTransport, Callable[..., AdaptationTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the adaptation 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,AdaptationTransport,Callable[..., AdaptationTransport]]]): + 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 AdaptationTransport 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 = AdaptationClient( + 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.AdaptationAsyncClient`.", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "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.Adaptation", + "credentialsType": None, + }, + ) + + async def create_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.CreatePhraseSetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + phrase_set: Optional[resource.PhraseSet] = None, + phrase_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""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. + + .. 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_create_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.CreatePhraseSetRequest( + parent="parent_value", + phrase_set_id="phrase_set_id_value", + ) + + # Make the request + response = await client.create_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.CreatePhraseSetRequest, dict]]): + The request object. Message sent by the client for the ``CreatePhraseSet`` + method. + parent (:class:`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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + phrase_set (:class:`google.cloud.speech_v1p1beta1.types.PhraseSet`): + Required. The phrase set to create. + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + phrase_set_id (:class:`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. + + This corresponds to the ``phrase_set_id`` 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.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + # 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 = [parent, phrase_set, phrase_set_id] + 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_adaptation.CreatePhraseSetRequest): + request = cloud_speech_adaptation.CreatePhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if phrase_set is not None: + request.phrase_set = phrase_set + if phrase_set_id is not None: + request.phrase_set_id = phrase_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # 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_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.GetPhraseSetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Get a phrase set. + + .. 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_get_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.GetPhraseSetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.GetPhraseSetRequest, dict]]): + The request object. Message sent by the client for the ``GetPhraseSet`` + method. + name (:class:`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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``name`` 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.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + # 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 = [name] + 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_adaptation.GetPhraseSetRequest): + request = cloud_speech_adaptation.GetPhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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 list_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.ListPhraseSetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPhraseSetAsyncPager: + r"""List phrase sets. + + .. 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_list_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.ListPhraseSetRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_phrase_set(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.ListPhraseSetRequest, dict]]): + The request object. Message sent by the client for the ``ListPhraseSet`` + method. + parent (:class:`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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` 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.services.adaptation.pagers.ListPhraseSetAsyncPager: + Message returned to the client by the ListPhraseSet + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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_adaptation.ListPhraseSetRequest): + request = cloud_speech_adaptation.ListPhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPhraseSetAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.UpdatePhraseSetRequest, dict] + ] = None, + *, + phrase_set: Optional[resource.PhraseSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Update a phrase set. + + .. 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_update_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.UpdatePhraseSetRequest( + ) + + # Make the request + response = await client.update_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.UpdatePhraseSetRequest, dict]]): + The request object. Message sent by the client for the ``UpdatePhraseSet`` + method. + phrase_set (:class:`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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + # 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 = [phrase_set, update_mask] + 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_adaptation.UpdatePhraseSetRequest): + request = cloud_speech_adaptation.UpdatePhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if phrase_set is not None: + request.phrase_set = phrase_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("phrase_set.name", request.phrase_set.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 delete_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.DeletePhraseSetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Delete a phrase set. + + .. 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_delete_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.DeletePhraseSetRequest( + name="name_value", + ) + + # Make the request + await client.delete_phrase_set(request=request) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.DeletePhraseSetRequest, dict]]): + The request object. Message sent by the client for the ``DeletePhraseSet`` + method. + name (:class:`str`): + Required. The name of the phrase set to delete. Format: + + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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`. + """ + # 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 = [name] + 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_adaptation.DeletePhraseSetRequest): + request = cloud_speech_adaptation.DeletePhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.CreateCustomClassRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + custom_class: Optional[resource.CustomClass] = None, + custom_class_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Create a custom class. + + .. 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_create_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.CreateCustomClassRequest( + parent="parent_value", + custom_class_id="custom_class_id_value", + ) + + # Make the request + response = await client.create_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.CreateCustomClassRequest, dict]]): + The request object. Message sent by the client for the ``CreateCustomClass`` + method. + parent (:class:`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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_class (:class:`google.cloud.speech_v1p1beta1.types.CustomClass`): + Required. The custom class to create. + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_class_id (:class:`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. + + This corresponds to the ``custom_class_id`` 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.CustomClass: + 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. + + """ + # 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 = [parent, custom_class, custom_class_id] + 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_adaptation.CreateCustomClassRequest): + request = cloud_speech_adaptation.CreateCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_class is not None: + request.custom_class = custom_class + if custom_class_id is not None: + request.custom_class_id = custom_class_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_custom_class + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # 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_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.GetCustomClassRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Get a custom class. + + .. 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_get_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.GetCustomClassRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.GetCustomClassRequest, dict]]): + The request object. Message sent by the client for the ``GetCustomClass`` + method. + name (:class:`str`): + Required. The name of the custom class to retrieve. + Format: + + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + + This corresponds to the ``name`` 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.CustomClass: + 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. + + """ + # 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 = [name] + 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_adaptation.GetCustomClassRequest): + request = cloud_speech_adaptation.GetCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_custom_class + ] + + # 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 list_custom_classes( + self, + request: Optional[ + Union[cloud_speech_adaptation.ListCustomClassesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCustomClassesAsyncPager: + r"""List custom classes. + + .. 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_list_custom_classes(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.ListCustomClassesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_classes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.ListCustomClassesRequest, dict]]): + The request object. Message sent by the client for the ``ListCustomClasses`` + method. + parent (:class:`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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` 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.services.adaptation.pagers.ListCustomClassesAsyncPager: + Message returned to the client by the ListCustomClasses + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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_adaptation.ListCustomClassesRequest): + request = cloud_speech_adaptation.ListCustomClassesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_custom_classes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCustomClassesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.UpdateCustomClassRequest, dict] + ] = None, + *, + custom_class: Optional[resource.CustomClass] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Update a custom class. + + .. 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_update_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.UpdateCustomClassRequest( + ) + + # Make the request + response = await client.update_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.UpdateCustomClassRequest, dict]]): + The request object. Message sent by the client for the ``UpdateCustomClass`` + method. + custom_class (: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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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.CustomClass: + 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. + + """ + # 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 = [custom_class, update_mask] + 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_adaptation.UpdateCustomClassRequest): + request = cloud_speech_adaptation.UpdateCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_class is not None: + request.custom_class = custom_class + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_custom_class + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("custom_class.name", request.custom_class.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 delete_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.DeleteCustomClassRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Delete a custom class. + + .. 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_delete_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationAsyncClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.DeleteCustomClassRequest( + name="name_value", + ) + + # Make the request + await client.delete_custom_class(request=request) + + Args: + request (Optional[Union[google.cloud.speech_v1p1beta1.types.DeleteCustomClassRequest, dict]]): + The request object. Message sent by the client for the ``DeleteCustomClass`` + method. + name (:class:`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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``name`` 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`. + """ + # 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 = [name] + 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_adaptation.DeleteCustomClassRequest): + request = cloud_speech_adaptation.DeleteCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_custom_class + ] + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AdaptationAsyncClient": + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("AdaptationAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/client.py new file mode 100644 index 0000000000000000000000000000000000000000..ff2856dbe48de3b080ef947018fa73cd6aa6c3c6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/client.py @@ -0,0 +1,2234 @@ +# -*- 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 os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.speech_v1p1beta1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.speech_v1p1beta1.services.adaptation import pagers +from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource + +from .transports.base import DEFAULT_CLIENT_INFO, AdaptationTransport +from .transports.grpc import AdaptationGrpcTransport +from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport +from .transports.rest import AdaptationRestTransport + + +class AdaptationClientMeta(type): + """Metaclass for the Adaptation client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AdaptationTransport]] + _transport_registry["grpc"] = AdaptationGrpcTransport + _transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport + _transport_registry["rest"] = AdaptationRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AdaptationTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AdaptationClient(metaclass=AdaptationClientMeta): + """Service that implements Google Cloud Speech Adaptation API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "speech.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "speech.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + AdaptationClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AdaptationClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AdaptationTransport: + """Returns the transport used by the client instance. + + Returns: + AdaptationTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + crypto_key_version: str, + ) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str, str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_class_path( + project: str, + location: str, + custom_class: str, + ) -> str: + """Returns a fully-qualified custom_class string.""" + return "projects/{project}/locations/{location}/customClasses/{custom_class}".format( + project=project, + location=location, + custom_class=custom_class, + ) + + @staticmethod + def parse_custom_class_path(path: str) -> Dict[str, str]: + """Parses a custom_class path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/customClasses/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def phrase_set_path( + project: str, + location: str, + phrase_set: str, + ) -> str: + """Returns a fully-qualified phrase_set string.""" + return "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( + project=project, + location=location, + phrase_set=phrase_set, + ) + + @staticmethod + def parse_phrase_set_path(path: str) -> Dict[str, str]: + """Parses a phrase_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/phraseSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. 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. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = AdaptationClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = AdaptationClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = AdaptationClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = AdaptationClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AdaptationClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AdaptationClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._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._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AdaptationTransport, Callable[..., AdaptationTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the adaptation 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,AdaptationTransport,Callable[..., AdaptationTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AdaptationTransport 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 the ``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_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + AdaptationClient._read_environment_variables() + ) + self._client_cert_source = AdaptationClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AdaptationClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AdaptationTransport) + if transport_provided: + # transport is a AdaptationTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(AdaptationTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or AdaptationClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[AdaptationTransport], Callable[..., AdaptationTransport] + ] = ( + AdaptationClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AdaptationTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.speech_v1p1beta1.AdaptationClient`.", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "credentialsType": None, + }, + ) + + def create_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.CreatePhraseSetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + phrase_set: Optional[resource.PhraseSet] = None, + phrase_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""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. + + .. 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 + + def sample_create_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.CreatePhraseSetRequest( + parent="parent_value", + phrase_set_id="phrase_set_id_value", + ) + + # Make the request + response = client.create_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.CreatePhraseSetRequest, dict]): + The request object. Message sent by the client for the ``CreatePhraseSet`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + phrase_set (google.cloud.speech_v1p1beta1.types.PhraseSet): + Required. The phrase set to create. + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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. + + This corresponds to the ``phrase_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + # 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 = [parent, phrase_set, phrase_set_id] + 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_adaptation.CreatePhraseSetRequest): + request = cloud_speech_adaptation.CreatePhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if phrase_set is not None: + request.phrase_set = phrase_set + if phrase_set_id is not None: + request.phrase_set_id = phrase_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.GetPhraseSetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Get a phrase set. + + .. 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 + + def sample_get_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.GetPhraseSetRequest( + name="name_value", + ) + + # Make the request + response = client.get_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.GetPhraseSetRequest, dict]): + The request object. Message sent by the client for the ``GetPhraseSet`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + # 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 = [name] + 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_adaptation.GetPhraseSetRequest): + request = cloud_speech_adaptation.GetPhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.ListPhraseSetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPhraseSetPager: + r"""List phrase sets. + + .. 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 + + def sample_list_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.ListPhraseSetRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_phrase_set(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.ListPhraseSetRequest, dict]): + The request object. Message sent by the client for the ``ListPhraseSet`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.services.adaptation.pagers.ListPhraseSetPager: + Message returned to the client by the ListPhraseSet + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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_adaptation.ListPhraseSetRequest): + request = cloud_speech_adaptation.ListPhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPhraseSetPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.UpdatePhraseSetRequest, dict] + ] = None, + *, + phrase_set: Optional[resource.PhraseSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Update a phrase set. + + .. 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 + + def sample_update_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.UpdatePhraseSetRequest( + ) + + # Make the request + response = client.update_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.UpdatePhraseSetRequest, dict]): + The request object. Message sent by the client for the ``UpdatePhraseSet`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + # 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 = [phrase_set, update_mask] + 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_adaptation.UpdatePhraseSetRequest): + request = cloud_speech_adaptation.UpdatePhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if phrase_set is not None: + request.phrase_set = phrase_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("phrase_set.name", request.phrase_set.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_phrase_set( + self, + request: Optional[ + Union[cloud_speech_adaptation.DeletePhraseSetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Delete a phrase set. + + .. 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 + + def sample_delete_phrase_set(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.DeletePhraseSetRequest( + name="name_value", + ) + + # Make the request + client.delete_phrase_set(request=request) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.DeletePhraseSetRequest, dict]): + The request object. Message sent by the client for the ``DeletePhraseSet`` + method. + name (str): + Required. The name of the phrase set to delete. Format: + + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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`. + """ + # 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 = [name] + 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_adaptation.DeletePhraseSetRequest): + request = cloud_speech_adaptation.DeletePhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.CreateCustomClassRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + custom_class: Optional[resource.CustomClass] = None, + custom_class_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Create a custom class. + + .. 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 + + def sample_create_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.CreateCustomClassRequest( + parent="parent_value", + custom_class_id="custom_class_id_value", + ) + + # Make the request + response = client.create_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.CreateCustomClassRequest, dict]): + The request object. Message sent by the client for the ``CreateCustomClass`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_class (google.cloud.speech_v1p1beta1.types.CustomClass): + Required. The custom class to create. + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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. + + This corresponds to the ``custom_class_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.CustomClass: + 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. + + """ + # 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 = [parent, custom_class, custom_class_id] + 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_adaptation.CreateCustomClassRequest): + request = cloud_speech_adaptation.CreateCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_class is not None: + request.custom_class = custom_class + if custom_class_id is not None: + request.custom_class_id = custom_class_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_custom_class] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.GetCustomClassRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Get a custom class. + + .. 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 + + def sample_get_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.GetCustomClassRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.GetCustomClassRequest, dict]): + The request object. Message sent by the client for the ``GetCustomClass`` + method. + name (str): + Required. The name of the custom class to retrieve. + Format: + + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.CustomClass: + 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. + + """ + # 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 = [name] + 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_adaptation.GetCustomClassRequest): + request = cloud_speech_adaptation.GetCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_custom_class] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_custom_classes( + self, + request: Optional[ + Union[cloud_speech_adaptation.ListCustomClassesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCustomClassesPager: + r"""List custom classes. + + .. 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 + + def sample_list_custom_classes(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.ListCustomClassesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_classes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.ListCustomClassesRequest, dict]): + The request object. Message sent by the client for the ``ListCustomClasses`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.services.adaptation.pagers.ListCustomClassesPager: + Message returned to the client by the ListCustomClasses + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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_adaptation.ListCustomClassesRequest): + request = cloud_speech_adaptation.ListCustomClassesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_custom_classes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCustomClassesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.UpdateCustomClassRequest, dict] + ] = None, + *, + custom_class: Optional[resource.CustomClass] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Update a custom class. + + .. 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 + + def sample_update_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.UpdateCustomClassRequest( + ) + + # Make the request + response = client.update_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.UpdateCustomClassRequest, dict]): + The request object. Message sent by the client for the ``UpdateCustomClass`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.CustomClass: + 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. + + """ + # 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 = [custom_class, update_mask] + 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_adaptation.UpdateCustomClassRequest): + request = cloud_speech_adaptation.UpdateCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_class is not None: + request.custom_class = custom_class + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_custom_class] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("custom_class.name", request.custom_class.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_custom_class( + self, + request: Optional[ + Union[cloud_speech_adaptation.DeleteCustomClassRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Delete a custom class. + + .. 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 + + def sample_delete_custom_class(): + # Create a client + client = speech_v1p1beta1.AdaptationClient() + + # Initialize request argument(s) + request = speech_v1p1beta1.DeleteCustomClassRequest( + name="name_value", + ) + + # Make the request + client.delete_custom_class(request=request) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.DeleteCustomClassRequest, dict]): + The request object. Message sent by the client for the ``DeleteCustomClass`` + method. + 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 `__ + with matching ``us`` or ``eu`` location value. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + # 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 = [name] + 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_adaptation.DeleteCustomClassRequest): + request = cloud_speech_adaptation.DeleteCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_custom_class] + + # 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._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "AdaptationClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("AdaptationClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..f7301de81ae25fb4eb5e31388fbde7b381f62648 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/pagers.py @@ -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) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7251a3b061c92de867ebbdadc989a40acfeab8fb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dc95d16148bc7421c042670750cd0aa960c9b5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py @@ -0,0 +1,340 @@ +# -*- 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 +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.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_adaptation, resource + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..df50b6c74cc439ce519c946290f436c4a5e3d887 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py @@ -0,0 +1,649 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +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 + +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)!r}" + + 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 = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC 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)!r}" + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..76a1bc89cf6235cf3bb9ffcb371c896c2c798d08 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py @@ -0,0 +1,739 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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.json_format import MessageToJson +from grpc.experimental import aio # 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)!r}" + + 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 `` 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)!r}" + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..f4cf38562f08b5eaecbf13c444b88bcd4aa32595 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest.py @@ -0,0 +1,2575 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation, resource + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAdaptationRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AdaptationRestInterceptor: + """Interceptor for Adaptation. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AdaptationRestTransport. + + .. code-block:: python + class MyCustomAdaptationInterceptor(AdaptationRestInterceptor): + def pre_create_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_classes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_classes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AdaptationRestTransport(interceptor=MyCustomAdaptationInterceptor()) + client = AdaptationClient(transport=transport) + + + """ + + def pre_create_custom_class( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.CreateCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for create_custom_class + + DEPRECATED. Please use the `post_create_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_create_custom_class` interceptor runs + before the `post_create_custom_class_with_metadata` interceptor. + """ + return response + + def post_create_custom_class_with_metadata( + self, + response: resource.CustomClass, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.CustomClass, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_create_custom_class_with_metadata` + interceptor in new development instead of the `post_create_custom_class` interceptor. + When both interceptors are used, this `post_create_custom_class_with_metadata` interceptor runs after the + `post_create_custom_class` interceptor. The (possibly modified) response returned by + `post_create_custom_class` will be passed to + `post_create_custom_class_with_metadata`. + """ + return response, metadata + + def pre_create_phrase_set( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.CreatePhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for create_phrase_set + + DEPRECATED. Please use the `post_create_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_create_phrase_set` interceptor runs + before the `post_create_phrase_set_with_metadata` interceptor. + """ + return response + + def post_create_phrase_set_with_metadata( + self, + response: resource.PhraseSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.PhraseSet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_create_phrase_set_with_metadata` + interceptor in new development instead of the `post_create_phrase_set` interceptor. + When both interceptors are used, this `post_create_phrase_set_with_metadata` interceptor runs after the + `post_create_phrase_set` interceptor. The (possibly modified) response returned by + `post_create_phrase_set` will be passed to + `post_create_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_delete_custom_class( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.DeleteCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_delete_phrase_set( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.DeletePhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_get_custom_class( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.GetCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for get_custom_class + + DEPRECATED. Please use the `post_get_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_get_custom_class` interceptor runs + before the `post_get_custom_class_with_metadata` interceptor. + """ + return response + + def post_get_custom_class_with_metadata( + self, + response: resource.CustomClass, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.CustomClass, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_get_custom_class_with_metadata` + interceptor in new development instead of the `post_get_custom_class` interceptor. + When both interceptors are used, this `post_get_custom_class_with_metadata` interceptor runs after the + `post_get_custom_class` interceptor. The (possibly modified) response returned by + `post_get_custom_class` will be passed to + `post_get_custom_class_with_metadata`. + """ + return response, metadata + + def pre_get_phrase_set( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.GetPhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_phrase_set(self, response: resource.PhraseSet) -> resource.PhraseSet: + """Post-rpc interceptor for get_phrase_set + + DEPRECATED. Please use the `post_get_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_get_phrase_set` interceptor runs + before the `post_get_phrase_set_with_metadata` interceptor. + """ + return response + + def post_get_phrase_set_with_metadata( + self, + response: resource.PhraseSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.PhraseSet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_get_phrase_set_with_metadata` + interceptor in new development instead of the `post_get_phrase_set` interceptor. + When both interceptors are used, this `post_get_phrase_set_with_metadata` interceptor runs after the + `post_get_phrase_set` interceptor. The (possibly modified) response returned by + `post_get_phrase_set` will be passed to + `post_get_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_list_custom_classes( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListCustomClassesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_custom_classes( + self, response: cloud_speech_adaptation.ListCustomClassesResponse + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + """Post-rpc interceptor for list_custom_classes + + DEPRECATED. Please use the `post_list_custom_classes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_list_custom_classes` interceptor runs + before the `post_list_custom_classes_with_metadata` interceptor. + """ + return response + + def post_list_custom_classes_with_metadata( + self, + response: cloud_speech_adaptation.ListCustomClassesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListCustomClassesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_custom_classes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_list_custom_classes_with_metadata` + interceptor in new development instead of the `post_list_custom_classes` interceptor. + When both interceptors are used, this `post_list_custom_classes_with_metadata` interceptor runs after the + `post_list_custom_classes` interceptor. The (possibly modified) response returned by + `post_list_custom_classes` will be passed to + `post_list_custom_classes_with_metadata`. + """ + return response, metadata + + def pre_list_phrase_set( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListPhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_phrase_set( + self, response: cloud_speech_adaptation.ListPhraseSetResponse + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + """Post-rpc interceptor for list_phrase_set + + DEPRECATED. Please use the `post_list_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_list_phrase_set` interceptor runs + before the `post_list_phrase_set_with_metadata` interceptor. + """ + return response + + def post_list_phrase_set_with_metadata( + self, + response: cloud_speech_adaptation.ListPhraseSetResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.ListPhraseSetResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_list_phrase_set_with_metadata` + interceptor in new development instead of the `post_list_phrase_set` interceptor. + When both interceptors are used, this `post_list_phrase_set_with_metadata` interceptor runs after the + `post_list_phrase_set` interceptor. The (possibly modified) response returned by + `post_list_phrase_set` will be passed to + `post_list_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_update_custom_class( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.UpdateCustomClassRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for update_custom_class + + DEPRECATED. Please use the `post_update_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_update_custom_class` interceptor runs + before the `post_update_custom_class_with_metadata` interceptor. + """ + return response + + def post_update_custom_class_with_metadata( + self, + response: resource.CustomClass, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.CustomClass, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_update_custom_class_with_metadata` + interceptor in new development instead of the `post_update_custom_class` interceptor. + When both interceptors are used, this `post_update_custom_class_with_metadata` interceptor runs after the + `post_update_custom_class` interceptor. The (possibly modified) response returned by + `post_update_custom_class` will be passed to + `post_update_custom_class_with_metadata`. + """ + return response, metadata + + def pre_update_phrase_set( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech_adaptation.UpdatePhraseSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for update_phrase_set + + DEPRECATED. Please use the `post_update_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. This `post_update_phrase_set` interceptor runs + before the `post_update_phrase_set_with_metadata` interceptor. + """ + return response + + def post_update_phrase_set_with_metadata( + self, + response: resource.PhraseSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.PhraseSet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Adaptation server but before it is returned to user code. + + We recommend only using this `post_update_phrase_set_with_metadata` + interceptor in new development instead of the `post_update_phrase_set` interceptor. + When both interceptors are used, this `post_update_phrase_set_with_metadata` interceptor runs after the + `post_update_phrase_set` interceptor. The (possibly modified) response returned by + `post_update_phrase_set` will be passed to + `post_update_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AdaptationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AdaptationRestInterceptor + + +class AdaptationRestTransport(_BaseAdaptationRestTransport): + """REST backend synchronous 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 JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AdaptationRestInterceptor] = None, + 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. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AdaptationRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AdaptationRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCustomClass( + _BaseAdaptationRestTransport._BaseCreateCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.CreateCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Call the create custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreateCustomClassRequest): + The request object. Message sent by the client for the ``CreateCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.CustomClass: + 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. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseCreateCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseCreateCustomClass._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseCreateCustomClass._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseCreateCustomClass._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.CreateCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "CreateCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._CreateCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.CustomClass.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.create_custom_class", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "CreateCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreatePhraseSet( + _BaseAdaptationRestTransport._BaseCreatePhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.CreatePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Call the create phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreatePhraseSetRequest): + The request object. Message sent by the client for the ``CreatePhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_phrase_set( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseCreatePhraseSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.CreatePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "CreatePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._CreatePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.PhraseSet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.create_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "CreatePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteCustomClass( + _BaseAdaptationRestTransport._BaseDeleteCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.DeleteCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeleteCustomClassRequest): + The request object. Message sent by the client for the ``DeleteCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseDeleteCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseDeleteCustomClass._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseDeleteCustomClass._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.DeleteCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "DeleteCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._DeleteCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeletePhraseSet( + _BaseAdaptationRestTransport._BaseDeletePhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.DeletePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeletePhraseSetRequest): + The request object. Message sent by the client for the ``DeletePhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseDeletePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_phrase_set( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseDeletePhraseSet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseDeletePhraseSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.DeletePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "DeletePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._DeletePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetCustomClass( + _BaseAdaptationRestTransport._BaseGetCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.GetCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Call the get custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetCustomClassRequest): + The request object. Message sent by the client for the ``GetCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.CustomClass: + 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. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseGetCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseGetCustomClass._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseGetCustomClass._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.GetCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "GetCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._GetCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.CustomClass.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.get_custom_class", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "GetCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPhraseSet( + _BaseAdaptationRestTransport._BaseGetPhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.GetPhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Call the get phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetPhraseSetRequest): + The request object. Message sent by the client for the ``GetPhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseGetPhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_phrase_set(request, metadata) + transcoded_request = ( + _BaseAdaptationRestTransport._BaseGetPhraseSet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseGetPhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.GetPhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "GetPhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._GetPhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.PhraseSet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.get_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "GetPhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListCustomClasses( + _BaseAdaptationRestTransport._BaseListCustomClasses, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.ListCustomClasses") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + r"""Call the list custom classes method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListCustomClassesRequest): + The request object. Message sent by the client for the ``ListCustomClasses`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech_adaptation.ListCustomClassesResponse: + Message returned to the client by the + ``ListCustomClasses`` method. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseListCustomClasses._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_custom_classes( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseListCustomClasses._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseListCustomClasses._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.ListCustomClasses", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "ListCustomClasses", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._ListCustomClasses._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech_adaptation.ListCustomClassesResponse() + pb_resp = cloud_speech_adaptation.ListCustomClassesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_custom_classes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_custom_classes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cloud_speech_adaptation.ListCustomClassesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.list_custom_classes", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "ListCustomClasses", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPhraseSet( + _BaseAdaptationRestTransport._BaseListPhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.ListPhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + r"""Call the list phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListPhraseSetRequest): + The request object. Message sent by the client for the ``ListPhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech_adaptation.ListPhraseSetResponse: + Message returned to the client by the ``ListPhraseSet`` + method. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseListPhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_phrase_set(request, metadata) + transcoded_request = ( + _BaseAdaptationRestTransport._BaseListPhraseSet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseListPhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.ListPhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "ListPhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._ListPhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech_adaptation.ListPhraseSetResponse() + pb_resp = cloud_speech_adaptation.ListPhraseSetResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cloud_speech_adaptation.ListPhraseSetResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.list_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "ListPhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCustomClass( + _BaseAdaptationRestTransport._BaseUpdateCustomClass, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.UpdateCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.CustomClass: + r"""Call the update custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdateCustomClassRequest): + The request object. Message sent by the client for the ``UpdateCustomClass`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.CustomClass: + 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. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_custom_class( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseUpdateCustomClass._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.UpdateCustomClass", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "UpdateCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._UpdateCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.CustomClass.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.update_custom_class", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "UpdateCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePhraseSet( + _BaseAdaptationRestTransport._BaseUpdatePhraseSet, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.UpdatePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.PhraseSet: + r"""Call the update phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdatePhraseSetRequest): + The request object. Message sent by the client for the ``UpdatePhraseSet`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_phrase_set( + request, metadata + ) + transcoded_request = _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_transcoded_request( + http_options, request + ) + + body = _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdaptationRestTransport._BaseUpdatePhraseSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.UpdatePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "UpdatePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._UpdatePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.PhraseSet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationClient.update_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "UpdatePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.CreateCustomClassRequest], resource.CustomClass + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.CreatePhraseSetRequest], resource.PhraseSet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_custom_class( + self, + ) -> Callable[[cloud_speech_adaptation.DeleteCustomClassRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.DeletePhraseSetRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.GetCustomClassRequest], resource.CustomClass + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.GetPhraseSetRequest], resource.PhraseSet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListCustomClassesRequest], + cloud_speech_adaptation.ListCustomClassesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCustomClasses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_phrase_set( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListPhraseSetRequest], + cloud_speech_adaptation.ListPhraseSetResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.UpdateCustomClassRequest], resource.CustomClass + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.UpdatePhraseSetRequest], resource.PhraseSet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseAdaptationRestTransport._BaseGetOperation, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: Response from GetOperation method. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseAdaptationRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseAdaptationRestTransport._BaseListOperations, AdaptationRestStub + ): + def __hash__(self): + return hash("AdaptationRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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 from ListOperations method. + """ + + http_options = ( + _BaseAdaptationRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseAdaptationRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAdaptationRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.AdaptationClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdaptationRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.AdaptationAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Adaptation", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AdaptationRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b7bff337e320774c15d86857af52f27b27ec4b13 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest_base.py @@ -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 + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +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_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("^(?Phttp(?:s)?://)?(?P.*)$", 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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46fd4742bf9bf09f5d77f5b776940109094160b2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb26978c91b27d4d4b929535f74b006ae589913 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/async_client.py @@ -0,0 +1,866 @@ +# -*- 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +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 + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from google.longrunning import operations_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. + """ + sa_info_func = ( + SpeechClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SpeechAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SpeechAsyncClient: The constructed client. + """ + sa_file_func = ( + SpeechClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(SpeechAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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) -> str: + """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 `__. + + .. 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 + \`StreamingRecognizeResponse`s 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[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SpeechAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/client.py new file mode 100644 index 0000000000000000000000000000000000000000..eebe201ddf2e284158b589ad2a3893cd4000290a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/client.py @@ -0,0 +1,1374 @@ +# -*- 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 os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.speech_v1p1beta1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.speech_v1p1beta1.types import cloud_speech + +from .transports.base import DEFAULT_CLIENT_INFO, SpeechTransport +from .transports.grpc import SpeechGrpcTransport +from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport +from .transports.rest import SpeechRestTransport + + +class SpeechClientMeta(type): + """Metaclass for the Speech client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] + _transport_registry["grpc"] = SpeechGrpcTransport + _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport + _transport_registry["rest"] = SpeechRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SpeechTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SpeechClient(metaclass=SpeechClientMeta): + """Service that implements Google Cloud Speech API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "speech.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "speech.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + SpeechClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SpeechClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SpeechTransport: + """Returns the transport used by the client instance. + + Returns: + SpeechTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + crypto_key_version: str, + ) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str, str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_class_path( + project: str, + location: str, + custom_class: str, + ) -> str: + """Returns a fully-qualified custom_class string.""" + return "projects/{project}/locations/{location}/customClasses/{custom_class}".format( + project=project, + location=location, + custom_class=custom_class, + ) + + @staticmethod + def parse_custom_class_path(path: str) -> Dict[str, str]: + """Parses a custom_class path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/customClasses/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def phrase_set_path( + project: str, + location: str, + phrase_set: str, + ) -> str: + """Returns a fully-qualified phrase_set string.""" + return "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( + project=project, + location=location, + phrase_set=phrase_set, + ) + + @staticmethod + def parse_phrase_set_path(path: str) -> Dict[str, str]: + """Parses a phrase_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/phraseSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. 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. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = SpeechClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = SpeechClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SpeechClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SpeechClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SpeechClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SpeechClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._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._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SpeechTransport, Callable[..., SpeechTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the speech 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. + 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 the ``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_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + SpeechClient._read_environment_variables() + ) + self._client_cert_source = SpeechClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SpeechClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SpeechTransport) + if transport_provided: + # transport is a SpeechTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(SpeechTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or SpeechClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SpeechTransport], Callable[..., SpeechTransport] + ] = ( + SpeechClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SpeechTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.speech_v1p1beta1.SpeechClient`.", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "credentialsType": None, + }, + ) + + 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 + + def sample_recognize(): + # Create a client + client = speech_v1p1beta1.SpeechClient() + + # 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 = client.recognize(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.RecognizeRequest, dict]): + The request object. The top-level message sent by the client for the + ``Recognize`` method. + config (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 (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.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`. + + 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._transport._wrapped_methods[self._transport.recognize] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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.Operation: + 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 `__. + + .. 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 + + def sample_long_running_recognize(): + # Create a client + client = speech_v1p1beta1.SpeechClient() + + # 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 = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v1p1beta1.types.LongRunningRecognizeRequest, dict]): + The request object. The top-level message sent by the client for the + ``LongRunningRecognize`` method. + config (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 (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.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`. + + Returns: + google.api_core.operation.Operation: + 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._transport._wrapped_methods[self._transport.long_running_recognize] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.LongRunningRecognizeResponse, + metadata_type=cloud_speech.LongRunningRecognizeMetadata, + ) + + # Done; return the response. + return response + + def streaming_recognize( + self, + requests: Optional[Iterator[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]]] = (), + ) -> Iterable[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 + + def sample_streaming_recognize(): + # Create a client + client = speech_v1p1beta1.SpeechClient() + + # 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 = client.streaming_recognize(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.speech_v1p1beta1.types.StreamingRecognizeRequest]): + The request object iterator. 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.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`. + + Returns: + Iterable[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 + \`StreamingRecognizeResponse`s 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._transport._wrapped_methods[self._transport.streaming_recognize] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SpeechClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SpeechClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5150a365b2d2d5454e96bdaf2968ca4dc59ba6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..02f87623780f99d593fde19ad3dc061aa85fd096 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/base.py @@ -0,0 +1,265 @@ +# -*- 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 +import google.auth # type: ignore +import google.protobuf +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 +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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd7ee11958f6641b557ce61f6d8f5aaf8e08e4d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py @@ -0,0 +1,479 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +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)!r}" + + 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 = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC 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)!r}" + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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 `__. + + 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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..02465bbbf5febd8c57fa757bb907dded5be39a4b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py @@ -0,0 +1,546 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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 +from grpc.experimental import aio # 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)!r}" + + 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 `` 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)!r}" + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 `__. + + 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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..808cefe2d3931f2c07914476fce4aabd08d6186f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/rest.py @@ -0,0 +1,1023 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.speech_v1p1beta1.types import cloud_speech + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSpeechRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SpeechRestInterceptor: + """Interceptor for Speech. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SpeechRestTransport. + + .. code-block:: python + class MyCustomSpeechInterceptor(SpeechRestInterceptor): + def pre_long_running_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_long_running_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SpeechRestTransport(interceptor=MyCustomSpeechInterceptor()) + client = SpeechClient(transport=transport) + + + """ + + def pre_long_running_recognize( + self, + request: cloud_speech.LongRunningRecognizeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.LongRunningRecognizeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for long_running_recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_long_running_recognize( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for long_running_recognize + + DEPRECATED. Please use the `post_long_running_recognize_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_long_running_recognize` interceptor runs + before the `post_long_running_recognize_with_metadata` interceptor. + """ + return response + + def post_long_running_recognize_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for long_running_recognize + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_long_running_recognize_with_metadata` + interceptor in new development instead of the `post_long_running_recognize` interceptor. + When both interceptors are used, this `post_long_running_recognize_with_metadata` interceptor runs after the + `post_long_running_recognize` interceptor. The (possibly modified) response returned by + `post_long_running_recognize` will be passed to + `post_long_running_recognize_with_metadata`. + """ + return response, metadata + + def pre_recognize( + self, + request: cloud_speech.RecognizeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.RecognizeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_recognize( + self, response: cloud_speech.RecognizeResponse + ) -> cloud_speech.RecognizeResponse: + """Post-rpc interceptor for recognize + + DEPRECATED. Please use the `post_recognize_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_recognize` interceptor runs + before the `post_recognize_with_metadata` interceptor. + """ + return response + + def post_recognize_with_metadata( + self, + response: cloud_speech.RecognizeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.RecognizeResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for recognize + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_recognize_with_metadata` + interceptor in new development instead of the `post_recognize` interceptor. + When both interceptors are used, this `post_recognize_with_metadata` interceptor runs after the + `post_recognize` interceptor. The (possibly modified) response returned by + `post_recognize` will be passed to + `post_recognize_with_metadata`. + """ + return response, metadata + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SpeechRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SpeechRestInterceptor + + +class SpeechRestTransport(_BaseSpeechRestTransport): + """REST backend synchronous 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 JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SpeechRestInterceptor] = None, + 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. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[SpeechRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SpeechRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1p1beta1/operations/{name=**}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1p1beta1/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1p1beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _LongRunningRecognize( + _BaseSpeechRestTransport._BaseLongRunningRecognize, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.LongRunningRecognize") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.LongRunningRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the long running recognize method over HTTP. + + Args: + request (~.cloud_speech.LongRunningRecognizeRequest): + The request object. The top-level message sent by the client for the + ``LongRunningRecognize`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseLongRunningRecognize._get_http_options() + ) + + request, metadata = self._interceptor.pre_long_running_recognize( + request, metadata + ) + transcoded_request = _BaseSpeechRestTransport._BaseLongRunningRecognize._get_transcoded_request( + http_options, request + ) + + body = _BaseSpeechRestTransport._BaseLongRunningRecognize._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSpeechRestTransport._BaseLongRunningRecognize._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.SpeechClient.LongRunningRecognize", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "LongRunningRecognize", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._LongRunningRecognize._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_long_running_recognize(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_long_running_recognize_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.SpeechClient.long_running_recognize", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "LongRunningRecognize", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Recognize(_BaseSpeechRestTransport._BaseRecognize, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.Recognize") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.RecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.RecognizeResponse: + r"""Call the recognize method over HTTP. + + Args: + request (~.cloud_speech.RecognizeRequest): + The request object. The top-level message sent by the client for the + ``Recognize`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.RecognizeResponse: + The only message returned to the client by the + ``Recognize`` method. It contains the result as zero or + more sequential ``SpeechRecognitionResult`` messages. + + """ + + http_options = _BaseSpeechRestTransport._BaseRecognize._get_http_options() + + request, metadata = self._interceptor.pre_recognize(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseRecognize._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseRecognize._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseRecognize._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.SpeechClient.Recognize", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "Recognize", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._Recognize._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.RecognizeResponse() + pb_resp = cloud_speech.RecognizeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_recognize(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_recognize_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.RecognizeResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.SpeechClient.recognize", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "Recognize", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StreamingRecognize( + _BaseSpeechRestTransport._BaseStreamingRecognize, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.StreamingRecognize") + + def __call__( + self, + request: cloud_speech.StreamingRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamingRecognize is not available over REST transport" + ) + + @property + def long_running_recognize( + self, + ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._LongRunningRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def recognize( + self, + ) -> Callable[[cloud_speech.RecognizeRequest], cloud_speech.RecognizeResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Recognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def streaming_recognize( + self, + ) -> Callable[ + [cloud_speech.StreamingRecognizeRequest], + cloud_speech.StreamingRecognizeResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StreamingRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseSpeechRestTransport._BaseGetOperation, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: Response from GetOperation method. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.SpeechClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.SpeechAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseSpeechRestTransport._BaseListOperations, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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 from ListOperations method. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v1p1beta1.SpeechClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v1p1beta1.SpeechAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v1p1beta1.Speech", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SpeechRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..17f89c4022ddcdb2cb5283a73d9e228cf047ea8d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/services/speech/transports/rest_base.py @@ -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("^(?Phttp(?:s)?://)?(?P.*)$", 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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9be07ebb5897000fc532bdfa0af40ba709af0d28 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/__init__.py @@ -0,0 +1,94 @@ +# -*- 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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/cloud_speech.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/cloud_speech.py new file mode 100644 index 0000000000000000000000000000000000000000..bff80c0adc7b1c365136e6fe24ff10b774bebe59 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/cloud_speech.py @@ -0,0 +1,1609 @@ +# -*- 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 + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.speech_v1p1beta1.types import resource + +__protobuf__ = proto.module( + package="google.cloud.speech.v1p1beta1", + manifest={ + "RecognizeRequest", + "LongRunningRecognizeRequest", + "TranscriptOutputConfig", + "StreamingRecognizeRequest", + "StreamingRecognitionConfig", + "RecognitionConfig", + "SpeakerDiarizationConfig", + "RecognitionMetadata", + "SpeechContext", + "RecognitionAudio", + "RecognizeResponse", + "LongRunningRecognizeResponse", + "LongRunningRecognizeMetadata", + "StreamingRecognizeResponse", + "StreamingRecognitionResult", + "SpeechRecognitionResult", + "SpeechRecognitionAlternative", + "WordInfo", + "SpeechAdaptationInfo", + }, +) + + +class RecognizeRequest(proto.Message): + r"""The top-level message sent by the client for the ``Recognize`` + method. + + Attributes: + config (google.cloud.speech_v1p1beta1.types.RecognitionConfig): + Required. Provides information to the + recognizer that specifies how to process the + request. + audio (google.cloud.speech_v1p1beta1.types.RecognitionAudio): + Required. The audio data to be recognized. + """ + + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + audio: "RecognitionAudio" = proto.Field( + proto.MESSAGE, + number=2, + message="RecognitionAudio", + ) + + +class LongRunningRecognizeRequest(proto.Message): + r"""The top-level message sent by the client for the + ``LongRunningRecognize`` method. + + Attributes: + config (google.cloud.speech_v1p1beta1.types.RecognitionConfig): + Required. Provides information to the + recognizer that specifies how to process the + request. + audio (google.cloud.speech_v1p1beta1.types.RecognitionAudio): + Required. The audio data to be recognized. + output_config (google.cloud.speech_v1p1beta1.types.TranscriptOutputConfig): + Optional. Specifies an optional destination + for the recognition results. + """ + + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + audio: "RecognitionAudio" = proto.Field( + proto.MESSAGE, + number=2, + message="RecognitionAudio", + ) + output_config: "TranscriptOutputConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="TranscriptOutputConfig", + ) + + +class TranscriptOutputConfig(proto.Message): + r"""Specifies an optional destination for the recognition + results. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_uri (str): + Specifies a Cloud Storage URI for the recognition results. + Must be specified in the format: + ``gs://bucket_name/object_name``, and the bucket must + already exist. + + This field is a member of `oneof`_ ``output_type``. + """ + + gcs_uri: str = proto.Field( + proto.STRING, + number=1, + oneof="output_type", + ) + + +class StreamingRecognizeRequest(proto.Message): + r"""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. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + streaming_config (google.cloud.speech_v1p1beta1.types.StreamingRecognitionConfig): + Provides information to the recognizer that specifies how to + process the request. The first ``StreamingRecognizeRequest`` + message must contain a ``streaming_config`` message. + + This field is a member of `oneof`_ ``streaming_request``. + audio_content (bytes): + The audio data to be recognized. Sequential chunks of audio + data are sent in sequential ``StreamingRecognizeRequest`` + messages. The first ``StreamingRecognizeRequest`` message + must not contain ``audio_content`` data and all subsequent + ``StreamingRecognizeRequest`` messages must contain + ``audio_content`` data. The audio bytes must be encoded as + specified in ``RecognitionConfig``. Note: as with all bytes + fields, proto buffers use a pure binary representation (not + base64). See `content + limits `__. + + This field is a member of `oneof`_ ``streaming_request``. + """ + + streaming_config: "StreamingRecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="streaming_request", + message="StreamingRecognitionConfig", + ) + audio_content: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="streaming_request", + ) + + +class StreamingRecognitionConfig(proto.Message): + r"""Provides information to the recognizer that specifies how to + process the request. + + Attributes: + config (google.cloud.speech_v1p1beta1.types.RecognitionConfig): + Required. Provides information to the + recognizer that specifies how to process the + request. + single_utterance (bool): + If ``false`` or omitted, the recognizer will perform + continuous recognition (continuing to wait for and process + audio even if the user pauses speaking) until the client + closes the input stream (gRPC API) or until the maximum time + limit has been reached. May return multiple + ``StreamingRecognitionResult``\ s with the ``is_final`` flag + set to ``true``. + + If ``true``, the recognizer will detect a single spoken + utterance. When it detects that the user has paused or + stopped speaking, it will return an + ``END_OF_SINGLE_UTTERANCE`` event and cease recognition. It + will return no more than one ``StreamingRecognitionResult`` + with the ``is_final`` flag set to ``true``. + + The ``single_utterance`` field can only be used with + specified models, otherwise an error is thrown. The + ``model`` field in + [RecognitionConfig][google.cloud.speech.v1p1beta1.RecognitionConfig] + must be set to: + + - ``command_and_search`` + - ``phone_call`` AND additional field + ``useEnhanced``\ =\ ``true`` + - The ``model`` field is left undefined. In this case the + API auto-selects a model based on any other parameters + that you set in ``RecognitionConfig``. + interim_results (bool): + If ``true``, interim results (tentative hypotheses) may be + returned as they become available (these interim results are + indicated with the ``is_final=false`` flag). If ``false`` or + omitted, only ``is_final=true`` result(s) are returned. + enable_voice_activity_events (bool): + If ``true``, responses with voice activity speech events + will be returned as they are detected. + voice_activity_timeout (google.cloud.speech_v1p1beta1.types.StreamingRecognitionConfig.VoiceActivityTimeout): + If set, the server will automatically close the stream after + the specified duration has elapsed after the last + VOICE_ACTIVITY speech event has been sent. The field + ``voice_activity_events`` must also be set to true. + """ + + class VoiceActivityTimeout(proto.Message): + r"""Events that a timeout can be set on for voice activity. + + Attributes: + speech_start_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream if no speech + begins. + speech_end_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream after speech + ends. + """ + + speech_start_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + speech_end_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + single_utterance: bool = proto.Field( + proto.BOOL, + number=2, + ) + interim_results: bool = proto.Field( + proto.BOOL, + number=3, + ) + enable_voice_activity_events: bool = proto.Field( + proto.BOOL, + number=5, + ) + voice_activity_timeout: VoiceActivityTimeout = proto.Field( + proto.MESSAGE, + number=6, + message=VoiceActivityTimeout, + ) + + +class RecognitionConfig(proto.Message): + r"""Provides information to the recognizer that specifies how to + process the request. + + Attributes: + encoding (google.cloud.speech_v1p1beta1.types.RecognitionConfig.AudioEncoding): + Encoding of audio data sent in all ``RecognitionAudio`` + messages. This field is optional for ``FLAC`` and ``WAV`` + audio files and required for all other audio formats. For + details, see + [AudioEncoding][google.cloud.speech.v1p1beta1.RecognitionConfig.AudioEncoding]. + sample_rate_hertz (int): + Sample rate in Hertz of the audio data sent in all + ``RecognitionAudio`` messages. Valid values are: 8000-48000. + 16000 is optimal. For best results, set the sampling rate of + the audio source to 16000 Hz. If that's not possible, use + the native sample rate of the audio source (instead of + re-sampling). This field is optional for FLAC and WAV audio + files, but is required for all other audio formats. For + details, see + [AudioEncoding][google.cloud.speech.v1p1beta1.RecognitionConfig.AudioEncoding]. + audio_channel_count (int): + The number of channels in the input audio data. ONLY set + this for MULTI-CHANNEL recognition. Valid values for + LINEAR16, OGG_OPUS and FLAC are ``1``-``8``. Valid value for + MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only ``1``. + If ``0`` or omitted, defaults to one channel (mono). Note: + We only recognize the first channel by default. To perform + independent recognition on each channel set + ``enable_separate_recognition_per_channel`` to 'true'. + enable_separate_recognition_per_channel (bool): + This needs to be set to ``true`` explicitly and + ``audio_channel_count`` > 1 to get each channel recognized + separately. The recognition result will contain a + ``channel_tag`` field to state which channel that result + belongs to. If this is not true, we will only recognize the + first channel. The request is billed cumulatively for all + channels recognized: ``audio_channel_count`` multiplied by + the length of the audio. + language_code (str): + Required. The language of the supplied audio as a + `BCP-47 `__ + language tag. Example: "en-US". See `Language + Support `__ + for a list of the currently supported language codes. + alternative_language_codes (MutableSequence[str]): + A list of up to 3 additional + `BCP-47 `__ + language tags, listing possible alternative languages of the + supplied audio. See `Language + Support `__ + for a list of the currently supported language codes. If + alternative languages are listed, recognition result will + contain recognition in the most likely language detected + including the main language_code. The recognition result + will include the language tag of the language detected in + the audio. Note: This feature is only supported for Voice + Command and Voice Search use cases and performance may vary + for other use cases (e.g., phone call transcription). + max_alternatives (int): + Maximum number of recognition hypotheses to be returned. + Specifically, the maximum number of + ``SpeechRecognitionAlternative`` messages within each + ``SpeechRecognitionResult``. The server may return fewer + than ``max_alternatives``. Valid values are ``0``-``30``. A + value of ``0`` or ``1`` will return a maximum of one. If + omitted, will return a maximum of one. + profanity_filter (bool): + If set to ``true``, the server will attempt to filter out + profanities, replacing all but the initial character in each + filtered word with asterisks, e.g. "f**\*". If set to + ``false`` or omitted, profanities won't be filtered out. + adaptation (google.cloud.speech_v1p1beta1.types.SpeechAdaptation): + Speech adaptation configuration improves the accuracy of + speech recognition. For more information, see the `speech + adaptation `__ + documentation. When speech adaptation is set it supersedes + the ``speech_contexts`` field. + transcript_normalization (google.cloud.speech_v1p1beta1.types.TranscriptNormalization): + Optional. 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. + speech_contexts (MutableSequence[google.cloud.speech_v1p1beta1.types.SpeechContext]): + Array of + [SpeechContext][google.cloud.speech.v1p1beta1.SpeechContext]. + A means to provide context to assist the speech recognition. + For more information, see `speech + adaptation `__. + enable_word_time_offsets (bool): + If ``true``, the top result includes a list of words and the + start and end time offsets (timestamps) for those words. If + ``false``, no word-level time offset information is + returned. The default is ``false``. + enable_word_confidence (bool): + If ``true``, the top result includes a list of words and the + confidence for those words. If ``false``, no word-level + confidence information is returned. The default is + ``false``. + enable_automatic_punctuation (bool): + If 'true', adds punctuation to recognition + result hypotheses. This feature is only + available in select languages. Setting this for + requests in other languages has no effect at + all. The default 'false' value does not add + punctuation to result hypotheses. + enable_spoken_punctuation (google.protobuf.wrappers_pb2.BoolValue): + The spoken punctuation behavior for the call If not set, + uses default behavior based on model of choice e.g. + command_and_search will enable spoken punctuation by default + If 'true', replaces spoken punctuation with the + corresponding symbols in the request. For example, "how are + you question mark" becomes "how are you?". See + https://cloud.google.com/speech-to-text/docs/spoken-punctuation + for support. If 'false', spoken punctuation is not replaced. + enable_spoken_emojis (google.protobuf.wrappers_pb2.BoolValue): + The spoken emoji behavior for the call + If not set, uses default behavior based on model + of choice If 'true', adds spoken emoji + formatting for the request. This will replace + spoken emojis with the corresponding Unicode + symbols in the final transcript. If 'false', + spoken emojis are not replaced. + enable_speaker_diarization (bool): + If 'true', enables speaker detection for each recognized + word in the top alternative of the recognition result using + a speaker_label provided in the WordInfo. Note: Use + diarization_config instead. + diarization_speaker_count (int): + If set, specifies the estimated number of speakers in the + conversation. Defaults to '2'. Ignored unless + enable_speaker_diarization is set to true. Note: Use + diarization_config instead. + diarization_config (google.cloud.speech_v1p1beta1.types.SpeakerDiarizationConfig): + Config to enable speaker diarization and set + additional parameters to make diarization better + suited for your application. Note: When this is + enabled, we send all the words from the + beginning of the audio for the top alternative + in every consecutive STREAMING responses. This + is done in order to improve our speaker tags as + our models learn to identify the speakers in the + conversation over time. For non-streaming + requests, the diarization results will be + provided only in the top alternative of the + FINAL SpeechRecognitionResult. + metadata (google.cloud.speech_v1p1beta1.types.RecognitionMetadata): + Metadata regarding this request. + model (str): + Which model to select for the given request. Select the + model best suited to your domain to get best results. If a + model is not explicitly specified, then we auto-select a + model based on the parameters in the RecognitionConfig. + + .. raw:: html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelDescription
latest_longBest for long form content like media or conversation.
latest_shortBest for short form content like commands or single shot directed + speech.
command_and_searchBest for short queries such as voice commands or voice search.
phone_callBest for audio that originated from a phone call (typically + recorded at an 8khz sampling rate).
videoBest for audio that originated from video or includes multiple + speakers. Ideally the audio is recorded at a 16khz or greater + sampling rate. This is a premium model that costs more than the + standard rate.
defaultBest for audio that is not one of the specific audio models. + For example, long-form audio. Ideally the audio is high-fidelity, + recorded at a 16khz or greater sampling rate.
medical_conversationBest for audio that originated from a conversation between a + medical provider and patient.
medical_dictationBest for audio that originated from dictation notes by a medical + provider.
+ use_enhanced (bool): + Set to true to use an enhanced model for speech recognition. + If ``use_enhanced`` is set to true and the ``model`` field + is not set, then an appropriate enhanced model is chosen if + an enhanced model exists for the audio. + + If ``use_enhanced`` is true and an enhanced version of the + specified model does not exist, then the speech is + recognized using the standard version of the specified + model. + """ + + class AudioEncoding(proto.Enum): + r"""The encoding of the audio data sent in the request. + + All encodings support only 1 channel (mono) audio, unless the + ``audio_channel_count`` and + ``enable_separate_recognition_per_channel`` fields are set. + + For best results, the audio source should be captured and + transmitted using a lossless encoding (``FLAC`` or ``LINEAR16``). + The accuracy of the speech recognition can be reduced if lossy + codecs are used to capture or transmit audio, particularly if + background noise is present. Lossy codecs include ``MULAW``, + ``AMR``, ``AMR_WB``, ``OGG_OPUS``, ``SPEEX_WITH_HEADER_BYTE``, + ``MP3``, and ``WEBM_OPUS``. + + The ``FLAC`` and ``WAV`` audio file formats include a header that + describes the included audio content. You can request recognition + for ``WAV`` files that contain either ``LINEAR16`` or ``MULAW`` + encoded audio. If you send ``FLAC`` or ``WAV`` audio file format in + your request, you do not need to specify an ``AudioEncoding``; the + audio encoding format is determined from the file header. If you + specify an ``AudioEncoding`` when you send send ``FLAC`` or ``WAV`` + audio, the encoding configuration must match the encoding described + in the audio header; otherwise the request returns an + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] + error code. + + Values: + ENCODING_UNSPECIFIED (0): + Not specified. + LINEAR16 (1): + Uncompressed 16-bit signed little-endian + samples (Linear PCM). + FLAC (2): + ``FLAC`` (Free Lossless Audio Codec) is the recommended + encoding because it is lossless--therefore recognition is + not compromised--and requires only about half the bandwidth + of ``LINEAR16``. ``FLAC`` stream encoding supports 16-bit + and 24-bit samples, however, not all fields in + ``STREAMINFO`` are supported. + MULAW (3): + 8-bit samples that compand 14-bit audio + samples using G.711 PCMU/mu-law. + AMR (4): + Adaptive Multi-Rate Narrowband codec. ``sample_rate_hertz`` + must be 8000. + AMR_WB (5): + Adaptive Multi-Rate Wideband codec. ``sample_rate_hertz`` + must be 16000. + OGG_OPUS (6): + Opus encoded audio frames in Ogg container + (`OggOpus `__). + ``sample_rate_hertz`` must be one of 8000, 12000, 16000, + 24000, or 48000. + SPEEX_WITH_HEADER_BYTE (7): + Although the use of lossy encodings is not recommended, if a + very low bitrate encoding is required, ``OGG_OPUS`` is + highly preferred over Speex encoding. The + `Speex `__ encoding supported by Cloud + Speech API has a header byte in each block, as in MIME type + ``audio/x-speex-with-header-byte``. It is a variant of the + RTP Speex encoding defined in `RFC + 5574 `__. The stream is + a sequence of blocks, one block per RTP packet. Each block + starts with a byte containing the length of the block, in + bytes, followed by one or more frames of Speex data, padded + to an integral number of bytes (octets) as specified in RFC + 5574. In other words, each RTP header is replaced with a + single byte containing the block length. Only Speex wideband + is supported. ``sample_rate_hertz`` must be 16000. + MP3 (8): + MP3 audio. MP3 encoding is a Beta feature and only available + in v1p1beta1. Support all standard MP3 bitrates (which range + from 32-320 kbps). When using this encoding, + ``sample_rate_hertz`` has to match the sample rate of the + file being used. + WEBM_OPUS (9): + Opus encoded audio frames in WebM container + (`WebM `__). + ``sample_rate_hertz`` must be one of 8000, 12000, 16000, + 24000, or 48000. + ALAW (10): + 8-bit samples that compand 13-bit audio + samples using G.711 PCMU/a-law. + """ + + ENCODING_UNSPECIFIED = 0 + LINEAR16 = 1 + FLAC = 2 + MULAW = 3 + AMR = 4 + AMR_WB = 5 + OGG_OPUS = 6 + SPEEX_WITH_HEADER_BYTE = 7 + MP3 = 8 + WEBM_OPUS = 9 + ALAW = 10 + + encoding: AudioEncoding = proto.Field( + proto.ENUM, + number=1, + enum=AudioEncoding, + ) + sample_rate_hertz: int = proto.Field( + proto.INT32, + number=2, + ) + audio_channel_count: int = proto.Field( + proto.INT32, + number=7, + ) + enable_separate_recognition_per_channel: bool = proto.Field( + proto.BOOL, + number=12, + ) + language_code: str = proto.Field( + proto.STRING, + number=3, + ) + alternative_language_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=18, + ) + max_alternatives: int = proto.Field( + proto.INT32, + number=4, + ) + profanity_filter: bool = proto.Field( + proto.BOOL, + number=5, + ) + adaptation: resource.SpeechAdaptation = proto.Field( + proto.MESSAGE, + number=20, + message=resource.SpeechAdaptation, + ) + transcript_normalization: resource.TranscriptNormalization = proto.Field( + proto.MESSAGE, + number=24, + message=resource.TranscriptNormalization, + ) + speech_contexts: MutableSequence["SpeechContext"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="SpeechContext", + ) + enable_word_time_offsets: bool = proto.Field( + proto.BOOL, + number=8, + ) + enable_word_confidence: bool = proto.Field( + proto.BOOL, + number=15, + ) + enable_automatic_punctuation: bool = proto.Field( + proto.BOOL, + number=11, + ) + enable_spoken_punctuation: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=22, + message=wrappers_pb2.BoolValue, + ) + enable_spoken_emojis: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=23, + message=wrappers_pb2.BoolValue, + ) + enable_speaker_diarization: bool = proto.Field( + proto.BOOL, + number=16, + ) + diarization_speaker_count: int = proto.Field( + proto.INT32, + number=17, + ) + diarization_config: "SpeakerDiarizationConfig" = proto.Field( + proto.MESSAGE, + number=19, + message="SpeakerDiarizationConfig", + ) + metadata: "RecognitionMetadata" = proto.Field( + proto.MESSAGE, + number=9, + message="RecognitionMetadata", + ) + model: str = proto.Field( + proto.STRING, + number=13, + ) + use_enhanced: bool = proto.Field( + proto.BOOL, + number=14, + ) + + +class SpeakerDiarizationConfig(proto.Message): + r"""Config to enable speaker diarization. + + Attributes: + enable_speaker_diarization (bool): + If 'true', enables speaker detection for each recognized + word in the top alternative of the recognition result using + a speaker_label provided in the WordInfo. + min_speaker_count (int): + Minimum number of speakers in the + conversation. This range gives you more + flexibility by allowing the system to + automatically determine the correct number of + speakers. If not set, the default value is 2. + max_speaker_count (int): + Maximum number of speakers in the + conversation. This range gives you more + flexibility by allowing the system to + automatically determine the correct number of + speakers. If not set, the default value is 6. + speaker_tag (int): + Output only. Unused. + """ + + enable_speaker_diarization: bool = proto.Field( + proto.BOOL, + number=1, + ) + min_speaker_count: int = proto.Field( + proto.INT32, + number=2, + ) + max_speaker_count: int = proto.Field( + proto.INT32, + number=3, + ) + speaker_tag: int = proto.Field( + proto.INT32, + number=5, + ) + + +class RecognitionMetadata(proto.Message): + r"""Description of audio data to be recognized. + + Attributes: + interaction_type (google.cloud.speech_v1p1beta1.types.RecognitionMetadata.InteractionType): + The use case most closely describing the + audio content to be recognized. + industry_naics_code_of_audio (int): + The industry vertical to which this speech + recognition request most closely applies. This + is most indicative of the topics contained in + the audio. Use the 6-digit NAICS code to + identify the industry vertical - see + https://www.naics.com/search/. + microphone_distance (google.cloud.speech_v1p1beta1.types.RecognitionMetadata.MicrophoneDistance): + The audio type that most closely describes + the audio being recognized. + original_media_type (google.cloud.speech_v1p1beta1.types.RecognitionMetadata.OriginalMediaType): + The original media the speech was recorded + on. + recording_device_type (google.cloud.speech_v1p1beta1.types.RecognitionMetadata.RecordingDeviceType): + The type of device the speech was recorded + with. + recording_device_name (str): + The device used to make the recording. + Examples 'Nexus 5X' or 'Polycom SoundStation IP + 6000' or 'POTS' or 'VoIP' or 'Cardioid + Microphone'. + original_mime_type (str): + Mime type of the original audio file. For example + ``audio/m4a``, ``audio/x-alaw-basic``, ``audio/mp3``, + ``audio/3gpp``. A list of possible audio mime types is + maintained at + http://www.iana.org/assignments/media-types/media-types.xhtml#audio + obfuscated_id (int): + Obfuscated (privacy-protected) ID of the + user, to identify number of unique users using + the service. + audio_topic (str): + Description of the content. Eg. "Recordings + of federal supreme court hearings from 2012". + """ + + class InteractionType(proto.Enum): + r"""Use case categories that the audio recognition request can be + described by. + + Values: + INTERACTION_TYPE_UNSPECIFIED (0): + Use case is either unknown or is something + other than one of the other values below. + DISCUSSION (1): + Multiple people in a conversation or discussion. For example + in a meeting with two or more people actively participating. + Typically all the primary people speaking would be in the + same room (if not, see PHONE_CALL) + PRESENTATION (2): + One or more persons lecturing or presenting + to others, mostly uninterrupted. + PHONE_CALL (3): + A phone-call or video-conference in which two + or more people, who are not in the same room, + are actively participating. + VOICEMAIL (4): + A recorded message intended for another + person to listen to. + PROFESSIONALLY_PRODUCED (5): + Professionally produced audio (eg. TV Show, + Podcast). + VOICE_SEARCH (6): + Transcribe spoken questions and queries into + text. + VOICE_COMMAND (7): + Transcribe voice commands, such as for + controlling a device. + DICTATION (8): + Transcribe speech to text to create a written + document, such as a text-message, email or + report. + """ + + INTERACTION_TYPE_UNSPECIFIED = 0 + DISCUSSION = 1 + PRESENTATION = 2 + PHONE_CALL = 3 + VOICEMAIL = 4 + PROFESSIONALLY_PRODUCED = 5 + VOICE_SEARCH = 6 + VOICE_COMMAND = 7 + DICTATION = 8 + + class MicrophoneDistance(proto.Enum): + r"""Enumerates the types of capture settings describing an audio + file. + + Values: + MICROPHONE_DISTANCE_UNSPECIFIED (0): + Audio type is not known. + NEARFIELD (1): + The audio was captured from a closely placed + microphone. Eg. phone, dictaphone, or handheld + microphone. Generally if there speaker is within + 1 meter of the microphone. + MIDFIELD (2): + The speaker if within 3 meters of the + microphone. + FARFIELD (3): + The speaker is more than 3 meters away from + the microphone. + """ + + MICROPHONE_DISTANCE_UNSPECIFIED = 0 + NEARFIELD = 1 + MIDFIELD = 2 + FARFIELD = 3 + + class OriginalMediaType(proto.Enum): + r"""The original media the speech was recorded on. + + Values: + ORIGINAL_MEDIA_TYPE_UNSPECIFIED (0): + Unknown original media type. + AUDIO (1): + The speech data is an audio recording. + VIDEO (2): + The speech data originally recorded on a + video. + """ + + ORIGINAL_MEDIA_TYPE_UNSPECIFIED = 0 + AUDIO = 1 + VIDEO = 2 + + class RecordingDeviceType(proto.Enum): + r"""The type of device the speech was recorded with. + + Values: + RECORDING_DEVICE_TYPE_UNSPECIFIED (0): + The recording device is unknown. + SMARTPHONE (1): + Speech was recorded on a smartphone. + PC (2): + Speech was recorded using a personal computer + or tablet. + PHONE_LINE (3): + Speech was recorded over a phone line. + VEHICLE (4): + Speech was recorded in a vehicle. + OTHER_OUTDOOR_DEVICE (5): + Speech was recorded outdoors. + OTHER_INDOOR_DEVICE (6): + Speech was recorded indoors. + """ + + RECORDING_DEVICE_TYPE_UNSPECIFIED = 0 + SMARTPHONE = 1 + PC = 2 + PHONE_LINE = 3 + VEHICLE = 4 + OTHER_OUTDOOR_DEVICE = 5 + OTHER_INDOOR_DEVICE = 6 + + interaction_type: InteractionType = proto.Field( + proto.ENUM, + number=1, + enum=InteractionType, + ) + industry_naics_code_of_audio: int = proto.Field( + proto.UINT32, + number=3, + ) + microphone_distance: MicrophoneDistance = proto.Field( + proto.ENUM, + number=4, + enum=MicrophoneDistance, + ) + original_media_type: OriginalMediaType = proto.Field( + proto.ENUM, + number=5, + enum=OriginalMediaType, + ) + recording_device_type: RecordingDeviceType = proto.Field( + proto.ENUM, + number=6, + enum=RecordingDeviceType, + ) + recording_device_name: str = proto.Field( + proto.STRING, + number=7, + ) + original_mime_type: str = proto.Field( + proto.STRING, + number=8, + ) + obfuscated_id: int = proto.Field( + proto.INT64, + number=9, + ) + audio_topic: str = proto.Field( + proto.STRING, + number=10, + ) + + +class SpeechContext(proto.Message): + r"""Provides "hints" to the speech recognizer to favor specific + words and phrases in the results. + + Attributes: + phrases (MutableSequence[str]): + A list of strings containing words and phrases "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 `__. + + List items can also be set to classes for groups of words + that represent common concepts that occur in natural + language. For example, rather than providing phrase hints + for every month of the year, using the $MONTH class improves + the likelihood of correctly transcribing audio that includes + months. + 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 and 20. We + recommend using a binary search approach to finding the + optimal value for your use case. + """ + + phrases: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=4, + ) + + +class RecognitionAudio(proto.Message): + r"""Contains audio data in the encoding specified in the + ``RecognitionConfig``. Either ``content`` or ``uri`` must be + supplied. Supplying both or neither returns + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + See `content + limits `__. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + content (bytes): + The audio data bytes encoded as specified in + ``RecognitionConfig``. Note: as with all bytes fields, proto + buffers use a pure binary representation, whereas JSON + representations use base64. + + This field is a member of `oneof`_ ``audio_source``. + uri (str): + URI that points to a file that contains audio data bytes as + specified in ``RecognitionConfig``. The file must not be + compressed (for example, gzip). Currently, only Google Cloud + Storage URIs are supported, which must be specified in the + following format: ``gs://bucket_name/object_name`` (other + URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + + This field is a member of `oneof`_ ``audio_source``. + """ + + content: bytes = proto.Field( + proto.BYTES, + number=1, + oneof="audio_source", + ) + uri: str = proto.Field( + proto.STRING, + number=2, + oneof="audio_source", + ) + + +class RecognizeResponse(proto.Message): + r"""The only message returned to the client by the ``Recognize`` method. + It contains the result as zero or more sequential + ``SpeechRecognitionResult`` messages. + + Attributes: + results (MutableSequence[google.cloud.speech_v1p1beta1.types.SpeechRecognitionResult]): + Sequential list of transcription results + corresponding to sequential portions of audio. + total_billed_time (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + corresponding request. + speech_adaptation_info (google.cloud.speech_v1p1beta1.types.SpeechAdaptationInfo): + Provides information on adaptation behavior + in response + request_id (int): + The ID associated with the request. This is a + unique ID specific only to the given request. + using_legacy_models (bool): + Whether request used legacy asr models (was + not automatically migrated to use conformer + models). + """ + + results: MutableSequence["SpeechRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SpeechRecognitionResult", + ) + total_billed_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + speech_adaptation_info: "SpeechAdaptationInfo" = proto.Field( + proto.MESSAGE, + number=7, + message="SpeechAdaptationInfo", + ) + request_id: int = proto.Field( + proto.INT64, + number=8, + ) + using_legacy_models: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +class LongRunningRecognizeResponse(proto.Message): + r"""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. + + Attributes: + results (MutableSequence[google.cloud.speech_v1p1beta1.types.SpeechRecognitionResult]): + Sequential list of transcription results + corresponding to sequential portions of audio. + total_billed_time (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + corresponding request. + output_config (google.cloud.speech_v1p1beta1.types.TranscriptOutputConfig): + Original output config if present in the + request. + output_error (google.rpc.status_pb2.Status): + If the transcript output fails this field + contains the relevant error. + speech_adaptation_info (google.cloud.speech_v1p1beta1.types.SpeechAdaptationInfo): + Provides information on speech adaptation + behavior in response + request_id (int): + The ID associated with the request. This is a + unique ID specific only to the given request. + """ + + results: MutableSequence["SpeechRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SpeechRecognitionResult", + ) + total_billed_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + output_config: "TranscriptOutputConfig" = proto.Field( + proto.MESSAGE, + number=6, + message="TranscriptOutputConfig", + ) + output_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=7, + message=status_pb2.Status, + ) + speech_adaptation_info: "SpeechAdaptationInfo" = proto.Field( + proto.MESSAGE, + number=8, + message="SpeechAdaptationInfo", + ) + request_id: int = proto.Field( + proto.INT64, + number=9, + ) + + +class LongRunningRecognizeMetadata(proto.Message): + r"""Describes the progress of a long-running ``LongRunningRecognize`` + call. It is included in the ``metadata`` field of the ``Operation`` + returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + progress_percent (int): + Approximate percentage of audio processed + thus far. Guaranteed to be 100 when the audio is + fully processed and the results are available. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent processing update. + uri (str): + Output only. The URI of the audio file being + transcribed. Empty if the audio was sent as byte + content. + output_config (google.cloud.speech_v1p1beta1.types.TranscriptOutputConfig): + Output only. A copy of the + TranscriptOutputConfig if it was set in the + request. + """ + + progress_percent: int = proto.Field( + proto.INT32, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + uri: str = proto.Field( + proto.STRING, + number=4, + ) + output_config: "TranscriptOutputConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="TranscriptOutputConfig", + ) + + +class StreamingRecognizeResponse(proto.Message): + r"""``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 ``StreamingRecognizeResponse``\ s + 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``. + + Attributes: + error (google.rpc.status_pb2.Status): + If set, returns a [google.rpc.Status][google.rpc.Status] + message that specifies the error for the operation. + results (MutableSequence[google.cloud.speech_v1p1beta1.types.StreamingRecognitionResult]): + This repeated list contains zero or more results that + correspond to consecutive portions of the audio currently + being processed. It contains zero or one ``is_final=true`` + result (the newly settled portion), followed by zero or more + ``is_final=false`` results (the interim results). + speech_event_type (google.cloud.speech_v1p1beta1.types.StreamingRecognizeResponse.SpeechEventType): + Indicates the type of speech event. + speech_event_time (google.protobuf.duration_pb2.Duration): + Time offset between the beginning of the + audio and event emission. + total_billed_time (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + stream. Set only if this is the last response in + the stream. + speech_adaptation_info (google.cloud.speech_v1p1beta1.types.SpeechAdaptationInfo): + Provides information on adaptation behavior + in response + request_id (int): + The ID associated with the request. This is a + unique ID specific only to the given request. + """ + + class SpeechEventType(proto.Enum): + r"""Indicates the type of speech event. + + Values: + SPEECH_EVENT_UNSPECIFIED (0): + No speech event specified. + END_OF_SINGLE_UTTERANCE (1): + This event indicates that the server has detected the end of + the user's speech utterance and expects no additional + speech. Therefore, the server will not process additional + audio (although it may subsequently return additional + results). The client should stop sending additional audio + data, half-close the gRPC connection, and wait for any + additional results until the server closes the gRPC + connection. This event is only sent if ``single_utterance`` + was set to ``true``, and is not used otherwise. + SPEECH_ACTIVITY_BEGIN (2): + This event indicates that the server has detected the + beginning of human voice activity in the stream. This event + can be returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_END (3): + This event indicates that the server has detected the end of + human voice activity in the stream. This event can be + returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_TIMEOUT (4): + This event indicates that the user-set + timeout for speech activity begin or end has + exceeded. Upon receiving this event, the client + is expected to send a half close. Further audio + will not be processed. + """ + + SPEECH_EVENT_UNSPECIFIED = 0 + END_OF_SINGLE_UTTERANCE = 1 + SPEECH_ACTIVITY_BEGIN = 2 + SPEECH_ACTIVITY_END = 3 + SPEECH_ACTIVITY_TIMEOUT = 4 + + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + results: MutableSequence["StreamingRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="StreamingRecognitionResult", + ) + speech_event_type: SpeechEventType = proto.Field( + proto.ENUM, + number=4, + enum=SpeechEventType, + ) + speech_event_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + total_billed_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + speech_adaptation_info: "SpeechAdaptationInfo" = proto.Field( + proto.MESSAGE, + number=9, + message="SpeechAdaptationInfo", + ) + request_id: int = proto.Field( + proto.INT64, + number=10, + ) + + +class StreamingRecognitionResult(proto.Message): + r"""A streaming speech recognition result corresponding to a + portion of the audio that is currently being processed. + + Attributes: + alternatives (MutableSequence[google.cloud.speech_v1p1beta1.types.SpeechRecognitionAlternative]): + May contain one or more recognition hypotheses (up to the + maximum specified in ``max_alternatives``). These + alternatives are ordered in terms of accuracy, with the top + (first) alternative being the most probable, as ranked by + the recognizer. + is_final (bool): + If ``false``, this ``StreamingRecognitionResult`` represents + an interim result that may change. If ``true``, this is the + final time the speech service will return this particular + ``StreamingRecognitionResult``, the recognizer will not + return any further hypotheses for this portion of the + transcript and corresponding audio. + stability (float): + An estimate of the likelihood that the recognizer will not + change its guess about this interim result. Values range + from 0.0 (completely unstable) to 1.0 (completely stable). + This field is only provided for interim results + (``is_final=false``). The default of 0.0 is a sentinel value + indicating ``stability`` was not set. + result_end_time (google.protobuf.duration_pb2.Duration): + Time offset of the end of this result + relative to the beginning of the audio. + channel_tag (int): + For multi-channel audio, this is the channel number + corresponding to the recognized result for the audio from + that channel. For audio_channel_count = N, its output values + can range from '1' to 'N'. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives: MutableSequence["SpeechRecognitionAlternative"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SpeechRecognitionAlternative", + ) + is_final: bool = proto.Field( + proto.BOOL, + number=2, + ) + stability: float = proto.Field( + proto.FLOAT, + number=3, + ) + result_end_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + channel_tag: int = proto.Field( + proto.INT32, + number=5, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + + +class SpeechRecognitionResult(proto.Message): + r"""A speech recognition result corresponding to a portion of the + audio. + + Attributes: + alternatives (MutableSequence[google.cloud.speech_v1p1beta1.types.SpeechRecognitionAlternative]): + May contain one or more recognition hypotheses (up to the + maximum specified in ``max_alternatives``). These + alternatives are ordered in terms of accuracy, with the top + (first) alternative being the most probable, as ranked by + the recognizer. + channel_tag (int): + For multi-channel audio, this is the channel number + corresponding to the recognized result for the audio from + that channel. For audio_channel_count = N, its output values + can range from '1' to 'N'. + result_end_time (google.protobuf.duration_pb2.Duration): + Time offset of the end of this result + relative to the beginning of the audio. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives: MutableSequence["SpeechRecognitionAlternative"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SpeechRecognitionAlternative", + ) + channel_tag: int = proto.Field( + proto.INT32, + number=2, + ) + result_end_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + language_code: str = proto.Field( + proto.STRING, + number=5, + ) + + +class SpeechRecognitionAlternative(proto.Message): + r"""Alternative hypotheses (a.k.a. n-best list). + + Attributes: + transcript (str): + Transcript text representing the words that + the user spoke. In languages that use spaces to + separate words, the transcript might have a + leading space if it isn't the first result. You + can concatenate each result to obtain the full + transcript without using a separator. + confidence (float): + The confidence estimate between 0.0 and 1.0. A higher number + indicates an estimated greater likelihood that the + recognized words are correct. This field is set only for the + top alternative of a non-streaming result or, of a streaming + result where ``is_final=true``. This field is not guaranteed + to be accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + words (MutableSequence[google.cloud.speech_v1p1beta1.types.WordInfo]): + A list of word-specific information for each recognized + word. Note: When ``enable_speaker_diarization`` is true, you + will see all the words from the beginning of the audio. + """ + + transcript: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + words: MutableSequence["WordInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="WordInfo", + ) + + +class WordInfo(proto.Message): + r"""Word-specific information for recognized words. + + Attributes: + start_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the start of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + end_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the end of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + word (str): + The word corresponding to this set of + information. + confidence (float): + The confidence estimate between 0.0 and 1.0. A higher number + indicates an estimated greater likelihood that the + recognized words are correct. This field is set only for the + top alternative of a non-streaming result or, of a streaming + result where ``is_final=true``. This field is not guaranteed + to be accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + speaker_tag (int): + Output only. A distinct integer value is assigned for every + speaker within the audio. This field specifies which one of + those speakers was detected to have spoken this word. Value + ranges from '1' to diarization_speaker_count. speaker_tag is + set if enable_speaker_diarization = 'true' and only for the + top alternative. Note: Use speaker_label instead. + speaker_label (str): + Output only. A label value assigned for every unique speaker + within the audio. This field specifies which speaker was + detected to have spoken this word. For some models, like + medical_conversation this can be actual speaker role, for + example "patient" or "provider", but generally this would be + a number identifying a speaker. This field is only set if + enable_speaker_diarization = 'true' and only for the top + alternative. + """ + + start_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + word: str = proto.Field( + proto.STRING, + number=3, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=4, + ) + speaker_tag: int = proto.Field( + proto.INT32, + number=5, + ) + speaker_label: str = proto.Field( + proto.STRING, + number=6, + ) + + +class SpeechAdaptationInfo(proto.Message): + r"""Information on speech adaptation use in results + + Attributes: + adaptation_timeout (bool): + Whether there was a timeout when applying + speech adaptation. If true, adaptation had no + effect in the response transcript. + timeout_message (str): + If set, returns a message specifying which + part of the speech adaptation request timed out. + """ + + adaptation_timeout: bool = proto.Field( + proto.BOOL, + number=1, + ) + timeout_message: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9048d7d20c5da36d8320eac27e8933824c5e96 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py @@ -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 + +import google.protobuf.field_mask_pb2 as 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 `__ + 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 `__ + 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 `__ + 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 `__ + 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 `__ + 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 `__ + 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 `__ + 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 `__ + with matching ``us`` or ``eu`` location value. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/resource.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cceeb2f2dd442f1b463d35ce33a64ce4dd6687 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v1p1beta1/types/resource.py @@ -0,0 +1,497 @@ +# -*- 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 + +import google.protobuf.timestamp_pb2 as 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 `__ + 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 `__ + 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 `__ + 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 `__ + 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 `__. + + 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 `__ + 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)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b59f5fc75d341be8aa38c13a187f96b56e6d7814 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/__init__.py @@ -0,0 +1,277 @@ +# -*- 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 sys + +import google.api_core as api_core + +from google.cloud.speech_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.speech import SpeechAsyncClient, SpeechClient +from .types.cloud_speech import ( + AutoDetectDecodingConfig, + BatchRecognizeFileMetadata, + BatchRecognizeFileResult, + BatchRecognizeMetadata, + BatchRecognizeRequest, + BatchRecognizeResponse, + BatchRecognizeResults, + BatchRecognizeTranscriptionMetadata, + CloudStorageResult, + Config, + CreateCustomClassRequest, + CreatePhraseSetRequest, + CreateRecognizerRequest, + CustomClass, + CustomPromptConfig, + DeleteCustomClassRequest, + DeletePhraseSetRequest, + DeleteRecognizerRequest, + DenoiserConfig, + ExplicitDecodingConfig, + GcsOutputConfig, + GetConfigRequest, + GetCustomClassRequest, + GetPhraseSetRequest, + GetRecognizerRequest, + InlineOutputConfig, + InlineResult, + ListCustomClassesRequest, + ListCustomClassesResponse, + ListPhraseSetsRequest, + ListPhraseSetsResponse, + ListRecognizersRequest, + ListRecognizersResponse, + NativeOutputFileFormatConfig, + OperationMetadata, + OutputFormatConfig, + PhraseSet, + RecognitionConfig, + RecognitionFeatures, + RecognitionOutputConfig, + RecognitionResponseMetadata, + Recognizer, + RecognizeRequest, + RecognizeResponse, + SpeakerDiarizationConfig, + SpeechAdaptation, + SpeechRecognitionAlternative, + SpeechRecognitionResult, + SrtOutputFileFormatConfig, + StreamingRecognitionConfig, + StreamingRecognitionFeatures, + StreamingRecognitionResult, + StreamingRecognizeRequest, + StreamingRecognizeResponse, + TranscriptNormalization, + TranslationConfig, + UndeleteCustomClassRequest, + UndeletePhraseSetRequest, + UndeleteRecognizerRequest, + UpdateConfigRequest, + UpdateCustomClassRequest, + UpdatePhraseSetRequest, + UpdateRecognizerRequest, + VttOutputFileFormatConfig, + WordInfo, +) +from .types.locations_metadata import ( + AccessMetadata, + LanguageMetadata, + LocationsMetadata, + ModelFeature, + ModelFeatures, + ModelMetadata, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.speech_v2") # type: ignore + api_core.check_dependency_versions("google.cloud.speech_v2") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.speech_v2" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "SpeechAsyncClient", + "AccessMetadata", + "AutoDetectDecodingConfig", + "BatchRecognizeFileMetadata", + "BatchRecognizeFileResult", + "BatchRecognizeMetadata", + "BatchRecognizeRequest", + "BatchRecognizeResponse", + "BatchRecognizeResults", + "BatchRecognizeTranscriptionMetadata", + "CloudStorageResult", + "Config", + "CreateCustomClassRequest", + "CreatePhraseSetRequest", + "CreateRecognizerRequest", + "CustomClass", + "CustomPromptConfig", + "DeleteCustomClassRequest", + "DeletePhraseSetRequest", + "DeleteRecognizerRequest", + "DenoiserConfig", + "ExplicitDecodingConfig", + "GcsOutputConfig", + "GetConfigRequest", + "GetCustomClassRequest", + "GetPhraseSetRequest", + "GetRecognizerRequest", + "InlineOutputConfig", + "InlineResult", + "LanguageMetadata", + "ListCustomClassesRequest", + "ListCustomClassesResponse", + "ListPhraseSetsRequest", + "ListPhraseSetsResponse", + "ListRecognizersRequest", + "ListRecognizersResponse", + "LocationsMetadata", + "ModelFeature", + "ModelFeatures", + "ModelMetadata", + "NativeOutputFileFormatConfig", + "OperationMetadata", + "OutputFormatConfig", + "PhraseSet", + "RecognitionConfig", + "RecognitionFeatures", + "RecognitionOutputConfig", + "RecognitionResponseMetadata", + "RecognizeRequest", + "RecognizeResponse", + "Recognizer", + "SpeakerDiarizationConfig", + "SpeechAdaptation", + "SpeechClient", + "SpeechRecognitionAlternative", + "SpeechRecognitionResult", + "SrtOutputFileFormatConfig", + "StreamingRecognitionConfig", + "StreamingRecognitionFeatures", + "StreamingRecognitionResult", + "StreamingRecognizeRequest", + "StreamingRecognizeResponse", + "TranscriptNormalization", + "TranslationConfig", + "UndeleteCustomClassRequest", + "UndeletePhraseSetRequest", + "UndeleteRecognizerRequest", + "UpdateConfigRequest", + "UpdateCustomClassRequest", + "UpdatePhraseSetRequest", + "UpdateRecognizerRequest", + "VttOutputFileFormatConfig", + "WordInfo", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..d835882c4eab133916b7d3552a7782b702e7172d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/gapic_metadata.json @@ -0,0 +1,373 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.speech_v2", + "protoPackage": "google.cloud.speech.v2", + "schema": "1.0", + "services": { + "Speech": { + "clients": { + "grpc": { + "libraryClient": "SpeechClient", + "rpcs": { + "BatchRecognize": { + "methods": [ + "batch_recognize" + ] + }, + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "CreateRecognizer": { + "methods": [ + "create_recognizer" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "DeleteRecognizer": { + "methods": [ + "delete_recognizer" + ] + }, + "GetConfig": { + "methods": [ + "get_config" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "GetRecognizer": { + "methods": [ + "get_recognizer" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSets": { + "methods": [ + "list_phrase_sets" + ] + }, + "ListRecognizers": { + "methods": [ + "list_recognizers" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + }, + "UndeleteCustomClass": { + "methods": [ + "undelete_custom_class" + ] + }, + "UndeletePhraseSet": { + "methods": [ + "undelete_phrase_set" + ] + }, + "UndeleteRecognizer": { + "methods": [ + "undelete_recognizer" + ] + }, + "UpdateConfig": { + "methods": [ + "update_config" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + }, + "UpdateRecognizer": { + "methods": [ + "update_recognizer" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SpeechAsyncClient", + "rpcs": { + "BatchRecognize": { + "methods": [ + "batch_recognize" + ] + }, + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "CreateRecognizer": { + "methods": [ + "create_recognizer" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "DeleteRecognizer": { + "methods": [ + "delete_recognizer" + ] + }, + "GetConfig": { + "methods": [ + "get_config" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "GetRecognizer": { + "methods": [ + "get_recognizer" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSets": { + "methods": [ + "list_phrase_sets" + ] + }, + "ListRecognizers": { + "methods": [ + "list_recognizers" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + }, + "UndeleteCustomClass": { + "methods": [ + "undelete_custom_class" + ] + }, + "UndeletePhraseSet": { + "methods": [ + "undelete_phrase_set" + ] + }, + "UndeleteRecognizer": { + "methods": [ + "undelete_recognizer" + ] + }, + "UpdateConfig": { + "methods": [ + "update_config" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + }, + "UpdateRecognizer": { + "methods": [ + "update_recognizer" + ] + } + } + }, + "rest": { + "libraryClient": "SpeechClient", + "rpcs": { + "BatchRecognize": { + "methods": [ + "batch_recognize" + ] + }, + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "CreateRecognizer": { + "methods": [ + "create_recognizer" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "DeleteRecognizer": { + "methods": [ + "delete_recognizer" + ] + }, + "GetConfig": { + "methods": [ + "get_config" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "GetRecognizer": { + "methods": [ + "get_recognizer" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSets": { + "methods": [ + "list_phrase_sets" + ] + }, + "ListRecognizers": { + "methods": [ + "list_recognizers" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + }, + "UndeleteCustomClass": { + "methods": [ + "undelete_custom_class" + ] + }, + "UndeletePhraseSet": { + "methods": [ + "undelete_phrase_set" + ] + }, + "UndeleteRecognizer": { + "methods": [ + "undelete_recognizer" + ] + }, + "UpdateConfig": { + "methods": [ + "update_config" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + }, + "UpdateRecognizer": { + "methods": [ + "update_recognizer" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..d372d0b1db6f01f24c3657099b75881bf85c15d3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/gapic_version.py @@ -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.38.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..02081c09b9abb4d2d2a2c037d675d04eee51df20 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-speech package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/__init__.py @@ -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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46fd4742bf9bf09f5d77f5b776940109094160b2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..7544b64854bcd56caa77c9253908ef86274209e7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/async_client.py @@ -0,0 +1,3856 @@ +# -*- 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +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_v2 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 + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.speech_v2.services.speech import pagers +from google.cloud.speech_v2.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: + """Enables speech transcription and resource management.""" + + _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 + + config_path = staticmethod(SpeechClient.config_path) + parse_config_path = staticmethod(SpeechClient.parse_config_path) + 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) + recognizer_path = staticmethod(SpeechClient.recognizer_path) + parse_recognizer_path = staticmethod(SpeechClient.parse_recognizer_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. + """ + sa_info_func = ( + SpeechClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SpeechAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SpeechAsyncClient: The constructed client. + """ + sa_file_func = ( + SpeechClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(SpeechAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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) -> str: + """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_v2.SpeechAsyncClient`.", + extra={ + "serviceName": "google.cloud.speech.v2.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.v2.Speech", + "credentialsType": None, + }, + ) + + async def create_recognizer( + self, + request: Optional[Union[cloud_speech.CreateRecognizerRequest, dict]] = None, + *, + parent: Optional[str] = None, + recognizer: Optional[cloud_speech.Recognizer] = None, + recognizer_id: Optional[str] = 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"""Creates a [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + async def sample_create_recognizer(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.CreateRecognizerRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.CreateRecognizerRequest, dict]]): + The request object. Request message for the + [CreateRecognizer][google.cloud.speech.v2.Speech.CreateRecognizer] + method. + parent (:class:`str`): + Required. The project and location where this Recognizer + will be created. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + recognizer (:class:`google.cloud.speech_v2.types.Recognizer`): + Required. The Recognizer to create. + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + recognizer_id (:class:`str`): + The ID to use for the Recognizer, which will become the + final component of the Recognizer's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``recognizer_id`` 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_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [parent, recognizer, recognizer_id] + 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.CreateRecognizerRequest): + request = cloud_speech.CreateRecognizerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if recognizer is not None: + request.recognizer = recognizer + if recognizer_id is not None: + request.recognizer_id = recognizer_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_recognizer + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # 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.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_recognizers( + self, + request: Optional[Union[cloud_speech.ListRecognizersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRecognizersAsyncPager: + r"""Lists Recognizers. + + .. 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_v2 + + async def sample_list_recognizers(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.ListRecognizersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_recognizers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.ListRecognizersRequest, dict]]): + The request object. Request message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + parent (:class:`str`): + Required. The project and location of Recognizers to + list. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` 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_v2.services.speech.pagers.ListRecognizersAsyncPager: + Response message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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.ListRecognizersRequest): + request = cloud_speech.ListRecognizersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_recognizers + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRecognizersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_recognizer( + self, + request: Optional[Union[cloud_speech.GetRecognizerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Recognizer: + r"""Returns the requested + [Recognizer][google.cloud.speech.v2.Recognizer]. Fails with + [NOT_FOUND][google.rpc.Code.NOT_FOUND] if the requested + Recognizer doesn't exist. + + .. 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_v2 + + async def sample_get_recognizer(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.GetRecognizerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_recognizer(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.GetRecognizerRequest, dict]]): + The request object. Request message for the + [GetRecognizer][google.cloud.speech.v2.Speech.GetRecognizer] + method. + name (:class:`str`): + Required. The name of the Recognizer to retrieve. The + expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + + This corresponds to the ``name`` 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_v2.types.Recognizer: + A Recognizer message. Stores + recognition configuration and metadata. + + """ + # 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 = [name] + 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.GetRecognizerRequest): + request = cloud_speech.GetRecognizerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_recognizer + ] + + # 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 update_recognizer( + self, + request: Optional[Union[cloud_speech.UpdateRecognizerRequest, dict]] = None, + *, + recognizer: Optional[cloud_speech.Recognizer] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + async def sample_update_recognizer(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.UpdateRecognizerRequest( + ) + + # Make the request + operation = client.update_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.UpdateRecognizerRequest, dict]]): + The request object. Request message for the + [UpdateRecognizer][google.cloud.speech.v2.Speech.UpdateRecognizer] + method. + recognizer (:class:`google.cloud.speech_v2.types.Recognizer`): + Required. The Recognizer to update. + + The Recognizer's ``name`` field is used to identify the + Recognizer to update. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to update. If empty, all non-default + valued fields are considered for update. Use ``*`` to + update the entire Recognizer resource. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [recognizer, update_mask] + 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.UpdateRecognizerRequest): + request = cloud_speech.UpdateRecognizerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if recognizer is not None: + request.recognizer = recognizer + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_recognizer + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("recognizer.name", request.recognizer.name),) + ), + ) + + # 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.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_recognizer( + self, + request: Optional[Union[cloud_speech.DeleteRecognizerRequest, dict]] = None, + *, + name: Optional[str] = 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"""Deletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + async def sample_delete_recognizer(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.DeleteRecognizerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.DeleteRecognizerRequest, dict]]): + The request object. Request message for the + [DeleteRecognizer][google.cloud.speech.v2.Speech.DeleteRecognizer] + method. + name (:class:`str`): + Required. The name of the Recognizer to delete. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}`` + + This corresponds to the ``name`` 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_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [name] + 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.DeleteRecognizerRequest): + request = cloud_speech.DeleteRecognizerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_recognizer + ] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloud_speech.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def undelete_recognizer( + self, + request: Optional[Union[cloud_speech.UndeleteRecognizerRequest, dict]] = None, + *, + name: Optional[str] = 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"""Undeletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + async def sample_undelete_recognizer(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.UndeleteRecognizerRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.UndeleteRecognizerRequest, dict]]): + The request object. Request message for the + [UndeleteRecognizer][google.cloud.speech.v2.Speech.UndeleteRecognizer] + method. + name (:class:`str`): + Required. The name of the Recognizer to undelete. + Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}`` + + This corresponds to the ``name`` 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_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [name] + 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.UndeleteRecognizerRequest): + request = cloud_speech.UndeleteRecognizerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_recognizer + ] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloud_speech.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def recognize( + self, + request: Optional[Union[cloud_speech.RecognizeRequest, dict]] = None, + *, + recognizer: Optional[str] = None, + config: Optional[cloud_speech.RecognitionConfig] = None, + config_mask: Optional[field_mask_pb2.FieldMask] = None, + content: Optional[bytes] = None, + uri: Optional[str] = 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_v2 + + async def sample_recognize(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.RecognizeRequest( + content=b'content_blob', + recognizer="recognizer_value", + ) + + # Make the request + response = await client.recognize(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.RecognizeRequest, dict]]): + The request object. Request message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. Either ``content`` or ``uri`` must be supplied. + Supplying both or neither returns + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + See `content + limits `__. + recognizer (:class:`str`): + Required. The name of the Recognizer to use during + recognition. The expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + The {recognizer} segment may be set to ``_`` to use an + empty implicit Recognizer. + + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config (:class:`google.cloud.speech_v2.types.RecognitionConfig`): + Features and audio metadata to use for the Automatic + Speech Recognition. This field in combination with the + [config_mask][google.cloud.speech.v2.RecognizeRequest.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource. + + This corresponds to the ``config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields in + [config][google.cloud.speech.v2.RecognizeRequest.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all non-default valued fields in + [config][google.cloud.speech.v2.RecognizeRequest.config] + override the values in the recognizer for this + recognition request. If a mask is provided, only the + fields listed in the mask override the config in the + recognizer for this recognition request. If a wildcard + (``*``) is provided, + [config][google.cloud.speech.v2.RecognizeRequest.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + + This corresponds to the ``config_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content (:class:`bytes`): + The audio data bytes encoded as specified in + [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. + As with all bytes fields, proto buffers use a pure + binary representation, whereas JSON representations use + base64. + + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + uri (:class:`str`): + URI that points to a file that contains audio data bytes + as specified in + [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. + The file must not be compressed (for example, gzip). + Currently, only Google Cloud Storage URIs are supported, + which must be specified in the following format: + ``gs://bucket_name/object_name`` (other URI formats + return + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + + This corresponds to the ``uri`` 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_v2.types.RecognizeResponse: + Response message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. + + """ + # 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 = [recognizer, config, config_mask, content, uri] + 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 recognizer is not None: + request.recognizer = recognizer + if config is not None: + request.config = config + if config_mask is not None: + request.config_mask = config_mask + if content is not None: + request.content = content + if uri is not None: + request.uri = uri + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.recognize + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("recognizer", request.recognizer),) + ), + ) + + # 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 + + 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_v2 + + async def sample_streaming_recognize(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.StreamingRecognizeRequest( + recognizer="recognizer_value", + ) + + # This method expects an iterator which contains + # 'speech_v2.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_v2.types.StreamingRecognizeRequest`]): + The request object AsyncIterator. Request message for the + [StreamingRecognize][google.cloud.speech.v2.Speech.StreamingRecognize] + method. Multiple + [StreamingRecognizeRequest][google.cloud.speech.v2.StreamingRecognizeRequest] + messages are sent in one call. + + If the [Recognizer][google.cloud.speech.v2.Recognizer] + referenced by + [recognizer][google.cloud.speech.v2.StreamingRecognizeRequest.recognizer] + contains a fully specified request configuration then + the stream may only contain messages with only + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio] + set. + + Otherwise the first message must contain a + [recognizer][google.cloud.speech.v2.StreamingRecognizeRequest.recognizer] + and a + [streaming_config][google.cloud.speech.v2.StreamingRecognizeRequest.streaming_config] + message that together fully specify the request + configuration and must not contain + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio]. + All subsequent messages must only have + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio] + 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: + AsyncIterable[google.cloud.speech_v2.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 then + no messages are streamed back to the client. + + Here are some examples of + \`StreamingRecognizeResponse`s 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 batch_recognize( + self, + request: Optional[Union[cloud_speech.BatchRecognizeRequest, dict]] = None, + *, + recognizer: Optional[str] = None, + config: Optional[cloud_speech.RecognitionConfig] = None, + config_mask: Optional[field_mask_pb2.FieldMask] = None, + files: Optional[ + MutableSequence[cloud_speech.BatchRecognizeFileMetadata] + ] = 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 batch asynchronous speech recognition: send + a request with N audio files and receive a long running + operation that can be polled to see when the + transcriptions are finished. + + .. 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_v2 + + async def sample_batch_recognize(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.BatchRecognizeRequest( + recognizer="recognizer_value", + ) + + # Make the request + operation = client.batch_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_v2.types.BatchRecognizeRequest, dict]]): + The request object. Request message for the + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + method. + recognizer (:class:`str`): + Required. The name of the Recognizer to use during + recognition. The expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + The {recognizer} segment may be set to ``_`` to use an + empty implicit Recognizer. + + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config (:class:`google.cloud.speech_v2.types.RecognitionConfig`): + Features and audio metadata to use for the Automatic + Speech Recognition. This field in combination with the + [config_mask][google.cloud.speech.v2.BatchRecognizeRequest.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource. + + This corresponds to the ``config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields in + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all given fields in + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + override the values in the recognizer for this + recognition request. If a mask is provided, only the + fields listed in the mask override the config in the + recognizer for this recognition request. If a wildcard + (``*``) is provided, + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + + This corresponds to the ``config_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + files (:class:`MutableSequence[google.cloud.speech_v2.types.BatchRecognizeFileMetadata]`): + Audio files with file metadata for + ASR. The maximum number of files allowed + to be specified is 15. + + This corresponds to the ``files`` 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_v2.types.BatchRecognizeResponse` Response message for + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + that is packaged into a longrunning + [Operation][google.longrunning.Operation]. + + """ + # 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 = [recognizer, config, config_mask, files] + 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.BatchRecognizeRequest): + request = cloud_speech.BatchRecognizeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if recognizer is not None: + request.recognizer = recognizer + if config is not None: + request.config = config + if config_mask is not None: + request.config_mask = config_mask + if files: + request.files.extend(files) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_recognize + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("recognizer", request.recognizer),) + ), + ) + + # 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.BatchRecognizeResponse, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_config( + self, + request: Optional[Union[cloud_speech.GetConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Config: + r"""Returns the requested [Config][google.cloud.speech.v2.Config]. + + .. 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_v2 + + async def sample_get_config(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.GetConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.GetConfigRequest, dict]]): + The request object. Request message for the + [GetConfig][google.cloud.speech.v2.Speech.GetConfig] + method. + name (:class:`str`): + Required. The name of the config to retrieve. There is + exactly one config resource per project per location. + The expected format is + ``projects/{project}/locations/{location}/config``. + + This corresponds to the ``name`` 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_v2.types.Config: + Message representing the config for the Speech-to-Text API. This includes an + optional [KMS + key](https://cloud.google.com/kms/docs/resource-hierarchy#keys) + with which incoming data will be encrypted. + + """ + # 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 = [name] + 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.GetConfigRequest): + request = cloud_speech.GetConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_config + ] + + # 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 update_config( + self, + request: Optional[Union[cloud_speech.UpdateConfigRequest, dict]] = None, + *, + config: Optional[cloud_speech.Config] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Config: + r"""Updates the [Config][google.cloud.speech.v2.Config]. + + .. 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_v2 + + async def sample_update_config(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.UpdateConfigRequest( + ) + + # Make the request + response = await client.update_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.UpdateConfigRequest, dict]]): + The request object. Request message for the + [UpdateConfig][google.cloud.speech.v2.Speech.UpdateConfig] + method. + config (:class:`google.cloud.speech_v2.types.Config`): + Required. The config to update. + + The config's ``name`` field is used to identify the + config to be updated. The expected format is + ``projects/{project}/locations/{location}/config``. + + This corresponds to the ``config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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_v2.types.Config: + Message representing the config for the Speech-to-Text API. This includes an + optional [KMS + key](https://cloud.google.com/kms/docs/resource-hierarchy#keys) + with which incoming data will be encrypted. + + """ + # 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, update_mask] + 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.UpdateConfigRequest): + request = cloud_speech.UpdateConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if config is not None: + request.config = config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("config.name", request.config.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 create_custom_class( + self, + request: Optional[Union[cloud_speech.CreateCustomClassRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_class: Optional[cloud_speech.CustomClass] = None, + custom_class_id: Optional[str] = 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"""Creates a [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + async def sample_create_custom_class(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.CreateCustomClassRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.CreateCustomClassRequest, dict]]): + The request object. Request message for the + [CreateCustomClass][google.cloud.speech.v2.Speech.CreateCustomClass] + method. + parent (:class:`str`): + Required. The project and location where this + CustomClass will be created. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_class (:class:`google.cloud.speech_v2.types.CustomClass`): + Required. The CustomClass to create. + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_class_id (:class:`str`): + The ID to use for the CustomClass, which will become the + final component of the CustomClass's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``custom_class_id`` 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_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [parent, custom_class, custom_class_id] + 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.CreateCustomClassRequest): + request = cloud_speech.CreateCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_class is not None: + request.custom_class = custom_class + if custom_class_id is not None: + request.custom_class_id = custom_class_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_custom_class + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # 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.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_custom_classes( + self, + request: Optional[Union[cloud_speech.ListCustomClassesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCustomClassesAsyncPager: + r"""Lists CustomClasses. + + .. 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_v2 + + async def sample_list_custom_classes(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.ListCustomClassesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_classes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.ListCustomClassesRequest, dict]]): + The request object. Request message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + parent (:class:`str`): + Required. The project and location of CustomClass + resources to list. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` 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_v2.services.speech.pagers.ListCustomClassesAsyncPager: + Response message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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.ListCustomClassesRequest): + request = cloud_speech.ListCustomClassesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_custom_classes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCustomClassesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_custom_class( + self, + request: Optional[Union[cloud_speech.GetCustomClassRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.CustomClass: + r"""Returns the requested + [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + async def sample_get_custom_class(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.GetCustomClassRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.GetCustomClassRequest, dict]]): + The request object. Request message for the + [GetCustomClass][google.cloud.speech.v2.Speech.GetCustomClass] + method. + name (:class:`str`): + Required. The name of the CustomClass to retrieve. The + expected format is + ``projects/{project}/locations/{location}/customClasses/{custom_class}``. + + This corresponds to the ``name`` 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_v2.types.CustomClass: + CustomClass for biasing in speech + recognition. Used to define a set of + words or phrases that represents a + common concept or theme likely to appear + in your audio, for example a list of + passenger ship names. + + """ + # 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 = [name] + 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.GetCustomClassRequest): + request = cloud_speech.GetCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_custom_class + ] + + # 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 update_custom_class( + self, + request: Optional[Union[cloud_speech.UpdateCustomClassRequest, dict]] = None, + *, + custom_class: Optional[cloud_speech.CustomClass] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + async def sample_update_custom_class(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.UpdateCustomClassRequest( + ) + + # Make the request + operation = client.update_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.UpdateCustomClassRequest, dict]]): + The request object. Request message for the + [UpdateCustomClass][google.cloud.speech.v2.Speech.UpdateCustomClass] + method. + custom_class (:class:`google.cloud.speech_v2.types.CustomClass`): + Required. The CustomClass to update. + + The CustomClass's ``name`` field is used to identify the + CustomClass to update. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}``. + + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If + empty, all fields are considered for + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [custom_class, update_mask] + 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.UpdateCustomClassRequest): + request = cloud_speech.UpdateCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_class is not None: + request.custom_class = custom_class + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_custom_class + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("custom_class.name", request.custom_class.name),) + ), + ) + + # 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.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_custom_class( + self, + request: Optional[Union[cloud_speech.DeleteCustomClassRequest, dict]] = None, + *, + name: Optional[str] = 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"""Deletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + async def sample_delete_custom_class(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.DeleteCustomClassRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.DeleteCustomClassRequest, dict]]): + The request object. Request message for the + [DeleteCustomClass][google.cloud.speech.v2.Speech.DeleteCustomClass] + method. + name (:class:`str`): + Required. The name of the CustomClass to delete. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + + This corresponds to the ``name`` 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_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [name] + 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.DeleteCustomClassRequest): + request = cloud_speech.DeleteCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_custom_class + ] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloud_speech.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def undelete_custom_class( + self, + request: Optional[Union[cloud_speech.UndeleteCustomClassRequest, dict]] = None, + *, + name: Optional[str] = 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"""Undeletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + async def sample_undelete_custom_class(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.UndeleteCustomClassRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.UndeleteCustomClassRequest, dict]]): + The request object. Request message for the + [UndeleteCustomClass][google.cloud.speech.v2.Speech.UndeleteCustomClass] + method. + name (:class:`str`): + Required. The name of the CustomClass to undelete. + Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + + This corresponds to the ``name`` 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_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [name] + 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.UndeleteCustomClassRequest): + request = cloud_speech.UndeleteCustomClassRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_custom_class + ] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + cloud_speech.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_phrase_set( + self, + request: Optional[Union[cloud_speech.CreatePhraseSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + phrase_set: Optional[cloud_speech.PhraseSet] = None, + phrase_set_id: Optional[str] = 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"""Creates a [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + async def sample_create_phrase_set(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.CreatePhraseSetRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.CreatePhraseSetRequest, dict]]): + The request object. Request message for the + [CreatePhraseSet][google.cloud.speech.v2.Speech.CreatePhraseSet] + method. + parent (:class:`str`): + Required. The project and location where this PhraseSet + will be created. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + phrase_set (:class:`google.cloud.speech_v2.types.PhraseSet`): + Required. The PhraseSet to create. + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + phrase_set_id (:class:`str`): + The ID to use for the PhraseSet, which will become the + final component of the PhraseSet's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``phrase_set_id`` 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_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [parent, phrase_set, phrase_set_id] + 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.CreatePhraseSetRequest): + request = cloud_speech.CreatePhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if phrase_set is not None: + request.phrase_set = phrase_set + if phrase_set_id is not None: + request.phrase_set_id = phrase_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # 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.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_phrase_sets( + self, + request: Optional[Union[cloud_speech.ListPhraseSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPhraseSetsAsyncPager: + r"""Lists PhraseSets. + + .. 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_v2 + + async def sample_list_phrase_sets(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.ListPhraseSetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_phrase_sets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.ListPhraseSetsRequest, dict]]): + The request object. Request message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + parent (:class:`str`): + Required. The project and location of PhraseSet + resources to list. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` 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_v2.services.speech.pagers.ListPhraseSetsAsyncPager: + Response message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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.ListPhraseSetsRequest): + request = cloud_speech.ListPhraseSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_phrase_sets + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPhraseSetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_phrase_set( + self, + request: Optional[Union[cloud_speech.GetPhraseSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.PhraseSet: + r"""Returns the requested + [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + async def sample_get_phrase_set(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.GetPhraseSetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.GetPhraseSetRequest, dict]]): + The request object. Request message for the + [GetPhraseSet][google.cloud.speech.v2.Speech.GetPhraseSet] + method. + name (:class:`str`): + Required. The name of the PhraseSet to retrieve. The + expected format is + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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_v2.types.PhraseSet: + PhraseSet for biasing in speech + recognition. A PhraseSet is used to + provide "hints" to the speech recognizer + to favor specific words and phrases in + the results. + + """ + # 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 = [name] + 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.GetPhraseSetRequest): + request = cloud_speech.GetPhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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 update_phrase_set( + self, + request: Optional[Union[cloud_speech.UpdatePhraseSetRequest, dict]] = None, + *, + phrase_set: Optional[cloud_speech.PhraseSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + async def sample_update_phrase_set(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.UpdatePhraseSetRequest( + ) + + # Make the request + operation = client.update_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.UpdatePhraseSetRequest, dict]]): + The request object. Request message for the + [UpdatePhraseSet][google.cloud.speech.v2.Speech.UpdatePhraseSet] + method. + phrase_set (:class:`google.cloud.speech_v2.types.PhraseSet`): + Required. The PhraseSet to update. + + The PhraseSet's ``name`` field is used to identify the + PhraseSet to update. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}``. + + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to update. If empty, all non-default + valued fields are considered for update. Use ``*`` to + update the entire PhraseSet resource. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [phrase_set, update_mask] + 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.UpdatePhraseSetRequest): + request = cloud_speech.UpdatePhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if phrase_set is not None: + request.phrase_set = phrase_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("phrase_set.name", request.phrase_set.name),) + ), + ) + + # 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.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_phrase_set( + self, + request: Optional[Union[cloud_speech.DeletePhraseSetRequest, dict]] = None, + *, + name: Optional[str] = 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"""Deletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + async def sample_delete_phrase_set(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.DeletePhraseSetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.DeletePhraseSetRequest, dict]]): + The request object. Request message for the + [DeletePhraseSet][google.cloud.speech.v2.Speech.DeletePhraseSet] + method. + name (:class:`str`): + Required. The name of the PhraseSet to delete. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [name] + 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.DeletePhraseSetRequest): + request = cloud_speech.DeletePhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def undelete_phrase_set( + self, + request: Optional[Union[cloud_speech.UndeletePhraseSetRequest, dict]] = None, + *, + name: Optional[str] = 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"""Undeletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + async def sample_undelete_phrase_set(): + # Create a client + client = speech_v2.SpeechAsyncClient() + + # Initialize request argument(s) + request = speech_v2.UndeletePhraseSetRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.speech_v2.types.UndeletePhraseSetRequest, dict]]): + The request object. Request message for the + [UndeletePhraseSet][google.cloud.speech.v2.Speech.UndeletePhraseSet] + method. + name (:class:`str`): + Required. The name of the PhraseSet to undelete. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [name] + 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.UndeletePhraseSetRequest): + request = cloud_speech.UndeletePhraseSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_phrase_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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: + None + """ + # 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` 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: + None + """ + # 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` 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: + ~.location_pb2.Location: + Location 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 request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` 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 request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SpeechAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/client.py new file mode 100644 index 0000000000000000000000000000000000000000..91f7f684e869cb7baa8de782ba2fdc59fb0bfcff --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/client.py @@ -0,0 +1,4351 @@ +# -*- 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 os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.speech_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.speech_v2.services.speech import pagers +from google.cloud.speech_v2.types import cloud_speech + +from .transports.base import DEFAULT_CLIENT_INFO, SpeechTransport +from .transports.grpc import SpeechGrpcTransport +from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport +from .transports.rest import SpeechRestTransport + + +class SpeechClientMeta(type): + """Metaclass for the Speech client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] + _transport_registry["grpc"] = SpeechGrpcTransport + _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport + _transport_registry["rest"] = SpeechRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SpeechTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SpeechClient(metaclass=SpeechClientMeta): + """Enables speech transcription and resource management.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "speech.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "speech.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + SpeechClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SpeechClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SpeechTransport: + """Returns the transport used by the client instance. + + Returns: + SpeechTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def config_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified config string.""" + return "projects/{project}/locations/{location}/config".format( + project=project, + location=location, + ) + + @staticmethod + def parse_config_path(path: str) -> Dict[str, str]: + """Parses a config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/config$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + crypto_key_version: str, + ) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str, str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_class_path( + project: str, + location: str, + custom_class: str, + ) -> str: + """Returns a fully-qualified custom_class string.""" + return "projects/{project}/locations/{location}/customClasses/{custom_class}".format( + project=project, + location=location, + custom_class=custom_class, + ) + + @staticmethod + def parse_custom_class_path(path: str) -> Dict[str, str]: + """Parses a custom_class path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/customClasses/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def phrase_set_path( + project: str, + location: str, + phrase_set: str, + ) -> str: + """Returns a fully-qualified phrase_set string.""" + return "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( + project=project, + location=location, + phrase_set=phrase_set, + ) + + @staticmethod + def parse_phrase_set_path(path: str) -> Dict[str, str]: + """Parses a phrase_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/phraseSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def recognizer_path( + project: str, + location: str, + recognizer: str, + ) -> str: + """Returns a fully-qualified recognizer string.""" + return ( + "projects/{project}/locations/{location}/recognizers/{recognizer}".format( + project=project, + location=location, + recognizer=recognizer, + ) + ) + + @staticmethod + def parse_recognizer_path(path: str) -> Dict[str, str]: + """Parses a recognizer path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/recognizers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. 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. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = SpeechClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = SpeechClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SpeechClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SpeechClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SpeechClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SpeechClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._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._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SpeechTransport, Callable[..., SpeechTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the speech 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. + 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 the ``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_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + SpeechClient._read_environment_variables() + ) + self._client_cert_source = SpeechClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SpeechClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SpeechTransport) + if transport_provided: + # transport is a SpeechTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(SpeechTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or SpeechClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SpeechTransport], Callable[..., SpeechTransport] + ] = ( + SpeechClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SpeechTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.speech_v2.SpeechClient`.", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.speech.v2.Speech", + "credentialsType": None, + }, + ) + + def create_recognizer( + self, + request: Optional[Union[cloud_speech.CreateRecognizerRequest, dict]] = None, + *, + parent: Optional[str] = None, + recognizer: Optional[cloud_speech.Recognizer] = None, + recognizer_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + def sample_create_recognizer(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.CreateRecognizerRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.CreateRecognizerRequest, dict]): + The request object. Request message for the + [CreateRecognizer][google.cloud.speech.v2.Speech.CreateRecognizer] + method. + parent (str): + Required. The project and location where this Recognizer + will be created. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + recognizer (google.cloud.speech_v2.types.Recognizer): + Required. The Recognizer to create. + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + recognizer_id (str): + The ID to use for the Recognizer, which will become the + final component of the Recognizer's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``recognizer_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.speech_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [parent, recognizer, recognizer_id] + 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.CreateRecognizerRequest): + request = cloud_speech.CreateRecognizerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if recognizer is not None: + request.recognizer = recognizer + if recognizer_id is not None: + request.recognizer_id = recognizer_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_recognizer] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_recognizers( + self, + request: Optional[Union[cloud_speech.ListRecognizersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListRecognizersPager: + r"""Lists Recognizers. + + .. 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_v2 + + def sample_list_recognizers(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.ListRecognizersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_recognizers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.ListRecognizersRequest, dict]): + The request object. Request message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + parent (str): + Required. The project and location of Recognizers to + list. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.services.speech.pagers.ListRecognizersPager: + Response message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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.ListRecognizersRequest): + request = cloud_speech.ListRecognizersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_recognizers] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRecognizersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_recognizer( + self, + request: Optional[Union[cloud_speech.GetRecognizerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Recognizer: + r"""Returns the requested + [Recognizer][google.cloud.speech.v2.Recognizer]. Fails with + [NOT_FOUND][google.rpc.Code.NOT_FOUND] if the requested + Recognizer doesn't exist. + + .. 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_v2 + + def sample_get_recognizer(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.GetRecognizerRequest( + name="name_value", + ) + + # Make the request + response = client.get_recognizer(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.GetRecognizerRequest, dict]): + The request object. Request message for the + [GetRecognizer][google.cloud.speech.v2.Speech.GetRecognizer] + method. + name (str): + Required. The name of the Recognizer to retrieve. The + expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.types.Recognizer: + A Recognizer message. Stores + recognition configuration and metadata. + + """ + # 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 = [name] + 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.GetRecognizerRequest): + request = cloud_speech.GetRecognizerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_recognizer] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_recognizer( + self, + request: Optional[Union[cloud_speech.UpdateRecognizerRequest, dict]] = None, + *, + recognizer: Optional[cloud_speech.Recognizer] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + def sample_update_recognizer(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.UpdateRecognizerRequest( + ) + + # Make the request + operation = client.update_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.UpdateRecognizerRequest, dict]): + The request object. Request message for the + [UpdateRecognizer][google.cloud.speech.v2.Speech.UpdateRecognizer] + method. + recognizer (google.cloud.speech_v2.types.Recognizer): + Required. The Recognizer to update. + + The Recognizer's ``name`` field is used to identify the + Recognizer to update. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to update. If empty, all non-default + valued fields are considered for update. Use ``*`` to + update the entire Recognizer resource. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.speech_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [recognizer, update_mask] + 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.UpdateRecognizerRequest): + request = cloud_speech.UpdateRecognizerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if recognizer is not None: + request.recognizer = recognizer + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_recognizer] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("recognizer.name", request.recognizer.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_recognizer( + self, + request: Optional[Union[cloud_speech.DeleteRecognizerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + def sample_delete_recognizer(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.DeleteRecognizerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.DeleteRecognizerRequest, dict]): + The request object. Request message for the + [DeleteRecognizer][google.cloud.speech.v2.Speech.DeleteRecognizer] + method. + name (str): + Required. The name of the Recognizer to delete. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.speech_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [name] + 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.DeleteRecognizerRequest): + request = cloud_speech.DeleteRecognizerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_recognizer] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def undelete_recognizer( + self, + request: Optional[Union[cloud_speech.UndeleteRecognizerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Undeletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + .. 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_v2 + + def sample_undelete_recognizer(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.UndeleteRecognizerRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_recognizer(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.UndeleteRecognizerRequest, dict]): + The request object. Request message for the + [UndeleteRecognizer][google.cloud.speech.v2.Speech.UndeleteRecognizer] + method. + name (str): + Required. The name of the Recognizer to undelete. + Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.speech_v2.types.Recognizer` A + Recognizer message. Stores recognition configuration and + metadata. + + """ + # 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 = [name] + 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.UndeleteRecognizerRequest): + request = cloud_speech.UndeleteRecognizerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_recognizer] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.Recognizer, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def recognize( + self, + request: Optional[Union[cloud_speech.RecognizeRequest, dict]] = None, + *, + recognizer: Optional[str] = None, + config: Optional[cloud_speech.RecognitionConfig] = None, + config_mask: Optional[field_mask_pb2.FieldMask] = None, + content: Optional[bytes] = None, + uri: Optional[str] = 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_v2 + + def sample_recognize(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.RecognizeRequest( + content=b'content_blob', + recognizer="recognizer_value", + ) + + # Make the request + response = client.recognize(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.RecognizeRequest, dict]): + The request object. Request message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. Either ``content`` or ``uri`` must be supplied. + Supplying both or neither returns + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + See `content + limits `__. + recognizer (str): + Required. The name of the Recognizer to use during + recognition. The expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + The {recognizer} segment may be set to ``_`` to use an + empty implicit Recognizer. + + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config (google.cloud.speech_v2.types.RecognitionConfig): + Features and audio metadata to use for the Automatic + Speech Recognition. This field in combination with the + [config_mask][google.cloud.speech.v2.RecognizeRequest.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource. + + This corresponds to the ``config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields in + [config][google.cloud.speech.v2.RecognizeRequest.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all non-default valued fields in + [config][google.cloud.speech.v2.RecognizeRequest.config] + override the values in the recognizer for this + recognition request. If a mask is provided, only the + fields listed in the mask override the config in the + recognizer for this recognition request. If a wildcard + (``*``) is provided, + [config][google.cloud.speech.v2.RecognizeRequest.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + + This corresponds to the ``config_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content (bytes): + The audio data bytes encoded as specified in + [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. + As with all bytes fields, proto buffers use a pure + binary representation, whereas JSON representations use + base64. + + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + uri (str): + URI that points to a file that contains audio data bytes + as specified in + [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. + The file must not be compressed (for example, gzip). + Currently, only Google Cloud Storage URIs are supported, + which must be specified in the following format: + ``gs://bucket_name/object_name`` (other URI formats + return + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + + This corresponds to the ``uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.types.RecognizeResponse: + Response message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. + + """ + # 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 = [recognizer, config, config_mask, content, uri] + 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 recognizer is not None: + request.recognizer = recognizer + if config is not None: + request.config = config + if config_mask is not None: + request.config_mask = config_mask + if content is not None: + request.content = content + if uri is not None: + request.uri = uri + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.recognize] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("recognizer", request.recognizer),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_recognize( + self, + requests: Optional[Iterator[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]]] = (), + ) -> Iterable[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_v2 + + def sample_streaming_recognize(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.StreamingRecognizeRequest( + recognizer="recognizer_value", + ) + + # This method expects an iterator which contains + # 'speech_v2.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 = client.streaming_recognize(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.speech_v2.types.StreamingRecognizeRequest]): + The request object iterator. Request message for the + [StreamingRecognize][google.cloud.speech.v2.Speech.StreamingRecognize] + method. Multiple + [StreamingRecognizeRequest][google.cloud.speech.v2.StreamingRecognizeRequest] + messages are sent in one call. + + If the [Recognizer][google.cloud.speech.v2.Recognizer] + referenced by + [recognizer][google.cloud.speech.v2.StreamingRecognizeRequest.recognizer] + contains a fully specified request configuration then + the stream may only contain messages with only + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio] + set. + + Otherwise the first message must contain a + [recognizer][google.cloud.speech.v2.StreamingRecognizeRequest.recognizer] + and a + [streaming_config][google.cloud.speech.v2.StreamingRecognizeRequest.streaming_config] + message that together fully specify the request + configuration and must not contain + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio]. + All subsequent messages must only have + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio] + set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + Iterable[google.cloud.speech_v2.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 then + no messages are streamed back to the client. + + Here are some examples of + \`StreamingRecognizeResponse`s 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._transport._wrapped_methods[self._transport.streaming_recognize] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_recognize( + self, + request: Optional[Union[cloud_speech.BatchRecognizeRequest, dict]] = None, + *, + recognizer: Optional[str] = None, + config: Optional[cloud_speech.RecognitionConfig] = None, + config_mask: Optional[field_mask_pb2.FieldMask] = None, + files: Optional[ + MutableSequence[cloud_speech.BatchRecognizeFileMetadata] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Performs batch asynchronous speech recognition: send + a request with N audio files and receive a long running + operation that can be polled to see when the + transcriptions are finished. + + .. 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_v2 + + def sample_batch_recognize(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.BatchRecognizeRequest( + recognizer="recognizer_value", + ) + + # Make the request + operation = client.batch_recognize(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.BatchRecognizeRequest, dict]): + The request object. Request message for the + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + method. + recognizer (str): + Required. The name of the Recognizer to use during + recognition. The expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + The {recognizer} segment may be set to ``_`` to use an + empty implicit Recognizer. + + This corresponds to the ``recognizer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config (google.cloud.speech_v2.types.RecognitionConfig): + Features and audio metadata to use for the Automatic + Speech Recognition. This field in combination with the + [config_mask][google.cloud.speech.v2.BatchRecognizeRequest.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource. + + This corresponds to the ``config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields in + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all given fields in + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + override the values in the recognizer for this + recognition request. If a mask is provided, only the + fields listed in the mask override the config in the + recognizer for this recognition request. If a wildcard + (``*``) is provided, + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + + This corresponds to the ``config_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + files (MutableSequence[google.cloud.speech_v2.types.BatchRecognizeFileMetadata]): + Audio files with file metadata for + ASR. The maximum number of files allowed + to be specified is 15. + + This corresponds to the ``files`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.BatchRecognizeResponse` Response message for + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + that is packaged into a longrunning + [Operation][google.longrunning.Operation]. + + """ + # 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 = [recognizer, config, config_mask, files] + 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.BatchRecognizeRequest): + request = cloud_speech.BatchRecognizeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if recognizer is not None: + request.recognizer = recognizer + if config is not None: + request.config = config + if config_mask is not None: + request.config_mask = config_mask + if files is not None: + request.files = files + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_recognize] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("recognizer", request.recognizer),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.BatchRecognizeResponse, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_config( + self, + request: Optional[Union[cloud_speech.GetConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Config: + r"""Returns the requested [Config][google.cloud.speech.v2.Config]. + + .. 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_v2 + + def sample_get_config(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.GetConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.GetConfigRequest, dict]): + The request object. Request message for the + [GetConfig][google.cloud.speech.v2.Speech.GetConfig] + method. + name (str): + Required. The name of the config to retrieve. There is + exactly one config resource per project per location. + The expected format is + ``projects/{project}/locations/{location}/config``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.types.Config: + Message representing the config for the Speech-to-Text API. This includes an + optional [KMS + key](https://cloud.google.com/kms/docs/resource-hierarchy#keys) + with which incoming data will be encrypted. + + """ + # 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 = [name] + 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.GetConfigRequest): + request = cloud_speech.GetConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_config] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_config( + self, + request: Optional[Union[cloud_speech.UpdateConfigRequest, dict]] = None, + *, + config: Optional[cloud_speech.Config] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Config: + r"""Updates the [Config][google.cloud.speech.v2.Config]. + + .. 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_v2 + + def sample_update_config(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.UpdateConfigRequest( + ) + + # Make the request + response = client.update_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.UpdateConfigRequest, dict]): + The request object. Request message for the + [UpdateConfig][google.cloud.speech.v2.Speech.UpdateConfig] + method. + config (google.cloud.speech_v2.types.Config): + Required. The config to update. + + The config's ``name`` field is used to identify the + config to be updated. The expected format is + ``projects/{project}/locations/{location}/config``. + + This corresponds to the ``config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.types.Config: + Message representing the config for the Speech-to-Text API. This includes an + optional [KMS + key](https://cloud.google.com/kms/docs/resource-hierarchy#keys) + with which incoming data will be encrypted. + + """ + # 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, update_mask] + 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.UpdateConfigRequest): + request = cloud_speech.UpdateConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if config is not None: + request.config = config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("config.name", request.config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_custom_class( + self, + request: Optional[Union[cloud_speech.CreateCustomClassRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_class: Optional[cloud_speech.CustomClass] = None, + custom_class_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + def sample_create_custom_class(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.CreateCustomClassRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.CreateCustomClassRequest, dict]): + The request object. Request message for the + [CreateCustomClass][google.cloud.speech.v2.Speech.CreateCustomClass] + method. + parent (str): + Required. The project and location where this + CustomClass will be created. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_class (google.cloud.speech_v2.types.CustomClass): + Required. The CustomClass to create. + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_class_id (str): + The ID to use for the CustomClass, which will become the + final component of the CustomClass's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``custom_class_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [parent, custom_class, custom_class_id] + 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.CreateCustomClassRequest): + request = cloud_speech.CreateCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_class is not None: + request.custom_class = custom_class + if custom_class_id is not None: + request.custom_class_id = custom_class_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_custom_class] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_custom_classes( + self, + request: Optional[Union[cloud_speech.ListCustomClassesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCustomClassesPager: + r"""Lists CustomClasses. + + .. 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_v2 + + def sample_list_custom_classes(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.ListCustomClassesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_classes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.ListCustomClassesRequest, dict]): + The request object. Request message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + parent (str): + Required. The project and location of CustomClass + resources to list. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.services.speech.pagers.ListCustomClassesPager: + Response message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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.ListCustomClassesRequest): + request = cloud_speech.ListCustomClassesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_custom_classes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCustomClassesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_custom_class( + self, + request: Optional[Union[cloud_speech.GetCustomClassRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.CustomClass: + r"""Returns the requested + [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + def sample_get_custom_class(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.GetCustomClassRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_class(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.GetCustomClassRequest, dict]): + The request object. Request message for the + [GetCustomClass][google.cloud.speech.v2.Speech.GetCustomClass] + method. + name (str): + Required. The name of the CustomClass to retrieve. The + expected format is + ``projects/{project}/locations/{location}/customClasses/{custom_class}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.types.CustomClass: + CustomClass for biasing in speech + recognition. Used to define a set of + words or phrases that represents a + common concept or theme likely to appear + in your audio, for example a list of + passenger ship names. + + """ + # 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 = [name] + 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.GetCustomClassRequest): + request = cloud_speech.GetCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_custom_class] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_custom_class( + self, + request: Optional[Union[cloud_speech.UpdateCustomClassRequest, dict]] = None, + *, + custom_class: Optional[cloud_speech.CustomClass] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + def sample_update_custom_class(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.UpdateCustomClassRequest( + ) + + # Make the request + operation = client.update_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.UpdateCustomClassRequest, dict]): + The request object. Request message for the + [UpdateCustomClass][google.cloud.speech.v2.Speech.UpdateCustomClass] + method. + custom_class (google.cloud.speech_v2.types.CustomClass): + Required. The CustomClass to update. + + The CustomClass's ``name`` field is used to identify the + CustomClass to update. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}``. + + This corresponds to the ``custom_class`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If + empty, all fields are considered for + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [custom_class, update_mask] + 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.UpdateCustomClassRequest): + request = cloud_speech.UpdateCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_class is not None: + request.custom_class = custom_class + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_custom_class] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("custom_class.name", request.custom_class.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_custom_class( + self, + request: Optional[Union[cloud_speech.DeleteCustomClassRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + def sample_delete_custom_class(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.DeleteCustomClassRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.DeleteCustomClassRequest, dict]): + The request object. Request message for the + [DeleteCustomClass][google.cloud.speech.v2.Speech.DeleteCustomClass] + method. + name (str): + Required. The name of the CustomClass to delete. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [name] + 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.DeleteCustomClassRequest): + request = cloud_speech.DeleteCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_custom_class] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def undelete_custom_class( + self, + request: Optional[Union[cloud_speech.UndeleteCustomClassRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Undeletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + .. 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_v2 + + def sample_undelete_custom_class(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.UndeleteCustomClassRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_custom_class(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.UndeleteCustomClassRequest, dict]): + The request object. Request message for the + [UndeleteCustomClass][google.cloud.speech.v2.Speech.UndeleteCustomClass] + method. + name (str): + Required. The name of the CustomClass to undelete. + Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.CustomClass` CustomClass for biasing in speech recognition. Used to define a set of words + or phrases that represents a common concept or theme + likely to appear in your audio, for example a list of + passenger ship names. + + """ + # 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 = [name] + 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.UndeleteCustomClassRequest): + request = cloud_speech.UndeleteCustomClassRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_custom_class] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.CustomClass, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_phrase_set( + self, + request: Optional[Union[cloud_speech.CreatePhraseSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + phrase_set: Optional[cloud_speech.PhraseSet] = None, + phrase_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + def sample_create_phrase_set(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.CreatePhraseSetRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.CreatePhraseSetRequest, dict]): + The request object. Request message for the + [CreatePhraseSet][google.cloud.speech.v2.Speech.CreatePhraseSet] + method. + parent (str): + Required. The project and location where this PhraseSet + will be created. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + phrase_set (google.cloud.speech_v2.types.PhraseSet): + Required. The PhraseSet to create. + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + phrase_set_id (str): + The ID to use for the PhraseSet, which will become the + final component of the PhraseSet's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``phrase_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [parent, phrase_set, phrase_set_id] + 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.CreatePhraseSetRequest): + request = cloud_speech.CreatePhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if phrase_set is not None: + request.phrase_set = phrase_set + if phrase_set_id is not None: + request.phrase_set_id = phrase_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_phrase_sets( + self, + request: Optional[Union[cloud_speech.ListPhraseSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPhraseSetsPager: + r"""Lists PhraseSets. + + .. 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_v2 + + def sample_list_phrase_sets(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.ListPhraseSetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_phrase_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.ListPhraseSetsRequest, dict]): + The request object. Request message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + parent (str): + Required. The project and location of PhraseSet + resources to list. The expected format is + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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_v2.services.speech.pagers.ListPhraseSetsPager: + Response message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [parent] + 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.ListPhraseSetsRequest): + request = cloud_speech.ListPhraseSetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_phrase_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPhraseSetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_phrase_set( + self, + request: Optional[Union[cloud_speech.GetPhraseSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.PhraseSet: + r"""Returns the requested + [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + def sample_get_phrase_set(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.GetPhraseSetRequest( + name="name_value", + ) + + # Make the request + response = client.get_phrase_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.GetPhraseSetRequest, dict]): + The request object. Request message for the + [GetPhraseSet][google.cloud.speech.v2.Speech.GetPhraseSet] + method. + name (str): + Required. The name of the PhraseSet to retrieve. The + expected format is + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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_v2.types.PhraseSet: + PhraseSet for biasing in speech + recognition. A PhraseSet is used to + provide "hints" to the speech recognizer + to favor specific words and phrases in + the results. + + """ + # 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 = [name] + 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.GetPhraseSetRequest): + request = cloud_speech.GetPhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_phrase_set( + self, + request: Optional[Union[cloud_speech.UpdatePhraseSetRequest, dict]] = None, + *, + phrase_set: Optional[cloud_speech.PhraseSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + def sample_update_phrase_set(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.UpdatePhraseSetRequest( + ) + + # Make the request + operation = client.update_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.UpdatePhraseSetRequest, dict]): + The request object. Request message for the + [UpdatePhraseSet][google.cloud.speech.v2.Speech.UpdatePhraseSet] + method. + phrase_set (google.cloud.speech_v2.types.PhraseSet): + Required. The PhraseSet to update. + + The PhraseSet's ``name`` field is used to identify the + PhraseSet to update. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}``. + + This corresponds to the ``phrase_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to update. If empty, all non-default + valued fields are considered for update. Use ``*`` to + update the entire PhraseSet resource. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [phrase_set, update_mask] + 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.UpdatePhraseSetRequest): + request = cloud_speech.UpdatePhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if phrase_set is not None: + request.phrase_set = phrase_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("phrase_set.name", request.phrase_set.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_phrase_set( + self, + request: Optional[Union[cloud_speech.DeletePhraseSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + def sample_delete_phrase_set(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.DeletePhraseSetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.DeletePhraseSetRequest, dict]): + The request object. Request message for the + [DeletePhraseSet][google.cloud.speech.v2.Speech.DeletePhraseSet] + method. + name (str): + Required. The name of the PhraseSet to delete. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [name] + 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.DeletePhraseSetRequest): + request = cloud_speech.DeletePhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def undelete_phrase_set( + self, + request: Optional[Union[cloud_speech.UndeletePhraseSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Undeletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + .. 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_v2 + + def sample_undelete_phrase_set(): + # Create a client + client = speech_v2.SpeechClient() + + # Initialize request argument(s) + request = speech_v2.UndeletePhraseSetRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_phrase_set(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.speech_v2.types.UndeletePhraseSetRequest, dict]): + The request object. Request message for the + [UndeletePhraseSet][google.cloud.speech.v2.Speech.UndeletePhraseSet] + method. + name (str): + Required. The name of the PhraseSet to undelete. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.speech_v2.types.PhraseSet` PhraseSet for biasing in speech recognition. A PhraseSet is used to provide + "hints" to the speech recognizer to favor specific + words and phrases in the results. + + """ + # 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 = [name] + 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.UndeletePhraseSetRequest): + request = cloud_speech.UndeletePhraseSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_phrase_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + cloud_speech.PhraseSet, + metadata_type=cloud_speech.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SpeechClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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.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`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + None + """ + # 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + None + """ + # 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.location_pb2.Location: + Location 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 request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` 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 request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SpeechClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2127feadecdca5eb9dc3de1de81dd89307af2e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/pagers.py @@ -0,0 +1,509 @@ +# -*- 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_v2.types import cloud_speech + + +class ListRecognizersPager: + """A pager for iterating through ``list_recognizers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.speech_v2.types.ListRecognizersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``recognizers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRecognizers`` requests and continue to iterate + through the ``recognizers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.speech_v2.types.ListRecognizersResponse` + 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.ListRecognizersResponse], + request: cloud_speech.ListRecognizersRequest, + response: cloud_speech.ListRecognizersResponse, + *, + 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_v2.types.ListRecognizersRequest): + The initial request object. + response (google.cloud.speech_v2.types.ListRecognizersResponse): + 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.ListRecognizersRequest(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.ListRecognizersResponse]: + 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[cloud_speech.Recognizer]: + for page in self.pages: + yield from page.recognizers + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRecognizersAsyncPager: + """A pager for iterating through ``list_recognizers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.speech_v2.types.ListRecognizersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``recognizers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRecognizers`` requests and continue to iterate + through the ``recognizers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.speech_v2.types.ListRecognizersResponse` + 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.ListRecognizersResponse]], + request: cloud_speech.ListRecognizersRequest, + response: cloud_speech.ListRecognizersResponse, + *, + 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_v2.types.ListRecognizersRequest): + The initial request object. + response (google.cloud.speech_v2.types.ListRecognizersResponse): + 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.ListRecognizersRequest(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.ListRecognizersResponse]: + 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[cloud_speech.Recognizer]: + async def async_generator(): + async for page in self.pages: + for response in page.recognizers: + 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_v2.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_v2.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.ListCustomClassesResponse], + request: cloud_speech.ListCustomClassesRequest, + response: cloud_speech.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_v2.types.ListCustomClassesRequest): + The initial request object. + response (google.cloud.speech_v2.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.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.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[cloud_speech.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_v2.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_v2.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.ListCustomClassesResponse]], + request: cloud_speech.ListCustomClassesRequest, + response: cloud_speech.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_v2.types.ListCustomClassesRequest): + The initial request object. + response (google.cloud.speech_v2.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.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.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[cloud_speech.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) + + +class ListPhraseSetsPager: + """A pager for iterating through ``list_phrase_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.speech_v2.types.ListPhraseSetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``phrase_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPhraseSets`` requests and continue to iterate + through the ``phrase_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.speech_v2.types.ListPhraseSetsResponse` + 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.ListPhraseSetsResponse], + request: cloud_speech.ListPhraseSetsRequest, + response: cloud_speech.ListPhraseSetsResponse, + *, + 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_v2.types.ListPhraseSetsRequest): + The initial request object. + response (google.cloud.speech_v2.types.ListPhraseSetsResponse): + 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.ListPhraseSetsRequest(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.ListPhraseSetsResponse]: + 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[cloud_speech.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 ListPhraseSetsAsyncPager: + """A pager for iterating through ``list_phrase_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.speech_v2.types.ListPhraseSetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``phrase_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPhraseSets`` requests and continue to iterate + through the ``phrase_sets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.speech_v2.types.ListPhraseSetsResponse` + 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.ListPhraseSetsResponse]], + request: cloud_speech.ListPhraseSetsRequest, + response: cloud_speech.ListPhraseSetsResponse, + *, + 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_v2.types.ListPhraseSetsRequest): + The initial request object. + response (google.cloud.speech_v2.types.ListPhraseSetsResponse): + 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.ListPhraseSetsRequest(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.ListPhraseSetsResponse]: + 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[cloud_speech.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) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5150a365b2d2d5454e96bdaf2968ca4dc59ba6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/__init__.py @@ -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", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8bbc00a8bd8ded379df0be047977220568b553ed --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/base.py @@ -0,0 +1,594 @@ +# -*- 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 +import google.auth # type: ignore +import google.protobuf +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 +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.speech_v2 import gapic_version as package_version +from google.cloud.speech_v2.types import cloud_speech + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_recognizer: gapic_v1.method.wrap_method( + self.create_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.list_recognizers: gapic_v1.method.wrap_method( + self.list_recognizers, + default_timeout=None, + client_info=client_info, + ), + self.get_recognizer: gapic_v1.method.wrap_method( + self.get_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.update_recognizer: gapic_v1.method.wrap_method( + self.update_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.delete_recognizer: gapic_v1.method.wrap_method( + self.delete_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.undelete_recognizer: gapic_v1.method.wrap_method( + self.undelete_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.recognize: gapic_v1.method.wrap_method( + self.recognize, + default_timeout=None, + client_info=client_info, + ), + self.streaming_recognize: gapic_v1.method.wrap_method( + self.streaming_recognize, + default_timeout=None, + client_info=client_info, + ), + self.batch_recognize: gapic_v1.method.wrap_method( + self.batch_recognize, + default_timeout=None, + client_info=client_info, + ), + self.get_config: gapic_v1.method.wrap_method( + self.get_config, + default_timeout=None, + client_info=client_info, + ), + self.update_config: gapic_v1.method.wrap_method( + self.update_config, + 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.list_custom_classes: gapic_v1.method.wrap_method( + self.list_custom_classes, + 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.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.undelete_custom_class: gapic_v1.method.wrap_method( + self.undelete_custom_class, + default_timeout=None, + client_info=client_info, + ), + self.create_phrase_set: gapic_v1.method.wrap_method( + self.create_phrase_set, + default_timeout=None, + client_info=client_info, + ), + self.list_phrase_sets: gapic_v1.method.wrap_method( + self.list_phrase_sets, + 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.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.undelete_phrase_set: gapic_v1.method.wrap_method( + self.undelete_phrase_set, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + 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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_recognizer( + self, + ) -> Callable[ + [cloud_speech.CreateRecognizerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_recognizers( + self, + ) -> Callable[ + [cloud_speech.ListRecognizersRequest], + Union[ + cloud_speech.ListRecognizersResponse, + Awaitable[cloud_speech.ListRecognizersResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_recognizer( + self, + ) -> Callable[ + [cloud_speech.GetRecognizerRequest], + Union[cloud_speech.Recognizer, Awaitable[cloud_speech.Recognizer]], + ]: + raise NotImplementedError() + + @property + def update_recognizer( + self, + ) -> Callable[ + [cloud_speech.UpdateRecognizerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_recognizer( + self, + ) -> Callable[ + [cloud_speech.DeleteRecognizerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def undelete_recognizer( + self, + ) -> Callable[ + [cloud_speech.UndeleteRecognizerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def recognize( + self, + ) -> Callable[ + [cloud_speech.RecognizeRequest], + Union[ + cloud_speech.RecognizeResponse, Awaitable[cloud_speech.RecognizeResponse] + ], + ]: + raise NotImplementedError() + + @property + def streaming_recognize( + self, + ) -> Callable[ + [cloud_speech.StreamingRecognizeRequest], + Union[ + cloud_speech.StreamingRecognizeResponse, + Awaitable[cloud_speech.StreamingRecognizeResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_recognize( + self, + ) -> Callable[ + [cloud_speech.BatchRecognizeRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_config( + self, + ) -> Callable[ + [cloud_speech.GetConfigRequest], + Union[cloud_speech.Config, Awaitable[cloud_speech.Config]], + ]: + raise NotImplementedError() + + @property + def update_config( + self, + ) -> Callable[ + [cloud_speech.UpdateConfigRequest], + Union[cloud_speech.Config, Awaitable[cloud_speech.Config]], + ]: + raise NotImplementedError() + + @property + def create_custom_class( + self, + ) -> Callable[ + [cloud_speech.CreateCustomClassRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech.ListCustomClassesRequest], + Union[ + cloud_speech.ListCustomClassesResponse, + Awaitable[cloud_speech.ListCustomClassesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_custom_class( + self, + ) -> Callable[ + [cloud_speech.GetCustomClassRequest], + Union[cloud_speech.CustomClass, Awaitable[cloud_speech.CustomClass]], + ]: + raise NotImplementedError() + + @property + def update_custom_class( + self, + ) -> Callable[ + [cloud_speech.UpdateCustomClassRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_custom_class( + self, + ) -> Callable[ + [cloud_speech.DeleteCustomClassRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def undelete_custom_class( + self, + ) -> Callable[ + [cloud_speech.UndeleteCustomClassRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_phrase_set( + self, + ) -> Callable[ + [cloud_speech.CreatePhraseSetRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_phrase_sets( + self, + ) -> Callable[ + [cloud_speech.ListPhraseSetsRequest], + Union[ + cloud_speech.ListPhraseSetsResponse, + Awaitable[cloud_speech.ListPhraseSetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_phrase_set( + self, + ) -> Callable[ + [cloud_speech.GetPhraseSetRequest], + Union[cloud_speech.PhraseSet, Awaitable[cloud_speech.PhraseSet]], + ]: + raise NotImplementedError() + + @property + def update_phrase_set( + self, + ) -> Callable[ + [cloud_speech.UpdatePhraseSetRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_phrase_set( + self, + ) -> Callable[ + [cloud_speech.DeletePhraseSetRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def undelete_phrase_set( + self, + ) -> Callable[ + [cloud_speech.UndeletePhraseSetRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + 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 cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SpeechTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..f65b4338a3722a6daa309518bcbfc451785a8d46 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/grpc.py @@ -0,0 +1,1079 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.speech_v2.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)!r}" + + 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.v2.Speech", + "rpcName": str(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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SpeechGrpcTransport(SpeechTransport): + """gRPC backend transport for Speech. + + Enables speech transcription and resource management. + + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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 create_recognizer( + self, + ) -> Callable[[cloud_speech.CreateRecognizerRequest], operations_pb2.Operation]: + r"""Return a callable for the create recognizer method over gRPC. + + Creates a [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.CreateRecognizerRequest], + ~.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 "create_recognizer" not in self._stubs: + self._stubs["create_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/CreateRecognizer", + request_serializer=cloud_speech.CreateRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_recognizer"] + + @property + def list_recognizers( + self, + ) -> Callable[ + [cloud_speech.ListRecognizersRequest], cloud_speech.ListRecognizersResponse + ]: + r"""Return a callable for the list recognizers method over gRPC. + + Lists Recognizers. + + Returns: + Callable[[~.ListRecognizersRequest], + ~.ListRecognizersResponse]: + 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_recognizers" not in self._stubs: + self._stubs["list_recognizers"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/ListRecognizers", + request_serializer=cloud_speech.ListRecognizersRequest.serialize, + response_deserializer=cloud_speech.ListRecognizersResponse.deserialize, + ) + return self._stubs["list_recognizers"] + + @property + def get_recognizer( + self, + ) -> Callable[[cloud_speech.GetRecognizerRequest], cloud_speech.Recognizer]: + r"""Return a callable for the get recognizer method over gRPC. + + Returns the requested + [Recognizer][google.cloud.speech.v2.Recognizer]. Fails with + [NOT_FOUND][google.rpc.Code.NOT_FOUND] if the requested + Recognizer doesn't exist. + + Returns: + Callable[[~.GetRecognizerRequest], + ~.Recognizer]: + 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_recognizer" not in self._stubs: + self._stubs["get_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/GetRecognizer", + request_serializer=cloud_speech.GetRecognizerRequest.serialize, + response_deserializer=cloud_speech.Recognizer.deserialize, + ) + return self._stubs["get_recognizer"] + + @property + def update_recognizer( + self, + ) -> Callable[[cloud_speech.UpdateRecognizerRequest], operations_pb2.Operation]: + r"""Return a callable for the update recognizer method over gRPC. + + Updates the [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.UpdateRecognizerRequest], + ~.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 "update_recognizer" not in self._stubs: + self._stubs["update_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdateRecognizer", + request_serializer=cloud_speech.UpdateRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_recognizer"] + + @property + def delete_recognizer( + self, + ) -> Callable[[cloud_speech.DeleteRecognizerRequest], operations_pb2.Operation]: + r"""Return a callable for the delete recognizer method over gRPC. + + Deletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.DeleteRecognizerRequest], + ~.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 "delete_recognizer" not in self._stubs: + self._stubs["delete_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/DeleteRecognizer", + request_serializer=cloud_speech.DeleteRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_recognizer"] + + @property + def undelete_recognizer( + self, + ) -> Callable[[cloud_speech.UndeleteRecognizerRequest], operations_pb2.Operation]: + r"""Return a callable for the undelete recognizer method over gRPC. + + Undeletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.UndeleteRecognizerRequest], + ~.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 "undelete_recognizer" not in self._stubs: + self._stubs["undelete_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UndeleteRecognizer", + request_serializer=cloud_speech.UndeleteRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["undelete_recognizer"] + + @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.v2.Speech/Recognize", + request_serializer=cloud_speech.RecognizeRequest.serialize, + response_deserializer=cloud_speech.RecognizeResponse.deserialize, + ) + return self._stubs["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.v2.Speech/StreamingRecognize", + request_serializer=cloud_speech.StreamingRecognizeRequest.serialize, + response_deserializer=cloud_speech.StreamingRecognizeResponse.deserialize, + ) + return self._stubs["streaming_recognize"] + + @property + def batch_recognize( + self, + ) -> Callable[[cloud_speech.BatchRecognizeRequest], operations_pb2.Operation]: + r"""Return a callable for the batch recognize method over gRPC. + + Performs batch asynchronous speech recognition: send + a request with N audio files and receive a long running + operation that can be polled to see when the + transcriptions are finished. + + Returns: + Callable[[~.BatchRecognizeRequest], + ~.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 "batch_recognize" not in self._stubs: + self._stubs["batch_recognize"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/BatchRecognize", + request_serializer=cloud_speech.BatchRecognizeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_recognize"] + + @property + def get_config( + self, + ) -> Callable[[cloud_speech.GetConfigRequest], cloud_speech.Config]: + r"""Return a callable for the get config method over gRPC. + + Returns the requested [Config][google.cloud.speech.v2.Config]. + + Returns: + Callable[[~.GetConfigRequest], + ~.Config]: + 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_config" not in self._stubs: + self._stubs["get_config"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/GetConfig", + request_serializer=cloud_speech.GetConfigRequest.serialize, + response_deserializer=cloud_speech.Config.deserialize, + ) + return self._stubs["get_config"] + + @property + def update_config( + self, + ) -> Callable[[cloud_speech.UpdateConfigRequest], cloud_speech.Config]: + r"""Return a callable for the update config method over gRPC. + + Updates the [Config][google.cloud.speech.v2.Config]. + + Returns: + Callable[[~.UpdateConfigRequest], + ~.Config]: + 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_config" not in self._stubs: + self._stubs["update_config"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdateConfig", + request_serializer=cloud_speech.UpdateConfigRequest.serialize, + response_deserializer=cloud_speech.Config.deserialize, + ) + return self._stubs["update_config"] + + @property + def create_custom_class( + self, + ) -> Callable[[cloud_speech.CreateCustomClassRequest], operations_pb2.Operation]: + r"""Return a callable for the create custom class method over gRPC. + + Creates a [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.CreateCustomClassRequest], + ~.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 "create_custom_class" not in self._stubs: + self._stubs["create_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/CreateCustomClass", + request_serializer=cloud_speech.CreateCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_custom_class"] + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech.ListCustomClassesRequest], cloud_speech.ListCustomClassesResponse + ]: + r"""Return a callable for the list custom classes method over gRPC. + + Lists CustomClasses. + + 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.v2.Speech/ListCustomClasses", + request_serializer=cloud_speech.ListCustomClassesRequest.serialize, + response_deserializer=cloud_speech.ListCustomClassesResponse.deserialize, + ) + return self._stubs["list_custom_classes"] + + @property + def get_custom_class( + self, + ) -> Callable[[cloud_speech.GetCustomClassRequest], cloud_speech.CustomClass]: + r"""Return a callable for the get custom class method over gRPC. + + Returns the requested + [CustomClass][google.cloud.speech.v2.CustomClass]. + + 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.v2.Speech/GetCustomClass", + request_serializer=cloud_speech.GetCustomClassRequest.serialize, + response_deserializer=cloud_speech.CustomClass.deserialize, + ) + return self._stubs["get_custom_class"] + + @property + def update_custom_class( + self, + ) -> Callable[[cloud_speech.UpdateCustomClassRequest], operations_pb2.Operation]: + r"""Return a callable for the update custom class method over gRPC. + + Updates the [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.UpdateCustomClassRequest], + ~.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 "update_custom_class" not in self._stubs: + self._stubs["update_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdateCustomClass", + request_serializer=cloud_speech.UpdateCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_custom_class"] + + @property + def delete_custom_class( + self, + ) -> Callable[[cloud_speech.DeleteCustomClassRequest], operations_pb2.Operation]: + r"""Return a callable for the delete custom class method over gRPC. + + Deletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.DeleteCustomClassRequest], + ~.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 "delete_custom_class" not in self._stubs: + self._stubs["delete_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/DeleteCustomClass", + request_serializer=cloud_speech.DeleteCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_custom_class"] + + @property + def undelete_custom_class( + self, + ) -> Callable[[cloud_speech.UndeleteCustomClassRequest], operations_pb2.Operation]: + r"""Return a callable for the undelete custom class method over gRPC. + + Undeletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.UndeleteCustomClassRequest], + ~.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 "undelete_custom_class" not in self._stubs: + self._stubs["undelete_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UndeleteCustomClass", + request_serializer=cloud_speech.UndeleteCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["undelete_custom_class"] + + @property + def create_phrase_set( + self, + ) -> Callable[[cloud_speech.CreatePhraseSetRequest], operations_pb2.Operation]: + r"""Return a callable for the create phrase set method over gRPC. + + Creates a [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.CreatePhraseSetRequest], + ~.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 "create_phrase_set" not in self._stubs: + self._stubs["create_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/CreatePhraseSet", + request_serializer=cloud_speech.CreatePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_phrase_set"] + + @property + def list_phrase_sets( + self, + ) -> Callable[ + [cloud_speech.ListPhraseSetsRequest], cloud_speech.ListPhraseSetsResponse + ]: + r"""Return a callable for the list phrase sets method over gRPC. + + Lists PhraseSets. + + Returns: + Callable[[~.ListPhraseSetsRequest], + ~.ListPhraseSetsResponse]: + 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_sets" not in self._stubs: + self._stubs["list_phrase_sets"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/ListPhraseSets", + request_serializer=cloud_speech.ListPhraseSetsRequest.serialize, + response_deserializer=cloud_speech.ListPhraseSetsResponse.deserialize, + ) + return self._stubs["list_phrase_sets"] + + @property + def get_phrase_set( + self, + ) -> Callable[[cloud_speech.GetPhraseSetRequest], cloud_speech.PhraseSet]: + r"""Return a callable for the get phrase set method over gRPC. + + Returns the requested + [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + 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.v2.Speech/GetPhraseSet", + request_serializer=cloud_speech.GetPhraseSetRequest.serialize, + response_deserializer=cloud_speech.PhraseSet.deserialize, + ) + return self._stubs["get_phrase_set"] + + @property + def update_phrase_set( + self, + ) -> Callable[[cloud_speech.UpdatePhraseSetRequest], operations_pb2.Operation]: + r"""Return a callable for the update phrase set method over gRPC. + + Updates the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.UpdatePhraseSetRequest], + ~.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 "update_phrase_set" not in self._stubs: + self._stubs["update_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdatePhraseSet", + request_serializer=cloud_speech.UpdatePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_phrase_set"] + + @property + def delete_phrase_set( + self, + ) -> Callable[[cloud_speech.DeletePhraseSetRequest], operations_pb2.Operation]: + r"""Return a callable for the delete phrase set method over gRPC. + + Deletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.DeletePhraseSetRequest], + ~.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 "delete_phrase_set" not in self._stubs: + self._stubs["delete_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/DeletePhraseSet", + request_serializer=cloud_speech.DeletePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_phrase_set"] + + @property + def undelete_phrase_set( + self, + ) -> Callable[[cloud_speech.UndeletePhraseSetRequest], operations_pb2.Operation]: + r"""Return a callable for the undelete phrase set method over gRPC. + + Undeletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.UndeletePhraseSetRequest], + ~.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 "undelete_phrase_set" not in self._stubs: + self._stubs["undelete_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UndeletePhraseSet", + request_serializer=cloud_speech.UndeletePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["undelete_phrase_set"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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 list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations 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_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations 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_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SpeechGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..8677bbaed7f8f9e039186cbc22c5f3d4bd97f857 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/grpc_asyncio.py @@ -0,0 +1,1279 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.speech_v2.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)!r}" + + 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.v2.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 `` 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)!r}" + 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.v2.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. + + Enables speech transcription and resource management. + + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 create_recognizer( + self, + ) -> Callable[ + [cloud_speech.CreateRecognizerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create recognizer method over gRPC. + + Creates a [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.CreateRecognizerRequest], + 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 "create_recognizer" not in self._stubs: + self._stubs["create_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/CreateRecognizer", + request_serializer=cloud_speech.CreateRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_recognizer"] + + @property + def list_recognizers( + self, + ) -> Callable[ + [cloud_speech.ListRecognizersRequest], + Awaitable[cloud_speech.ListRecognizersResponse], + ]: + r"""Return a callable for the list recognizers method over gRPC. + + Lists Recognizers. + + Returns: + Callable[[~.ListRecognizersRequest], + Awaitable[~.ListRecognizersResponse]]: + 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_recognizers" not in self._stubs: + self._stubs["list_recognizers"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/ListRecognizers", + request_serializer=cloud_speech.ListRecognizersRequest.serialize, + response_deserializer=cloud_speech.ListRecognizersResponse.deserialize, + ) + return self._stubs["list_recognizers"] + + @property + def get_recognizer( + self, + ) -> Callable[ + [cloud_speech.GetRecognizerRequest], Awaitable[cloud_speech.Recognizer] + ]: + r"""Return a callable for the get recognizer method over gRPC. + + Returns the requested + [Recognizer][google.cloud.speech.v2.Recognizer]. Fails with + [NOT_FOUND][google.rpc.Code.NOT_FOUND] if the requested + Recognizer doesn't exist. + + Returns: + Callable[[~.GetRecognizerRequest], + Awaitable[~.Recognizer]]: + 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_recognizer" not in self._stubs: + self._stubs["get_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/GetRecognizer", + request_serializer=cloud_speech.GetRecognizerRequest.serialize, + response_deserializer=cloud_speech.Recognizer.deserialize, + ) + return self._stubs["get_recognizer"] + + @property + def update_recognizer( + self, + ) -> Callable[ + [cloud_speech.UpdateRecognizerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update recognizer method over gRPC. + + Updates the [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.UpdateRecognizerRequest], + 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 "update_recognizer" not in self._stubs: + self._stubs["update_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdateRecognizer", + request_serializer=cloud_speech.UpdateRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_recognizer"] + + @property + def delete_recognizer( + self, + ) -> Callable[ + [cloud_speech.DeleteRecognizerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete recognizer method over gRPC. + + Deletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.DeleteRecognizerRequest], + 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 "delete_recognizer" not in self._stubs: + self._stubs["delete_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/DeleteRecognizer", + request_serializer=cloud_speech.DeleteRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_recognizer"] + + @property + def undelete_recognizer( + self, + ) -> Callable[ + [cloud_speech.UndeleteRecognizerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the undelete recognizer method over gRPC. + + Undeletes the [Recognizer][google.cloud.speech.v2.Recognizer]. + + Returns: + Callable[[~.UndeleteRecognizerRequest], + 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 "undelete_recognizer" not in self._stubs: + self._stubs["undelete_recognizer"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UndeleteRecognizer", + request_serializer=cloud_speech.UndeleteRecognizerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["undelete_recognizer"] + + @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.v2.Speech/Recognize", + request_serializer=cloud_speech.RecognizeRequest.serialize, + response_deserializer=cloud_speech.RecognizeResponse.deserialize, + ) + return self._stubs["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.v2.Speech/StreamingRecognize", + request_serializer=cloud_speech.StreamingRecognizeRequest.serialize, + response_deserializer=cloud_speech.StreamingRecognizeResponse.deserialize, + ) + return self._stubs["streaming_recognize"] + + @property + def batch_recognize( + self, + ) -> Callable[ + [cloud_speech.BatchRecognizeRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the batch recognize method over gRPC. + + Performs batch asynchronous speech recognition: send + a request with N audio files and receive a long running + operation that can be polled to see when the + transcriptions are finished. + + Returns: + Callable[[~.BatchRecognizeRequest], + 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 "batch_recognize" not in self._stubs: + self._stubs["batch_recognize"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/BatchRecognize", + request_serializer=cloud_speech.BatchRecognizeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_recognize"] + + @property + def get_config( + self, + ) -> Callable[[cloud_speech.GetConfigRequest], Awaitable[cloud_speech.Config]]: + r"""Return a callable for the get config method over gRPC. + + Returns the requested [Config][google.cloud.speech.v2.Config]. + + Returns: + Callable[[~.GetConfigRequest], + Awaitable[~.Config]]: + 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_config" not in self._stubs: + self._stubs["get_config"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/GetConfig", + request_serializer=cloud_speech.GetConfigRequest.serialize, + response_deserializer=cloud_speech.Config.deserialize, + ) + return self._stubs["get_config"] + + @property + def update_config( + self, + ) -> Callable[[cloud_speech.UpdateConfigRequest], Awaitable[cloud_speech.Config]]: + r"""Return a callable for the update config method over gRPC. + + Updates the [Config][google.cloud.speech.v2.Config]. + + Returns: + Callable[[~.UpdateConfigRequest], + Awaitable[~.Config]]: + 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_config" not in self._stubs: + self._stubs["update_config"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdateConfig", + request_serializer=cloud_speech.UpdateConfigRequest.serialize, + response_deserializer=cloud_speech.Config.deserialize, + ) + return self._stubs["update_config"] + + @property + def create_custom_class( + self, + ) -> Callable[ + [cloud_speech.CreateCustomClassRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create custom class method over gRPC. + + Creates a [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.CreateCustomClassRequest], + 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 "create_custom_class" not in self._stubs: + self._stubs["create_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/CreateCustomClass", + request_serializer=cloud_speech.CreateCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_custom_class"] + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech.ListCustomClassesRequest], + Awaitable[cloud_speech.ListCustomClassesResponse], + ]: + r"""Return a callable for the list custom classes method over gRPC. + + Lists CustomClasses. + + 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.v2.Speech/ListCustomClasses", + request_serializer=cloud_speech.ListCustomClassesRequest.serialize, + response_deserializer=cloud_speech.ListCustomClassesResponse.deserialize, + ) + return self._stubs["list_custom_classes"] + + @property + def get_custom_class( + self, + ) -> Callable[ + [cloud_speech.GetCustomClassRequest], Awaitable[cloud_speech.CustomClass] + ]: + r"""Return a callable for the get custom class method over gRPC. + + Returns the requested + [CustomClass][google.cloud.speech.v2.CustomClass]. + + 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.v2.Speech/GetCustomClass", + request_serializer=cloud_speech.GetCustomClassRequest.serialize, + response_deserializer=cloud_speech.CustomClass.deserialize, + ) + return self._stubs["get_custom_class"] + + @property + def update_custom_class( + self, + ) -> Callable[ + [cloud_speech.UpdateCustomClassRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update custom class method over gRPC. + + Updates the [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.UpdateCustomClassRequest], + 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 "update_custom_class" not in self._stubs: + self._stubs["update_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdateCustomClass", + request_serializer=cloud_speech.UpdateCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_custom_class"] + + @property + def delete_custom_class( + self, + ) -> Callable[ + [cloud_speech.DeleteCustomClassRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete custom class method over gRPC. + + Deletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.DeleteCustomClassRequest], + 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 "delete_custom_class" not in self._stubs: + self._stubs["delete_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/DeleteCustomClass", + request_serializer=cloud_speech.DeleteCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_custom_class"] + + @property + def undelete_custom_class( + self, + ) -> Callable[ + [cloud_speech.UndeleteCustomClassRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the undelete custom class method over gRPC. + + Undeletes the [CustomClass][google.cloud.speech.v2.CustomClass]. + + Returns: + Callable[[~.UndeleteCustomClassRequest], + 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 "undelete_custom_class" not in self._stubs: + self._stubs["undelete_custom_class"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UndeleteCustomClass", + request_serializer=cloud_speech.UndeleteCustomClassRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["undelete_custom_class"] + + @property + def create_phrase_set( + self, + ) -> Callable[ + [cloud_speech.CreatePhraseSetRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create phrase set method over gRPC. + + Creates a [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.CreatePhraseSetRequest], + 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 "create_phrase_set" not in self._stubs: + self._stubs["create_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/CreatePhraseSet", + request_serializer=cloud_speech.CreatePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_phrase_set"] + + @property + def list_phrase_sets( + self, + ) -> Callable[ + [cloud_speech.ListPhraseSetsRequest], + Awaitable[cloud_speech.ListPhraseSetsResponse], + ]: + r"""Return a callable for the list phrase sets method over gRPC. + + Lists PhraseSets. + + Returns: + Callable[[~.ListPhraseSetsRequest], + Awaitable[~.ListPhraseSetsResponse]]: + 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_sets" not in self._stubs: + self._stubs["list_phrase_sets"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/ListPhraseSets", + request_serializer=cloud_speech.ListPhraseSetsRequest.serialize, + response_deserializer=cloud_speech.ListPhraseSetsResponse.deserialize, + ) + return self._stubs["list_phrase_sets"] + + @property + def get_phrase_set( + self, + ) -> Callable[ + [cloud_speech.GetPhraseSetRequest], Awaitable[cloud_speech.PhraseSet] + ]: + r"""Return a callable for the get phrase set method over gRPC. + + Returns the requested + [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + 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.v2.Speech/GetPhraseSet", + request_serializer=cloud_speech.GetPhraseSetRequest.serialize, + response_deserializer=cloud_speech.PhraseSet.deserialize, + ) + return self._stubs["get_phrase_set"] + + @property + def update_phrase_set( + self, + ) -> Callable[ + [cloud_speech.UpdatePhraseSetRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update phrase set method over gRPC. + + Updates the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.UpdatePhraseSetRequest], + 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 "update_phrase_set" not in self._stubs: + self._stubs["update_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UpdatePhraseSet", + request_serializer=cloud_speech.UpdatePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_phrase_set"] + + @property + def delete_phrase_set( + self, + ) -> Callable[ + [cloud_speech.DeletePhraseSetRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete phrase set method over gRPC. + + Deletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.DeletePhraseSetRequest], + 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 "delete_phrase_set" not in self._stubs: + self._stubs["delete_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/DeletePhraseSet", + request_serializer=cloud_speech.DeletePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_phrase_set"] + + @property + def undelete_phrase_set( + self, + ) -> Callable[ + [cloud_speech.UndeletePhraseSetRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the undelete phrase set method over gRPC. + + Undeletes the [PhraseSet][google.cloud.speech.v2.PhraseSet]. + + Returns: + Callable[[~.UndeletePhraseSetRequest], + 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 "undelete_phrase_set" not in self._stubs: + self._stubs["undelete_phrase_set"] = self._logged_channel.unary_unary( + "/google.cloud.speech.v2.Speech/UndeletePhraseSet", + request_serializer=cloud_speech.UndeletePhraseSetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["undelete_phrase_set"] + + 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_recognizer: self._wrap_method( + self.create_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.list_recognizers: self._wrap_method( + self.list_recognizers, + default_timeout=None, + client_info=client_info, + ), + self.get_recognizer: self._wrap_method( + self.get_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.update_recognizer: self._wrap_method( + self.update_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.delete_recognizer: self._wrap_method( + self.delete_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.undelete_recognizer: self._wrap_method( + self.undelete_recognizer, + default_timeout=None, + client_info=client_info, + ), + self.recognize: self._wrap_method( + self.recognize, + default_timeout=None, + client_info=client_info, + ), + self.streaming_recognize: self._wrap_method( + self.streaming_recognize, + default_timeout=None, + client_info=client_info, + ), + self.batch_recognize: self._wrap_method( + self.batch_recognize, + default_timeout=None, + client_info=client_info, + ), + self.get_config: self._wrap_method( + self.get_config, + default_timeout=None, + client_info=client_info, + ), + self.update_config: self._wrap_method( + self.update_config, + 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.list_custom_classes: self._wrap_method( + self.list_custom_classes, + 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.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.undelete_custom_class: self._wrap_method( + self.undelete_custom_class, + default_timeout=None, + client_info=client_info, + ), + self.create_phrase_set: self._wrap_method( + self.create_phrase_set, + default_timeout=None, + client_info=client_info, + ), + self.list_phrase_sets: self._wrap_method( + self.list_phrase_sets, + 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.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.undelete_phrase_set: self._wrap_method( + self.undelete_phrase_set, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + 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 delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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 list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations 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_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations 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_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("SpeechGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..9137732efb6ce34fded7cfd55389a5f96e769f0c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/rest.py @@ -0,0 +1,6080 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.speech_v2.types import cloud_speech + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSpeechRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SpeechRestInterceptor: + """Interceptor for Speech. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SpeechRestTransport. + + .. code-block:: python + class MyCustomSpeechInterceptor(SpeechRestInterceptor): + def pre_batch_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_classes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_classes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_phrase_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_phrase_sets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_recognizers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_recognizers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SpeechRestTransport(interceptor=MyCustomSpeechInterceptor()) + client = SpeechClient(transport=transport) + + + """ + + def pre_batch_recognize( + self, + request: cloud_speech.BatchRecognizeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.BatchRecognizeRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for batch_recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_batch_recognize( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_recognize + + DEPRECATED. Please use the `post_batch_recognize_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_batch_recognize` interceptor runs + before the `post_batch_recognize_with_metadata` interceptor. + """ + return response + + def post_batch_recognize_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for batch_recognize + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_batch_recognize_with_metadata` + interceptor in new development instead of the `post_batch_recognize` interceptor. + When both interceptors are used, this `post_batch_recognize_with_metadata` interceptor runs after the + `post_batch_recognize` interceptor. The (possibly modified) response returned by + `post_batch_recognize` will be passed to + `post_batch_recognize_with_metadata`. + """ + return response, metadata + + def pre_create_custom_class( + self, + request: cloud_speech.CreateCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.CreateCustomClassRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_create_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_custom_class + + DEPRECATED. Please use the `post_create_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_create_custom_class` interceptor runs + before the `post_create_custom_class_with_metadata` interceptor. + """ + return response + + def post_create_custom_class_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_create_custom_class_with_metadata` + interceptor in new development instead of the `post_create_custom_class` interceptor. + When both interceptors are used, this `post_create_custom_class_with_metadata` interceptor runs after the + `post_create_custom_class` interceptor. The (possibly modified) response returned by + `post_create_custom_class` will be passed to + `post_create_custom_class_with_metadata`. + """ + return response, metadata + + def pre_create_phrase_set( + self, + request: cloud_speech.CreatePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.CreatePhraseSetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_create_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_phrase_set + + DEPRECATED. Please use the `post_create_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_create_phrase_set` interceptor runs + before the `post_create_phrase_set_with_metadata` interceptor. + """ + return response + + def post_create_phrase_set_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_create_phrase_set_with_metadata` + interceptor in new development instead of the `post_create_phrase_set` interceptor. + When both interceptors are used, this `post_create_phrase_set_with_metadata` interceptor runs after the + `post_create_phrase_set` interceptor. The (possibly modified) response returned by + `post_create_phrase_set` will be passed to + `post_create_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_create_recognizer( + self, + request: cloud_speech.CreateRecognizerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.CreateRecognizerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_create_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_recognizer + + DEPRECATED. Please use the `post_create_recognizer_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_create_recognizer` interceptor runs + before the `post_create_recognizer_with_metadata` interceptor. + """ + return response + + def post_create_recognizer_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_recognizer + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_create_recognizer_with_metadata` + interceptor in new development instead of the `post_create_recognizer` interceptor. + When both interceptors are used, this `post_create_recognizer_with_metadata` interceptor runs after the + `post_create_recognizer` interceptor. The (possibly modified) response returned by + `post_create_recognizer` will be passed to + `post_create_recognizer_with_metadata`. + """ + return response, metadata + + def pre_delete_custom_class( + self, + request: cloud_speech.DeleteCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.DeleteCustomClassRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_custom_class + + DEPRECATED. Please use the `post_delete_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_delete_custom_class` interceptor runs + before the `post_delete_custom_class_with_metadata` interceptor. + """ + return response + + def post_delete_custom_class_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_delete_custom_class_with_metadata` + interceptor in new development instead of the `post_delete_custom_class` interceptor. + When both interceptors are used, this `post_delete_custom_class_with_metadata` interceptor runs after the + `post_delete_custom_class` interceptor. The (possibly modified) response returned by + `post_delete_custom_class` will be passed to + `post_delete_custom_class_with_metadata`. + """ + return response, metadata + + def pre_delete_phrase_set( + self, + request: cloud_speech.DeletePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.DeletePhraseSetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_phrase_set + + DEPRECATED. Please use the `post_delete_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_delete_phrase_set` interceptor runs + before the `post_delete_phrase_set_with_metadata` interceptor. + """ + return response + + def post_delete_phrase_set_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_delete_phrase_set_with_metadata` + interceptor in new development instead of the `post_delete_phrase_set` interceptor. + When both interceptors are used, this `post_delete_phrase_set_with_metadata` interceptor runs after the + `post_delete_phrase_set` interceptor. The (possibly modified) response returned by + `post_delete_phrase_set` will be passed to + `post_delete_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_delete_recognizer( + self, + request: cloud_speech.DeleteRecognizerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.DeleteRecognizerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_recognizer + + DEPRECATED. Please use the `post_delete_recognizer_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_delete_recognizer` interceptor runs + before the `post_delete_recognizer_with_metadata` interceptor. + """ + return response + + def post_delete_recognizer_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_recognizer + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_delete_recognizer_with_metadata` + interceptor in new development instead of the `post_delete_recognizer` interceptor. + When both interceptors are used, this `post_delete_recognizer_with_metadata` interceptor runs after the + `post_delete_recognizer` interceptor. The (possibly modified) response returned by + `post_delete_recognizer` will be passed to + `post_delete_recognizer_with_metadata`. + """ + return response, metadata + + def pre_get_config( + self, + request: cloud_speech.GetConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.GetConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_config(self, response: cloud_speech.Config) -> cloud_speech.Config: + """Post-rpc interceptor for get_config + + DEPRECATED. Please use the `post_get_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_get_config` interceptor runs + before the `post_get_config_with_metadata` interceptor. + """ + return response + + def post_get_config_with_metadata( + self, + response: cloud_speech.Config, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.Config, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_get_config_with_metadata` + interceptor in new development instead of the `post_get_config` interceptor. + When both interceptors are used, this `post_get_config_with_metadata` interceptor runs after the + `post_get_config` interceptor. The (possibly modified) response returned by + `post_get_config` will be passed to + `post_get_config_with_metadata`. + """ + return response, metadata + + def pre_get_custom_class( + self, + request: cloud_speech.GetCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.GetCustomClassRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_custom_class( + self, response: cloud_speech.CustomClass + ) -> cloud_speech.CustomClass: + """Post-rpc interceptor for get_custom_class + + DEPRECATED. Please use the `post_get_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_get_custom_class` interceptor runs + before the `post_get_custom_class_with_metadata` interceptor. + """ + return response + + def post_get_custom_class_with_metadata( + self, + response: cloud_speech.CustomClass, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.CustomClass, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_get_custom_class_with_metadata` + interceptor in new development instead of the `post_get_custom_class` interceptor. + When both interceptors are used, this `post_get_custom_class_with_metadata` interceptor runs after the + `post_get_custom_class` interceptor. The (possibly modified) response returned by + `post_get_custom_class` will be passed to + `post_get_custom_class_with_metadata`. + """ + return response, metadata + + def pre_get_phrase_set( + self, + request: cloud_speech.GetPhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.GetPhraseSetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_phrase_set( + self, response: cloud_speech.PhraseSet + ) -> cloud_speech.PhraseSet: + """Post-rpc interceptor for get_phrase_set + + DEPRECATED. Please use the `post_get_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_get_phrase_set` interceptor runs + before the `post_get_phrase_set_with_metadata` interceptor. + """ + return response + + def post_get_phrase_set_with_metadata( + self, + response: cloud_speech.PhraseSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.PhraseSet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_get_phrase_set_with_metadata` + interceptor in new development instead of the `post_get_phrase_set` interceptor. + When both interceptors are used, this `post_get_phrase_set_with_metadata` interceptor runs after the + `post_get_phrase_set` interceptor. The (possibly modified) response returned by + `post_get_phrase_set` will be passed to + `post_get_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_get_recognizer( + self, + request: cloud_speech.GetRecognizerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.GetRecognizerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_recognizer( + self, response: cloud_speech.Recognizer + ) -> cloud_speech.Recognizer: + """Post-rpc interceptor for get_recognizer + + DEPRECATED. Please use the `post_get_recognizer_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_get_recognizer` interceptor runs + before the `post_get_recognizer_with_metadata` interceptor. + """ + return response + + def post_get_recognizer_with_metadata( + self, + response: cloud_speech.Recognizer, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.Recognizer, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_recognizer + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_get_recognizer_with_metadata` + interceptor in new development instead of the `post_get_recognizer` interceptor. + When both interceptors are used, this `post_get_recognizer_with_metadata` interceptor runs after the + `post_get_recognizer` interceptor. The (possibly modified) response returned by + `post_get_recognizer` will be passed to + `post_get_recognizer_with_metadata`. + """ + return response, metadata + + def pre_list_custom_classes( + self, + request: cloud_speech.ListCustomClassesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.ListCustomClassesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_custom_classes( + self, response: cloud_speech.ListCustomClassesResponse + ) -> cloud_speech.ListCustomClassesResponse: + """Post-rpc interceptor for list_custom_classes + + DEPRECATED. Please use the `post_list_custom_classes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_list_custom_classes` interceptor runs + before the `post_list_custom_classes_with_metadata` interceptor. + """ + return response + + def post_list_custom_classes_with_metadata( + self, + response: cloud_speech.ListCustomClassesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.ListCustomClassesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_custom_classes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_list_custom_classes_with_metadata` + interceptor in new development instead of the `post_list_custom_classes` interceptor. + When both interceptors are used, this `post_list_custom_classes_with_metadata` interceptor runs after the + `post_list_custom_classes` interceptor. The (possibly modified) response returned by + `post_list_custom_classes` will be passed to + `post_list_custom_classes_with_metadata`. + """ + return response, metadata + + def pre_list_phrase_sets( + self, + request: cloud_speech.ListPhraseSetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.ListPhraseSetsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_phrase_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_phrase_sets( + self, response: cloud_speech.ListPhraseSetsResponse + ) -> cloud_speech.ListPhraseSetsResponse: + """Post-rpc interceptor for list_phrase_sets + + DEPRECATED. Please use the `post_list_phrase_sets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_list_phrase_sets` interceptor runs + before the `post_list_phrase_sets_with_metadata` interceptor. + """ + return response + + def post_list_phrase_sets_with_metadata( + self, + response: cloud_speech.ListPhraseSetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.ListPhraseSetsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_phrase_sets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_list_phrase_sets_with_metadata` + interceptor in new development instead of the `post_list_phrase_sets` interceptor. + When both interceptors are used, this `post_list_phrase_sets_with_metadata` interceptor runs after the + `post_list_phrase_sets` interceptor. The (possibly modified) response returned by + `post_list_phrase_sets` will be passed to + `post_list_phrase_sets_with_metadata`. + """ + return response, metadata + + def pre_list_recognizers( + self, + request: cloud_speech.ListRecognizersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.ListRecognizersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_recognizers + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_recognizers( + self, response: cloud_speech.ListRecognizersResponse + ) -> cloud_speech.ListRecognizersResponse: + """Post-rpc interceptor for list_recognizers + + DEPRECATED. Please use the `post_list_recognizers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_list_recognizers` interceptor runs + before the `post_list_recognizers_with_metadata` interceptor. + """ + return response + + def post_list_recognizers_with_metadata( + self, + response: cloud_speech.ListRecognizersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.ListRecognizersResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_recognizers + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_list_recognizers_with_metadata` + interceptor in new development instead of the `post_list_recognizers` interceptor. + When both interceptors are used, this `post_list_recognizers_with_metadata` interceptor runs after the + `post_list_recognizers` interceptor. The (possibly modified) response returned by + `post_list_recognizers` will be passed to + `post_list_recognizers_with_metadata`. + """ + return response, metadata + + def pre_recognize( + self, + request: cloud_speech.RecognizeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.RecognizeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_recognize( + self, response: cloud_speech.RecognizeResponse + ) -> cloud_speech.RecognizeResponse: + """Post-rpc interceptor for recognize + + DEPRECATED. Please use the `post_recognize_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_recognize` interceptor runs + before the `post_recognize_with_metadata` interceptor. + """ + return response + + def post_recognize_with_metadata( + self, + response: cloud_speech.RecognizeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.RecognizeResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for recognize + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_recognize_with_metadata` + interceptor in new development instead of the `post_recognize` interceptor. + When both interceptors are used, this `post_recognize_with_metadata` interceptor runs after the + `post_recognize` interceptor. The (possibly modified) response returned by + `post_recognize` will be passed to + `post_recognize_with_metadata`. + """ + return response, metadata + + def pre_undelete_custom_class( + self, + request: cloud_speech.UndeleteCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.UndeleteCustomClassRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for undelete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_undelete_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_custom_class + + DEPRECATED. Please use the `post_undelete_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_undelete_custom_class` interceptor runs + before the `post_undelete_custom_class_with_metadata` interceptor. + """ + return response + + def post_undelete_custom_class_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for undelete_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_undelete_custom_class_with_metadata` + interceptor in new development instead of the `post_undelete_custom_class` interceptor. + When both interceptors are used, this `post_undelete_custom_class_with_metadata` interceptor runs after the + `post_undelete_custom_class` interceptor. The (possibly modified) response returned by + `post_undelete_custom_class` will be passed to + `post_undelete_custom_class_with_metadata`. + """ + return response, metadata + + def pre_undelete_phrase_set( + self, + request: cloud_speech.UndeletePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.UndeletePhraseSetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for undelete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_undelete_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_phrase_set + + DEPRECATED. Please use the `post_undelete_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_undelete_phrase_set` interceptor runs + before the `post_undelete_phrase_set_with_metadata` interceptor. + """ + return response + + def post_undelete_phrase_set_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for undelete_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_undelete_phrase_set_with_metadata` + interceptor in new development instead of the `post_undelete_phrase_set` interceptor. + When both interceptors are used, this `post_undelete_phrase_set_with_metadata` interceptor runs after the + `post_undelete_phrase_set` interceptor. The (possibly modified) response returned by + `post_undelete_phrase_set` will be passed to + `post_undelete_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_undelete_recognizer( + self, + request: cloud_speech.UndeleteRecognizerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.UndeleteRecognizerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for undelete_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_undelete_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_recognizer + + DEPRECATED. Please use the `post_undelete_recognizer_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_undelete_recognizer` interceptor runs + before the `post_undelete_recognizer_with_metadata` interceptor. + """ + return response + + def post_undelete_recognizer_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for undelete_recognizer + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_undelete_recognizer_with_metadata` + interceptor in new development instead of the `post_undelete_recognizer` interceptor. + When both interceptors are used, this `post_undelete_recognizer_with_metadata` interceptor runs after the + `post_undelete_recognizer` interceptor. The (possibly modified) response returned by + `post_undelete_recognizer` will be passed to + `post_undelete_recognizer_with_metadata`. + """ + return response, metadata + + def pre_update_config( + self, + request: cloud_speech.UpdateConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.UpdateConfigRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_config(self, response: cloud_speech.Config) -> cloud_speech.Config: + """Post-rpc interceptor for update_config + + DEPRECATED. Please use the `post_update_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_update_config` interceptor runs + before the `post_update_config_with_metadata` interceptor. + """ + return response + + def post_update_config_with_metadata( + self, + response: cloud_speech.Config, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_speech.Config, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_update_config_with_metadata` + interceptor in new development instead of the `post_update_config` interceptor. + When both interceptors are used, this `post_update_config_with_metadata` interceptor runs after the + `post_update_config` interceptor. The (possibly modified) response returned by + `post_update_config` will be passed to + `post_update_config_with_metadata`. + """ + return response, metadata + + def pre_update_custom_class( + self, + request: cloud_speech.UpdateCustomClassRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.UpdateCustomClassRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_custom_class + + DEPRECATED. Please use the `post_update_custom_class_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_update_custom_class` interceptor runs + before the `post_update_custom_class_with_metadata` interceptor. + """ + return response + + def post_update_custom_class_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_custom_class + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_update_custom_class_with_metadata` + interceptor in new development instead of the `post_update_custom_class` interceptor. + When both interceptors are used, this `post_update_custom_class_with_metadata` interceptor runs after the + `post_update_custom_class` interceptor. The (possibly modified) response returned by + `post_update_custom_class` will be passed to + `post_update_custom_class_with_metadata`. + """ + return response, metadata + + def pre_update_phrase_set( + self, + request: cloud_speech.UpdatePhraseSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.UpdatePhraseSetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_phrase_set + + DEPRECATED. Please use the `post_update_phrase_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_update_phrase_set` interceptor runs + before the `post_update_phrase_set_with_metadata` interceptor. + """ + return response + + def post_update_phrase_set_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_phrase_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_update_phrase_set_with_metadata` + interceptor in new development instead of the `post_update_phrase_set` interceptor. + When both interceptors are used, this `post_update_phrase_set_with_metadata` interceptor runs after the + `post_update_phrase_set` interceptor. The (possibly modified) response returned by + `post_update_phrase_set` will be passed to + `post_update_phrase_set_with_metadata`. + """ + return response, metadata + + def pre_update_recognizer( + self, + request: cloud_speech.UpdateRecognizerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_speech.UpdateRecognizerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_recognizer + + DEPRECATED. Please use the `post_update_recognizer_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Speech server but before + it is returned to user code. This `post_update_recognizer` interceptor runs + before the `post_update_recognizer_with_metadata` interceptor. + """ + return response + + def post_update_recognizer_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_recognizer + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Speech server but before it is returned to user code. + + We recommend only using this `post_update_recognizer_with_metadata` + interceptor in new development instead of the `post_update_recognizer` interceptor. + When both interceptors are used, this `post_update_recognizer_with_metadata` interceptor runs after the + `post_update_recognizer` interceptor. The (possibly modified) response returned by + `post_update_recognizer` will be passed to + `post_update_recognizer_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SpeechRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SpeechRestInterceptor + + +class SpeechRestTransport(_BaseSpeechRestTransport): + """REST backend synchronous transport for Speech. + + Enables speech transcription and resource management. + + 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[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SpeechRestInterceptor] = None, + 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. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[SpeechRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SpeechRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchRecognize(_BaseSpeechRestTransport._BaseBatchRecognize, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.BatchRecognize") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.BatchRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch recognize method over HTTP. + + Args: + request (~.cloud_speech.BatchRecognizeRequest): + The request object. Request message for the + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseBatchRecognize._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_recognize(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseBatchRecognize._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseBatchRecognize._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseBatchRecognize._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.BatchRecognize", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "BatchRecognize", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._BatchRecognize._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_recognize(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_recognize_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.batch_recognize", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "BatchRecognize", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateCustomClass( + _BaseSpeechRestTransport._BaseCreateCustomClass, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.CreateCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.CreateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create custom class method over HTTP. + + Args: + request (~.cloud_speech.CreateCustomClassRequest): + The request object. Request message for the + [CreateCustomClass][google.cloud.speech.v2.Speech.CreateCustomClass] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseCreateCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_custom_class( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseCreateCustomClass._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSpeechRestTransport._BaseCreateCustomClass._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseCreateCustomClass._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.CreateCustomClass", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "CreateCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._CreateCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.create_custom_class", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "CreateCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreatePhraseSet( + _BaseSpeechRestTransport._BaseCreatePhraseSet, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.CreatePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.CreatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create phrase set method over HTTP. + + Args: + request (~.cloud_speech.CreatePhraseSetRequest): + The request object. Request message for the + [CreatePhraseSet][google.cloud.speech.v2.Speech.CreatePhraseSet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseCreatePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_phrase_set( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseCreatePhraseSet._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseCreatePhraseSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseCreatePhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.CreatePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "CreatePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._CreatePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.create_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "CreatePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateRecognizer( + _BaseSpeechRestTransport._BaseCreateRecognizer, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.CreateRecognizer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.CreateRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create recognizer method over HTTP. + + Args: + request (~.cloud_speech.CreateRecognizerRequest): + The request object. Request message for the + [CreateRecognizer][google.cloud.speech.v2.Speech.CreateRecognizer] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseCreateRecognizer._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_recognizer( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseCreateRecognizer._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSpeechRestTransport._BaseCreateRecognizer._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseCreateRecognizer._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.CreateRecognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "CreateRecognizer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._CreateRecognizer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_recognizer(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_recognizer_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.create_recognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "CreateRecognizer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteCustomClass( + _BaseSpeechRestTransport._BaseDeleteCustomClass, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.DeleteCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.DeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete custom class method over HTTP. + + Args: + request (~.cloud_speech.DeleteCustomClassRequest): + The request object. Request message for the + [DeleteCustomClass][google.cloud.speech.v2.Speech.DeleteCustomClass] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseDeleteCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_custom_class( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseDeleteCustomClass._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseDeleteCustomClass._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.DeleteCustomClass", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "DeleteCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._DeleteCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.delete_custom_class", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "DeleteCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePhraseSet( + _BaseSpeechRestTransport._BaseDeletePhraseSet, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.DeletePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.DeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete phrase set method over HTTP. + + Args: + request (~.cloud_speech.DeletePhraseSetRequest): + The request object. Request message for the + [DeletePhraseSet][google.cloud.speech.v2.Speech.DeletePhraseSet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseDeletePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_phrase_set( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseDeletePhraseSet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseDeletePhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.DeletePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "DeletePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._DeletePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.delete_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "DeletePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteRecognizer( + _BaseSpeechRestTransport._BaseDeleteRecognizer, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.DeleteRecognizer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.DeleteRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete recognizer method over HTTP. + + Args: + request (~.cloud_speech.DeleteRecognizerRequest): + The request object. Request message for the + [DeleteRecognizer][google.cloud.speech.v2.Speech.DeleteRecognizer] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseDeleteRecognizer._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_recognizer( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseDeleteRecognizer._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseDeleteRecognizer._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.DeleteRecognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "DeleteRecognizer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._DeleteRecognizer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_recognizer(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_recognizer_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.delete_recognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "DeleteRecognizer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetConfig(_BaseSpeechRestTransport._BaseGetConfig, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.GetConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Config: + r"""Call the get config method over HTTP. + + Args: + request (~.cloud_speech.GetConfigRequest): + The request object. Request message for the + [GetConfig][google.cloud.speech.v2.Speech.GetConfig] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.Config: + Message representing the config for the Speech-to-Text + API. This includes an optional `KMS + key `__ + with which incoming data will be encrypted. + + """ + + http_options = _BaseSpeechRestTransport._BaseGetConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_config(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetConfig._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetConfig._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.GetConfig", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.Config() + pb_resp = cloud_speech.Config.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.Config.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.get_config", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetCustomClass(_BaseSpeechRestTransport._BaseGetCustomClass, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.GetCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.CustomClass: + r"""Call the get custom class method over HTTP. + + Args: + request (~.cloud_speech.GetCustomClassRequest): + The request object. Request message for the + [GetCustomClass][google.cloud.speech.v2.Speech.GetCustomClass] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.CustomClass: + CustomClass for biasing in speech + recognition. Used to define a set of + words or phrases that represents a + common concept or theme likely to appear + in your audio, for example a list of + passenger ship names. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseGetCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_custom_class( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetCustomClass._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetCustomClass._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.GetCustomClass", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.CustomClass() + pb_resp = cloud_speech.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.CustomClass.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.get_custom_class", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPhraseSet(_BaseSpeechRestTransport._BaseGetPhraseSet, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetPhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.GetPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.PhraseSet: + r"""Call the get phrase set method over HTTP. + + Args: + request (~.cloud_speech.GetPhraseSetRequest): + The request object. Request message for the + [GetPhraseSet][google.cloud.speech.v2.Speech.GetPhraseSet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.PhraseSet: + PhraseSet for biasing in speech + recognition. A PhraseSet is used to + provide "hints" to the speech recognizer + to favor specific words and phrases in + the results. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseGetPhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_phrase_set(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetPhraseSet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetPhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.GetPhraseSet", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetPhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetPhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.PhraseSet() + pb_resp = cloud_speech.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.PhraseSet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.get_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetPhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRecognizer(_BaseSpeechRestTransport._BaseGetRecognizer, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetRecognizer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.GetRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Recognizer: + r"""Call the get recognizer method over HTTP. + + Args: + request (~.cloud_speech.GetRecognizerRequest): + The request object. Request message for the + [GetRecognizer][google.cloud.speech.v2.Speech.GetRecognizer] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.Recognizer: + A Recognizer message. Stores + recognition configuration and metadata. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseGetRecognizer._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_recognizer(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetRecognizer._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetRecognizer._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.GetRecognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetRecognizer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetRecognizer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.Recognizer() + pb_resp = cloud_speech.Recognizer.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_recognizer(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_recognizer_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.Recognizer.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.get_recognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetRecognizer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListCustomClasses( + _BaseSpeechRestTransport._BaseListCustomClasses, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.ListCustomClasses") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.ListCustomClassesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.ListCustomClassesResponse: + r"""Call the list custom classes method over HTTP. + + Args: + request (~.cloud_speech.ListCustomClassesRequest): + The request object. Request message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.ListCustomClassesResponse: + Response message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseListCustomClasses._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_custom_classes( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseListCustomClasses._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseListCustomClasses._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.ListCustomClasses", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListCustomClasses", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._ListCustomClasses._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.ListCustomClassesResponse() + pb_resp = cloud_speech.ListCustomClassesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_custom_classes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_custom_classes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.ListCustomClassesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.list_custom_classes", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListCustomClasses", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPhraseSets(_BaseSpeechRestTransport._BaseListPhraseSets, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.ListPhraseSets") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.ListPhraseSetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.ListPhraseSetsResponse: + r"""Call the list phrase sets method over HTTP. + + Args: + request (~.cloud_speech.ListPhraseSetsRequest): + The request object. Request message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.ListPhraseSetsResponse: + Response message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseListPhraseSets._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_phrase_sets( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseListPhraseSets._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseListPhraseSets._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.ListPhraseSets", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListPhraseSets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._ListPhraseSets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.ListPhraseSetsResponse() + pb_resp = cloud_speech.ListPhraseSetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_phrase_sets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_phrase_sets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.ListPhraseSetsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.list_phrase_sets", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListPhraseSets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRecognizers( + _BaseSpeechRestTransport._BaseListRecognizers, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.ListRecognizers") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cloud_speech.ListRecognizersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.ListRecognizersResponse: + r"""Call the list recognizers method over HTTP. + + Args: + request (~.cloud_speech.ListRecognizersRequest): + The request object. Request message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.ListRecognizersResponse: + Response message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseListRecognizers._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_recognizers( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseListRecognizers._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseListRecognizers._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.ListRecognizers", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListRecognizers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._ListRecognizers._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.ListRecognizersResponse() + pb_resp = cloud_speech.ListRecognizersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_recognizers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_recognizers_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.ListRecognizersResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.list_recognizers", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListRecognizers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Recognize(_BaseSpeechRestTransport._BaseRecognize, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.Recognize") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.RecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.RecognizeResponse: + r"""Call the recognize method over HTTP. + + Args: + request (~.cloud_speech.RecognizeRequest): + The request object. Request message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. Either ``content`` or ``uri`` must be supplied. + Supplying both or neither returns + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + See `content + limits `__. + 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`. + + Returns: + ~.cloud_speech.RecognizeResponse: + Response message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. + + """ + + http_options = _BaseSpeechRestTransport._BaseRecognize._get_http_options() + + request, metadata = self._interceptor.pre_recognize(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseRecognize._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseRecognize._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseRecognize._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.Recognize", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "Recognize", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._Recognize._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.RecognizeResponse() + pb_resp = cloud_speech.RecognizeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_recognize(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_recognize_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.RecognizeResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.recognize", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "Recognize", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StreamingRecognize( + _BaseSpeechRestTransport._BaseStreamingRecognize, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.StreamingRecognize") + + def __call__( + self, + request: cloud_speech.StreamingRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamingRecognize is not available over REST transport" + ) + + class _UndeleteCustomClass( + _BaseSpeechRestTransport._BaseUndeleteCustomClass, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.UndeleteCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.UndeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the undelete custom class method over HTTP. + + Args: + request (~.cloud_speech.UndeleteCustomClassRequest): + The request object. Request message for the + [UndeleteCustomClass][google.cloud.speech.v2.Speech.UndeleteCustomClass] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseUndeleteCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_undelete_custom_class( + request, metadata + ) + transcoded_request = _BaseSpeechRestTransport._BaseUndeleteCustomClass._get_transcoded_request( + http_options, request + ) + + body = _BaseSpeechRestTransport._BaseUndeleteCustomClass._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSpeechRestTransport._BaseUndeleteCustomClass._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.UndeleteCustomClass", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UndeleteCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._UndeleteCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_undelete_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_undelete_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.undelete_custom_class", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UndeleteCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UndeletePhraseSet( + _BaseSpeechRestTransport._BaseUndeletePhraseSet, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.UndeletePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.UndeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the undelete phrase set method over HTTP. + + Args: + request (~.cloud_speech.UndeletePhraseSetRequest): + The request object. Request message for the + [UndeletePhraseSet][google.cloud.speech.v2.Speech.UndeletePhraseSet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseUndeletePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_undelete_phrase_set( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseUndeletePhraseSet._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSpeechRestTransport._BaseUndeletePhraseSet._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseUndeletePhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.UndeletePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UndeletePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._UndeletePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_undelete_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_undelete_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.undelete_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UndeletePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UndeleteRecognizer( + _BaseSpeechRestTransport._BaseUndeleteRecognizer, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.UndeleteRecognizer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.UndeleteRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the undelete recognizer method over HTTP. + + Args: + request (~.cloud_speech.UndeleteRecognizerRequest): + The request object. Request message for the + [UndeleteRecognizer][google.cloud.speech.v2.Speech.UndeleteRecognizer] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseUndeleteRecognizer._get_http_options() + ) + + request, metadata = self._interceptor.pre_undelete_recognizer( + request, metadata + ) + transcoded_request = _BaseSpeechRestTransport._BaseUndeleteRecognizer._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseSpeechRestTransport._BaseUndeleteRecognizer._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseUndeleteRecognizer._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.UndeleteRecognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UndeleteRecognizer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._UndeleteRecognizer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_undelete_recognizer(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_undelete_recognizer_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.undelete_recognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UndeleteRecognizer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateConfig(_BaseSpeechRestTransport._BaseUpdateConfig, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.UpdateConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.UpdateConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_speech.Config: + r"""Call the update config method over HTTP. + + Args: + request (~.cloud_speech.UpdateConfigRequest): + The request object. Request message for the + [UpdateConfig][google.cloud.speech.v2.Speech.UpdateConfig] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.cloud_speech.Config: + Message representing the config for the Speech-to-Text + API. This includes an optional `KMS + key `__ + with which incoming data will be encrypted. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseUpdateConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_config(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseUpdateConfig._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseUpdateConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseUpdateConfig._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.UpdateConfig", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdateConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._UpdateConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_speech.Config() + pb_resp = cloud_speech.Config.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cloud_speech.Config.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.update_config", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdateConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCustomClass( + _BaseSpeechRestTransport._BaseUpdateCustomClass, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.UpdateCustomClass") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.UpdateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update custom class method over HTTP. + + Args: + request (~.cloud_speech.UpdateCustomClassRequest): + The request object. Request message for the + [UpdateCustomClass][google.cloud.speech.v2.Speech.UpdateCustomClass] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseUpdateCustomClass._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_custom_class( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseUpdateCustomClass._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSpeechRestTransport._BaseUpdateCustomClass._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseUpdateCustomClass._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.UpdateCustomClass", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdateCustomClass", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._UpdateCustomClass._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_custom_class(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_custom_class_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.update_custom_class", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdateCustomClass", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePhraseSet( + _BaseSpeechRestTransport._BaseUpdatePhraseSet, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.UpdatePhraseSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.UpdatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update phrase set method over HTTP. + + Args: + request (~.cloud_speech.UpdatePhraseSetRequest): + The request object. Request message for the + [UpdatePhraseSet][google.cloud.speech.v2.Speech.UpdatePhraseSet] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseUpdatePhraseSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_phrase_set( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseUpdatePhraseSet._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseUpdatePhraseSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseUpdatePhraseSet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.UpdatePhraseSet", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdatePhraseSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._UpdatePhraseSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_phrase_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_phrase_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.update_phrase_set", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdatePhraseSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateRecognizer( + _BaseSpeechRestTransport._BaseUpdateRecognizer, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.UpdateRecognizer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cloud_speech.UpdateRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update recognizer method over HTTP. + + Args: + request (~.cloud_speech.UpdateRecognizerRequest): + The request object. Request message for the + [UpdateRecognizer][google.cloud.speech.v2.Speech.UpdateRecognizer] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSpeechRestTransport._BaseUpdateRecognizer._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_recognizer( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseUpdateRecognizer._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSpeechRestTransport._BaseUpdateRecognizer._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseUpdateRecognizer._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.UpdateRecognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdateRecognizer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._UpdateRecognizer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_recognizer(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_recognizer_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechClient.update_recognizer", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "UpdateRecognizer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_recognize( + self, + ) -> Callable[[cloud_speech.BatchRecognizeRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_custom_class( + self, + ) -> Callable[[cloud_speech.CreateCustomClassRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_phrase_set( + self, + ) -> Callable[[cloud_speech.CreatePhraseSetRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_recognizer( + self, + ) -> Callable[[cloud_speech.CreateRecognizerRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_custom_class( + self, + ) -> Callable[[cloud_speech.DeleteCustomClassRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_phrase_set( + self, + ) -> Callable[[cloud_speech.DeletePhraseSetRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_recognizer( + self, + ) -> Callable[[cloud_speech.DeleteRecognizerRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_config( + self, + ) -> Callable[[cloud_speech.GetConfigRequest], cloud_speech.Config]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_class( + self, + ) -> Callable[[cloud_speech.GetCustomClassRequest], cloud_speech.CustomClass]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_phrase_set( + self, + ) -> Callable[[cloud_speech.GetPhraseSetRequest], cloud_speech.PhraseSet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_recognizer( + self, + ) -> Callable[[cloud_speech.GetRecognizerRequest], cloud_speech.Recognizer]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech.ListCustomClassesRequest], cloud_speech.ListCustomClassesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCustomClasses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_phrase_sets( + self, + ) -> Callable[ + [cloud_speech.ListPhraseSetsRequest], cloud_speech.ListPhraseSetsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPhraseSets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_recognizers( + self, + ) -> Callable[ + [cloud_speech.ListRecognizersRequest], cloud_speech.ListRecognizersResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListRecognizers(self._session, self._host, self._interceptor) # type: ignore + + @property + def recognize( + self, + ) -> Callable[[cloud_speech.RecognizeRequest], cloud_speech.RecognizeResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Recognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def streaming_recognize( + self, + ) -> Callable[ + [cloud_speech.StreamingRecognizeRequest], + cloud_speech.StreamingRecognizeResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StreamingRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_custom_class( + self, + ) -> Callable[[cloud_speech.UndeleteCustomClassRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_phrase_set( + self, + ) -> Callable[[cloud_speech.UndeletePhraseSetRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_recognizer( + self, + ) -> Callable[[cloud_speech.UndeleteRecognizerRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeleteRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_config( + self, + ) -> Callable[[cloud_speech.UpdateConfigRequest], cloud_speech.Config]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_class( + self, + ) -> Callable[[cloud_speech.UpdateCustomClassRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_phrase_set( + self, + ) -> Callable[[cloud_speech.UpdatePhraseSetRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_recognizer( + self, + ) -> Callable[[cloud_speech.UpdateRecognizerRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseSpeechRestTransport._BaseGetLocation, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseSpeechRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.GetLocation", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseSpeechRestTransport._BaseListLocations, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.ListLocations", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseSpeechRestTransport._BaseCancelOperation, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSpeechRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.CancelOperation", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseSpeechRestTransport._BaseDeleteOperation, SpeechRestStub + ): + def __hash__(self): + return hash("SpeechRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseDeleteOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = ( + _BaseSpeechRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseSpeechRestTransport._BaseGetOperation, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: Response from GetOperation method. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseSpeechRestTransport._BaseListOperations, SpeechRestStub): + def __hash__(self): + return hash("SpeechRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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 from ListOperations method. + """ + + http_options = ( + _BaseSpeechRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseSpeechRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSpeechRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.speech_v2.SpeechClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpeechRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.speech_v2.SpeechAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.speech.v2.Speech", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SpeechRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7973d32101617093fd46f67e736e063422ffdb6f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/services/speech/transports/rest_base.py @@ -0,0 +1,1407 @@ +# -*- 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.speech_v2.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("^(?Phttp(?:s)?://)?(?P.*)$", 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 _BaseBatchRecognize: + 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": "/v2/{recognizer=projects/*/locations/*/recognizers/*}:batchRecognize", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.BatchRecognizeRequest.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._BaseBatchRecognize._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + 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": "/v2/{parent=projects/*/locations/*}/customClasses", + "body": "custom_class", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._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": "/v2/{parent=projects/*/locations/*}/phraseSets", + "body": "phrase_set", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._BaseCreatePhraseSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateRecognizer: + 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": "/v2/{parent=projects/*/locations/*}/recognizers", + "body": "recognizer", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.CreateRecognizerRequest.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._BaseCreateRecognizer._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": "/v2/{name=projects/*/locations/*/customClasses/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._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": "/v2/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._BaseDeletePhraseSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteRecognizer: + 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": "/v2/{name=projects/*/locations/*/recognizers/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.DeleteRecognizerRequest.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( + _BaseSpeechRestTransport._BaseDeleteRecognizer._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetConfig: + 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": "/v2/{name=projects/*/locations/*/config}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.GetConfigRequest.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( + _BaseSpeechRestTransport._BaseGetConfig._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": "/v2/{name=projects/*/locations/*/customClasses/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._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": "/v2/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._BaseGetPhraseSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRecognizer: + 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": "/v2/{name=projects/*/locations/*/recognizers/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.GetRecognizerRequest.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( + _BaseSpeechRestTransport._BaseGetRecognizer._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": "/v2/{parent=projects/*/locations/*}/customClasses", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._BaseListCustomClasses._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPhraseSets: + 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": "/v2/{parent=projects/*/locations/*}/phraseSets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.ListPhraseSetsRequest.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( + _BaseSpeechRestTransport._BaseListPhraseSets._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRecognizers: + 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": "/v2/{parent=projects/*/locations/*}/recognizers", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.ListRecognizersRequest.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( + _BaseSpeechRestTransport._BaseListRecognizers._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": "/v2/{recognizer=projects/*/locations/*/recognizers/*}: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 _BaseUndeleteCustomClass: + 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": "/v2/{name=projects/*/locations/*/customClasses/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.UndeleteCustomClassRequest.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._BaseUndeleteCustomClass._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeletePhraseSet: + 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": "/v2/{name=projects/*/locations/*/phraseSets/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.UndeletePhraseSetRequest.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._BaseUndeletePhraseSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeleteRecognizer: + 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": "/v2/{name=projects/*/locations/*/recognizers/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.UndeleteRecognizerRequest.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._BaseUndeleteRecognizer._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateConfig: + 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": "/v2/{config.name=projects/*/locations/*/config}", + "body": "config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.UpdateConfigRequest.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._BaseUpdateConfig._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": "/v2/{custom_class.name=projects/*/locations/*/customClasses/*}", + "body": "custom_class", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._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": "/v2/{phrase_set.name=projects/*/locations/*/phraseSets/*}", + "body": "phrase_set", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.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( + _BaseSpeechRestTransport._BaseUpdatePhraseSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateRecognizer: + 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": "/v2/{recognizer.name=projects/*/locations/*/recognizers/*}", + "body": "recognizer", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_speech.UpdateRecognizerRequest.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._BaseUpdateRecognizer._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + 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": "/v2/{name=projects/*/locations/*}", + }, + ] + 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 _BaseListLocations: + 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": "/v2/{name=projects/*}/locations", + }, + ] + 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 _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + 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_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/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 + + 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": "/v2/{name=projects/*/locations/*/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 + + 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": "/v2/{name=projects/*/locations/*}/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",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0974b24d9f13e51abf7245e801f9db54cbcd5d78 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/__init__.py @@ -0,0 +1,164 @@ +# -*- 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 ( + AutoDetectDecodingConfig, + BatchRecognizeFileMetadata, + BatchRecognizeFileResult, + BatchRecognizeMetadata, + BatchRecognizeRequest, + BatchRecognizeResponse, + BatchRecognizeResults, + BatchRecognizeTranscriptionMetadata, + CloudStorageResult, + Config, + CreateCustomClassRequest, + CreatePhraseSetRequest, + CreateRecognizerRequest, + CustomClass, + CustomPromptConfig, + DeleteCustomClassRequest, + DeletePhraseSetRequest, + DeleteRecognizerRequest, + DenoiserConfig, + ExplicitDecodingConfig, + GcsOutputConfig, + GetConfigRequest, + GetCustomClassRequest, + GetPhraseSetRequest, + GetRecognizerRequest, + InlineOutputConfig, + InlineResult, + ListCustomClassesRequest, + ListCustomClassesResponse, + ListPhraseSetsRequest, + ListPhraseSetsResponse, + ListRecognizersRequest, + ListRecognizersResponse, + NativeOutputFileFormatConfig, + OperationMetadata, + OutputFormatConfig, + PhraseSet, + RecognitionConfig, + RecognitionFeatures, + RecognitionOutputConfig, + RecognitionResponseMetadata, + Recognizer, + RecognizeRequest, + RecognizeResponse, + SpeakerDiarizationConfig, + SpeechAdaptation, + SpeechRecognitionAlternative, + SpeechRecognitionResult, + SrtOutputFileFormatConfig, + StreamingRecognitionConfig, + StreamingRecognitionFeatures, + StreamingRecognitionResult, + StreamingRecognizeRequest, + StreamingRecognizeResponse, + TranscriptNormalization, + TranslationConfig, + UndeleteCustomClassRequest, + UndeletePhraseSetRequest, + UndeleteRecognizerRequest, + UpdateConfigRequest, + UpdateCustomClassRequest, + UpdatePhraseSetRequest, + UpdateRecognizerRequest, + VttOutputFileFormatConfig, + WordInfo, +) +from .locations_metadata import ( + AccessMetadata, + LanguageMetadata, + LocationsMetadata, + ModelFeature, + ModelFeatures, + ModelMetadata, +) + +__all__ = ( + "AutoDetectDecodingConfig", + "BatchRecognizeFileMetadata", + "BatchRecognizeFileResult", + "BatchRecognizeMetadata", + "BatchRecognizeRequest", + "BatchRecognizeResponse", + "BatchRecognizeResults", + "BatchRecognizeTranscriptionMetadata", + "CloudStorageResult", + "Config", + "CreateCustomClassRequest", + "CreatePhraseSetRequest", + "CreateRecognizerRequest", + "CustomClass", + "CustomPromptConfig", + "DeleteCustomClassRequest", + "DeletePhraseSetRequest", + "DeleteRecognizerRequest", + "DenoiserConfig", + "ExplicitDecodingConfig", + "GcsOutputConfig", + "GetConfigRequest", + "GetCustomClassRequest", + "GetPhraseSetRequest", + "GetRecognizerRequest", + "InlineOutputConfig", + "InlineResult", + "ListCustomClassesRequest", + "ListCustomClassesResponse", + "ListPhraseSetsRequest", + "ListPhraseSetsResponse", + "ListRecognizersRequest", + "ListRecognizersResponse", + "NativeOutputFileFormatConfig", + "OperationMetadata", + "OutputFormatConfig", + "PhraseSet", + "RecognitionConfig", + "RecognitionFeatures", + "RecognitionOutputConfig", + "RecognitionResponseMetadata", + "Recognizer", + "RecognizeRequest", + "RecognizeResponse", + "SpeakerDiarizationConfig", + "SpeechAdaptation", + "SpeechRecognitionAlternative", + "SpeechRecognitionResult", + "SrtOutputFileFormatConfig", + "StreamingRecognitionConfig", + "StreamingRecognitionFeatures", + "StreamingRecognitionResult", + "StreamingRecognizeRequest", + "StreamingRecognizeResponse", + "TranscriptNormalization", + "TranslationConfig", + "UndeleteCustomClassRequest", + "UndeletePhraseSetRequest", + "UndeleteRecognizerRequest", + "UpdateConfigRequest", + "UpdateCustomClassRequest", + "UpdatePhraseSetRequest", + "UpdateRecognizerRequest", + "VttOutputFileFormatConfig", + "WordInfo", + "AccessMetadata", + "LanguageMetadata", + "LocationsMetadata", + "ModelFeature", + "ModelFeatures", + "ModelMetadata", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/cloud_speech.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/cloud_speech.py new file mode 100644 index 0000000000000000000000000000000000000000..62c25f29b526205fc695ba188b599e8e6e072ae3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/cloud_speech.py @@ -0,0 +1,3510 @@ +# -*- 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 + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.speech.v2", + manifest={ + "CreateRecognizerRequest", + "OperationMetadata", + "ListRecognizersRequest", + "ListRecognizersResponse", + "GetRecognizerRequest", + "UpdateRecognizerRequest", + "DeleteRecognizerRequest", + "UndeleteRecognizerRequest", + "Recognizer", + "AutoDetectDecodingConfig", + "ExplicitDecodingConfig", + "SpeakerDiarizationConfig", + "CustomPromptConfig", + "RecognitionFeatures", + "TranscriptNormalization", + "TranslationConfig", + "SpeechAdaptation", + "DenoiserConfig", + "RecognitionConfig", + "RecognizeRequest", + "RecognitionResponseMetadata", + "SpeechRecognitionAlternative", + "WordInfo", + "SpeechRecognitionResult", + "RecognizeResponse", + "StreamingRecognitionFeatures", + "StreamingRecognitionConfig", + "StreamingRecognizeRequest", + "BatchRecognizeRequest", + "GcsOutputConfig", + "InlineOutputConfig", + "NativeOutputFileFormatConfig", + "VttOutputFileFormatConfig", + "SrtOutputFileFormatConfig", + "OutputFormatConfig", + "RecognitionOutputConfig", + "BatchRecognizeResponse", + "BatchRecognizeResults", + "CloudStorageResult", + "InlineResult", + "BatchRecognizeFileResult", + "BatchRecognizeTranscriptionMetadata", + "BatchRecognizeMetadata", + "BatchRecognizeFileMetadata", + "StreamingRecognitionResult", + "StreamingRecognizeResponse", + "Config", + "GetConfigRequest", + "UpdateConfigRequest", + "CustomClass", + "PhraseSet", + "CreateCustomClassRequest", + "ListCustomClassesRequest", + "ListCustomClassesResponse", + "GetCustomClassRequest", + "UpdateCustomClassRequest", + "DeleteCustomClassRequest", + "UndeleteCustomClassRequest", + "CreatePhraseSetRequest", + "ListPhraseSetsRequest", + "ListPhraseSetsResponse", + "GetPhraseSetRequest", + "UpdatePhraseSetRequest", + "DeletePhraseSetRequest", + "UndeletePhraseSetRequest", + }, +) + + +class CreateRecognizerRequest(proto.Message): + r"""Request message for the + [CreateRecognizer][google.cloud.speech.v2.Speech.CreateRecognizer] + method. + + Attributes: + recognizer (google.cloud.speech_v2.types.Recognizer): + Required. The Recognizer to create. + validate_only (bool): + If set, validate the request and preview the + Recognizer, but do not actually create it. + recognizer_id (str): + The ID to use for the Recognizer, which will become the + final component of the Recognizer's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + parent (str): + Required. The project and location where this Recognizer + will be created. The expected format is + ``projects/{project}/locations/{location}``. + """ + + recognizer: "Recognizer" = proto.Field( + proto.MESSAGE, + number=1, + message="Recognizer", + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + recognizer_id: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of a long-running operation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation was last updated. + resource (str): + The resource path for the target of the + operation. + method (str): + The method that triggered the operation. + kms_key_name (str): + The `KMS key + name `__ + with which the content of the Operation is encrypted. The + expected format is + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + kms_key_version_name (str): + The `KMS key version + name `__ + with which content of the Operation is encrypted. The + expected format is + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}``. + batch_recognize_request (google.cloud.speech_v2.types.BatchRecognizeRequest): + The BatchRecognizeRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + create_recognizer_request (google.cloud.speech_v2.types.CreateRecognizerRequest): + The CreateRecognizerRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + update_recognizer_request (google.cloud.speech_v2.types.UpdateRecognizerRequest): + The UpdateRecognizerRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + delete_recognizer_request (google.cloud.speech_v2.types.DeleteRecognizerRequest): + The DeleteRecognizerRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + undelete_recognizer_request (google.cloud.speech_v2.types.UndeleteRecognizerRequest): + The UndeleteRecognizerRequest that spawned + the Operation. + + This field is a member of `oneof`_ ``request``. + create_custom_class_request (google.cloud.speech_v2.types.CreateCustomClassRequest): + The CreateCustomClassRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + update_custom_class_request (google.cloud.speech_v2.types.UpdateCustomClassRequest): + The UpdateCustomClassRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + delete_custom_class_request (google.cloud.speech_v2.types.DeleteCustomClassRequest): + The DeleteCustomClassRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + undelete_custom_class_request (google.cloud.speech_v2.types.UndeleteCustomClassRequest): + The UndeleteCustomClassRequest that spawned + the Operation. + + This field is a member of `oneof`_ ``request``. + create_phrase_set_request (google.cloud.speech_v2.types.CreatePhraseSetRequest): + The CreatePhraseSetRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + update_phrase_set_request (google.cloud.speech_v2.types.UpdatePhraseSetRequest): + The UpdatePhraseSetRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + delete_phrase_set_request (google.cloud.speech_v2.types.DeletePhraseSetRequest): + The DeletePhraseSetRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + undelete_phrase_set_request (google.cloud.speech_v2.types.UndeletePhraseSetRequest): + The UndeletePhraseSetRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + update_config_request (google.cloud.speech_v2.types.UpdateConfigRequest): + The UpdateConfigRequest that spawned the + Operation. + + This field is a member of `oneof`_ ``request``. + progress_percent (int): + The percent progress of the Operation. Values + can range from 0-100. If the value is 100, then + the operation is finished. + batch_recognize_metadata (google.cloud.speech_v2.types.BatchRecognizeMetadata): + Metadata specific to the BatchRecognize + method. + + This field is a member of `oneof`_ ``metadata``. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + resource: str = proto.Field( + proto.STRING, + number=3, + ) + method: str = proto.Field( + proto.STRING, + number=4, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=6, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=7, + ) + batch_recognize_request: "BatchRecognizeRequest" = proto.Field( + proto.MESSAGE, + number=8, + oneof="request", + message="BatchRecognizeRequest", + ) + create_recognizer_request: "CreateRecognizerRequest" = proto.Field( + proto.MESSAGE, + number=9, + oneof="request", + message="CreateRecognizerRequest", + ) + update_recognizer_request: "UpdateRecognizerRequest" = proto.Field( + proto.MESSAGE, + number=10, + oneof="request", + message="UpdateRecognizerRequest", + ) + delete_recognizer_request: "DeleteRecognizerRequest" = proto.Field( + proto.MESSAGE, + number=11, + oneof="request", + message="DeleteRecognizerRequest", + ) + undelete_recognizer_request: "UndeleteRecognizerRequest" = proto.Field( + proto.MESSAGE, + number=12, + oneof="request", + message="UndeleteRecognizerRequest", + ) + create_custom_class_request: "CreateCustomClassRequest" = proto.Field( + proto.MESSAGE, + number=13, + oneof="request", + message="CreateCustomClassRequest", + ) + update_custom_class_request: "UpdateCustomClassRequest" = proto.Field( + proto.MESSAGE, + number=14, + oneof="request", + message="UpdateCustomClassRequest", + ) + delete_custom_class_request: "DeleteCustomClassRequest" = proto.Field( + proto.MESSAGE, + number=15, + oneof="request", + message="DeleteCustomClassRequest", + ) + undelete_custom_class_request: "UndeleteCustomClassRequest" = proto.Field( + proto.MESSAGE, + number=16, + oneof="request", + message="UndeleteCustomClassRequest", + ) + create_phrase_set_request: "CreatePhraseSetRequest" = proto.Field( + proto.MESSAGE, + number=17, + oneof="request", + message="CreatePhraseSetRequest", + ) + update_phrase_set_request: "UpdatePhraseSetRequest" = proto.Field( + proto.MESSAGE, + number=18, + oneof="request", + message="UpdatePhraseSetRequest", + ) + delete_phrase_set_request: "DeletePhraseSetRequest" = proto.Field( + proto.MESSAGE, + number=19, + oneof="request", + message="DeletePhraseSetRequest", + ) + undelete_phrase_set_request: "UndeletePhraseSetRequest" = proto.Field( + proto.MESSAGE, + number=20, + oneof="request", + message="UndeletePhraseSetRequest", + ) + update_config_request: "UpdateConfigRequest" = proto.Field( + proto.MESSAGE, + number=21, + oneof="request", + message="UpdateConfigRequest", + ) + progress_percent: int = proto.Field( + proto.INT32, + number=22, + ) + batch_recognize_metadata: "BatchRecognizeMetadata" = proto.Field( + proto.MESSAGE, + number=23, + oneof="metadata", + message="BatchRecognizeMetadata", + ) + + +class ListRecognizersRequest(proto.Message): + r"""Request message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + + Attributes: + parent (str): + Required. The project and location of Recognizers to list. + The expected format is + ``projects/{project}/locations/{location}``. + page_size (int): + The maximum number of Recognizers to return. + The service may return fewer than this value. If + unspecified, at most 5 Recognizers will be + returned. The maximum value is 100; values above + 100 will be coerced to 100. + page_token (str): + A page token, received from a previous + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + must match the call that provided the page token. + show_deleted (bool): + Whether, or not, to show resources that have + been deleted. + """ + + 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, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListRecognizersResponse(proto.Message): + r"""Response message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + + Attributes: + recognizers (MutableSequence[google.cloud.speech_v2.types.Recognizer]): + The list of requested Recognizers. + next_page_token (str): + A token, which can be sent as + [page_token][google.cloud.speech.v2.ListRecognizersRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. This token expires after 72 hours. + """ + + @property + def raw_page(self): + return self + + recognizers: MutableSequence["Recognizer"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Recognizer", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetRecognizerRequest(proto.Message): + r"""Request message for the + [GetRecognizer][google.cloud.speech.v2.Speech.GetRecognizer] method. + + Attributes: + name (str): + Required. The name of the Recognizer to retrieve. The + expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateRecognizerRequest(proto.Message): + r"""Request message for the + [UpdateRecognizer][google.cloud.speech.v2.Speech.UpdateRecognizer] + method. + + Attributes: + recognizer (google.cloud.speech_v2.types.Recognizer): + Required. The Recognizer to update. + + The Recognizer's ``name`` field is used to identify the + Recognizer to update. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to update. If empty, all non-default + valued fields are considered for update. Use ``*`` to update + the entire Recognizer resource. + validate_only (bool): + If set, validate the request and preview the + updated Recognizer, but do not actually update + it. + """ + + recognizer: "Recognizer" = proto.Field( + proto.MESSAGE, + number=1, + message="Recognizer", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteRecognizerRequest(proto.Message): + r"""Request message for the + [DeleteRecognizer][google.cloud.speech.v2.Speech.DeleteRecognizer] + method. + + Attributes: + name (str): + Required. The name of the Recognizer to delete. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}`` + validate_only (bool): + If set, validate the request and preview the + deleted Recognizer, but do not actually delete + it. + allow_missing (bool): + If set to true, and the Recognizer is not + found, the request will succeed and be a no-op + (no Operation is recorded in this case). + etag (str): + 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. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UndeleteRecognizerRequest(proto.Message): + r"""Request message for the + [UndeleteRecognizer][google.cloud.speech.v2.Speech.UndeleteRecognizer] + method. + + Attributes: + name (str): + Required. The name of the Recognizer to undelete. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}`` + validate_only (bool): + If set, validate the request and preview the + undeleted Recognizer, but do not actually + undelete it. + etag (str): + 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. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Recognizer(proto.Message): + r"""A Recognizer message. Stores recognition configuration and + metadata. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + Recognizer. Format: + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + uid (str): + Output only. System-assigned unique + identifier for the Recognizer. + display_name (str): + User-settable, human-readable name for the + Recognizer. Must be 63 characters or less. + model (str): + Optional. This field is now deprecated. Prefer the + [``model``][google.cloud.speech.v2.RecognitionConfig.model] + field in the + [``RecognitionConfig``][google.cloud.speech.v2.RecognitionConfig] + message. + + Which model to use for recognition requests. Select the + model best suited to your domain to get best results. + + Guidance for choosing which model to use can be found in the + `Transcription Models + Documentation `__ + and the models supported in each region can be found in the + `Table Of Supported + Models `__. + language_codes (MutableSequence[str]): + Optional. This field is now deprecated. Prefer the + [``language_codes``][google.cloud.speech.v2.RecognitionConfig.language_codes] + field in the + [``RecognitionConfig``][google.cloud.speech.v2.RecognitionConfig] + message. + + The language of the supplied audio as a + `BCP-47 `__ + language tag. + + Supported languages for each model are listed in the `Table + of Supported + Models `__. + + If additional languages are provided, recognition result + will contain recognition in the most likely language + detected. The recognition result will include the language + tag of the language detected in the audio. When you create + or update a Recognizer, these values are stored in + normalized BCP-47 form. For example, "en-us" is stored as + "en-US". + default_recognition_config (google.cloud.speech_v2.types.RecognitionConfig): + Default configuration to use for requests with this + Recognizer. This can be overwritten by inline configuration + in the + [RecognizeRequest.config][google.cloud.speech.v2.RecognizeRequest.config] + field. + annotations (MutableMapping[str, str]): + 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. + state (google.cloud.speech_v2.types.Recognizer.State): + Output only. The Recognizer lifecycle state. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + Recognizer was modified. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + Recognizer was requested for deletion. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + Recognizer will be purged. + 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. + reconciling (bool): + Output only. Whether or not this Recognizer + is in the process of being updated. + kms_key_name (str): + Output only. The `KMS key + name `__ + with which the Recognizer 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 `__ + with which the Recognizer is encrypted. The expected format + is + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}``. + """ + + class State(proto.Enum): + r"""Set of states that define the lifecycle of a Recognizer. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + ACTIVE (2): + The Recognizer is active and ready for use. + DELETED (4): + This Recognizer has been deleted. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 2 + DELETED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + model: str = proto.Field( + proto.STRING, + number=4, + ) + language_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=17, + ) + default_recognition_config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=6, + message="RecognitionConfig", + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + 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=14, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=12, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=13, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=15, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=16, + ) + + +class AutoDetectDecodingConfig(proto.Message): + r"""Automatically detected decoding parameters. Supported for the + following encodings: + + - WAV_LINEAR16: 16-bit signed little-endian PCM samples in a WAV + container. + + - WAV_MULAW: 8-bit companded mulaw samples in a WAV container. + + - WAV_ALAW: 8-bit companded alaw samples in a WAV container. + + - RFC4867_5_AMR: AMR frames with an rfc4867.5 header. + + - RFC4867_5_AMRWB: AMR-WB frames with an rfc4867.5 header. + + - FLAC: FLAC frames in the "native FLAC" container format. + + - MP3: MPEG audio frames with optional (ignored) ID3 metadata. + + - OGG_OPUS: Opus audio frames in an Ogg container. + + - WEBM_OPUS: Opus audio frames in a WebM container. + + - MP4_AAC: AAC audio frames in an MP4 container. + + - M4A_AAC: AAC audio frames in an M4A container. + + - MOV_AAC: AAC audio frames in an MOV container. + + """ + + +class ExplicitDecodingConfig(proto.Message): + r"""Explicitly specified decoding parameters. + + Attributes: + encoding (google.cloud.speech_v2.types.ExplicitDecodingConfig.AudioEncoding): + Required. Encoding of the audio data sent for + recognition. + sample_rate_hertz (int): + Optional. Sample rate in Hertz of the audio + data sent for recognition. Valid values are: + 8000-48000, and 16000 is optimal. For best + results, set the sampling rate of the audio + source to 16000 Hz. If that's not possible, use + the native sample rate of the audio source + (instead of resampling). Note that this field is + marked as OPTIONAL for backward compatibility + reasons. It is (and has always been) effectively + REQUIRED. + audio_channel_count (int): + Optional. Number of channels present in the + audio data sent for recognition. Note that this + field is marked as OPTIONAL for backward + compatibility reasons. It is (and has always + been) effectively REQUIRED. + + The maximum allowed value is 8. + """ + + class AudioEncoding(proto.Enum): + r"""Supported audio data encodings. + + Values: + AUDIO_ENCODING_UNSPECIFIED (0): + Default value. This value is unused. + LINEAR16 (1): + Headerless 16-bit signed little-endian PCM + samples. + MULAW (2): + Headerless 8-bit companded mulaw samples. + ALAW (3): + Headerless 8-bit companded alaw samples. + AMR (4): + AMR frames with an rfc4867.5 header. + AMR_WB (5): + AMR-WB frames with an rfc4867.5 header. + FLAC (6): + FLAC frames in the "native FLAC" container + format. + MP3 (7): + MPEG audio frames with optional (ignored) ID3 + metadata. + OGG_OPUS (8): + Opus audio frames in an Ogg container. + WEBM_OPUS (9): + Opus audio frames in a WebM container. + MP4_AAC (10): + AAC audio frames in an MP4 container. + M4A_AAC (11): + AAC audio frames in an M4A container. + MOV_AAC (12): + AAC audio frames in an MOV container. + """ + + AUDIO_ENCODING_UNSPECIFIED = 0 + LINEAR16 = 1 + MULAW = 2 + ALAW = 3 + AMR = 4 + AMR_WB = 5 + FLAC = 6 + MP3 = 7 + OGG_OPUS = 8 + WEBM_OPUS = 9 + MP4_AAC = 10 + M4A_AAC = 11 + MOV_AAC = 12 + + encoding: AudioEncoding = proto.Field( + proto.ENUM, + number=1, + enum=AudioEncoding, + ) + sample_rate_hertz: int = proto.Field( + proto.INT32, + number=2, + ) + audio_channel_count: int = proto.Field( + proto.INT32, + number=3, + ) + + +class SpeakerDiarizationConfig(proto.Message): + r"""Configuration to enable speaker diarization. + + Attributes: + min_speaker_count (int): + Optional. The system automatically determines + the number of speakers. This value is not + currently used. + max_speaker_count (int): + Optional. The system automatically determines + the number of speakers. This value is not + currently used. + """ + + min_speaker_count: int = proto.Field( + proto.INT32, + number=2, + ) + max_speaker_count: int = proto.Field( + proto.INT32, + number=3, + ) + + +class CustomPromptConfig(proto.Message): + r"""Configuration to enable custom prompt in chirp3. + + Attributes: + custom_prompt (str): + Optional. The custom instructions to override + the existing instructions for chirp3. + """ + + custom_prompt: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RecognitionFeatures(proto.Message): + r"""Available recognition features. + + Attributes: + profanity_filter (bool): + If set to ``true``, the server will attempt to filter out + profanities, replacing all but the initial character in each + filtered word with asterisks, for instance, "f**\*". If set + to ``false`` or omitted, profanities won't be filtered out. + enable_word_time_offsets (bool): + If ``true``, the top result includes a list of words and the + start and end time offsets (timestamps) for those words. If + ``false``, no word-level time offset information is + returned. The default is ``false``. + enable_word_confidence (bool): + If ``true``, the top result includes a list of words and the + confidence for those words. If ``false``, no word-level + confidence information is returned. The default is + ``false``. + enable_automatic_punctuation (bool): + If ``true``, adds punctuation to recognition result + hypotheses. This feature is only available in select + languages. The default ``false`` value does not add + punctuation to result hypotheses. + enable_spoken_punctuation (bool): + The spoken punctuation behavior for the call. If ``true``, + replaces spoken punctuation with the corresponding symbols + in the request. For example, "how are you question mark" + becomes "how are you?". See + https://cloud.google.com/speech-to-text/docs/spoken-punctuation + for support. If ``false``, spoken punctuation is not + replaced. + enable_spoken_emojis (bool): + The spoken emoji behavior for the call. If ``true``, adds + spoken emoji formatting for the request. This will replace + spoken emojis with the corresponding Unicode symbols in the + final transcript. If ``false``, spoken emojis are not + replaced. + multi_channel_mode (google.cloud.speech_v2.types.RecognitionFeatures.MultiChannelMode): + Mode for recognizing multi-channel audio. + diarization_config (google.cloud.speech_v2.types.SpeakerDiarizationConfig): + Configuration to enable speaker diarization. + To enable diarization, set this field to an + empty SpeakerDiarizationConfig message. + max_alternatives (int): + Maximum number of recognition hypotheses to be returned. The + server may return fewer than ``max_alternatives``. Valid + values are ``0``-``30``. A value of ``0`` or ``1`` will + return a maximum of one. If omitted, will return a maximum + of one. + custom_prompt_config (google.cloud.speech_v2.types.CustomPromptConfig): + Optional. Configuration to enable custom + prompt for chirp3. + """ + + class MultiChannelMode(proto.Enum): + r"""Options for how to recognize multi-channel audio. + + Values: + MULTI_CHANNEL_MODE_UNSPECIFIED (0): + Default value for the multi-channel mode. If + the audio contains multiple channels, only the + first channel will be transcribed; other + channels will be ignored. + SEPARATE_RECOGNITION_PER_CHANNEL (1): + If selected, each channel in the provided audio is + transcribed independently. This cannot be selected if the + selected [model][google.cloud.speech.v2.Recognizer.model] is + ``latest_short``. + """ + + MULTI_CHANNEL_MODE_UNSPECIFIED = 0 + SEPARATE_RECOGNITION_PER_CHANNEL = 1 + + profanity_filter: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_word_time_offsets: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_word_confidence: bool = proto.Field( + proto.BOOL, + number=3, + ) + enable_automatic_punctuation: bool = proto.Field( + proto.BOOL, + number=4, + ) + enable_spoken_punctuation: bool = proto.Field( + proto.BOOL, + number=14, + ) + enable_spoken_emojis: bool = proto.Field( + proto.BOOL, + number=15, + ) + multi_channel_mode: MultiChannelMode = proto.Field( + proto.ENUM, + number=17, + enum=MultiChannelMode, + ) + diarization_config: "SpeakerDiarizationConfig" = proto.Field( + proto.MESSAGE, + number=9, + message="SpeakerDiarizationConfig", + ) + max_alternatives: int = proto.Field( + proto.INT32, + number=16, + ) + custom_prompt_config: "CustomPromptConfig" = proto.Field( + proto.MESSAGE, + number=18, + message="CustomPromptConfig", + ) + + +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_v2.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, + ) + + +class TranslationConfig(proto.Message): + r"""Translation configuration. Use to translate the given audio + into text for the desired language. + + Attributes: + target_language (str): + Required. The language code to translate to. + """ + + target_language: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SpeechAdaptation(proto.Message): + r"""Provides "hints" to the speech recognizer to favor specific + words and phrases in the results. PhraseSets can be specified as + an inline resource, or a reference to an existing PhraseSet + resource. + + Attributes: + phrase_sets (MutableSequence[google.cloud.speech_v2.types.SpeechAdaptation.AdaptationPhraseSet]): + A list of inline or referenced PhraseSets. + custom_classes (MutableSequence[google.cloud.speech_v2.types.CustomClass]): + A list of inline CustomClasses. Existing + CustomClass resources can be referenced directly + in a PhraseSet. + """ + + class AdaptationPhraseSet(proto.Message): + r"""A biasing PhraseSet, which can be either a string referencing + the name of an existing PhraseSets resource, or an inline + definition of a PhraseSet. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + phrase_set (str): + The name of an existing PhraseSet resource. + The user must have read access to the resource + and it must not be deleted. + + This field is a member of `oneof`_ ``value``. + inline_phrase_set (google.cloud.speech_v2.types.PhraseSet): + An inline defined PhraseSet. + + This field is a member of `oneof`_ ``value``. + """ + + phrase_set: str = proto.Field( + proto.STRING, + number=1, + oneof="value", + ) + inline_phrase_set: "PhraseSet" = proto.Field( + proto.MESSAGE, + number=2, + oneof="value", + message="PhraseSet", + ) + + phrase_sets: MutableSequence[AdaptationPhraseSet] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AdaptationPhraseSet, + ) + custom_classes: MutableSequence["CustomClass"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="CustomClass", + ) + + +class DenoiserConfig(proto.Message): + r"""Denoiser config. May not be supported for all models and may + have no effect. + + Attributes: + denoise_audio (bool): + Denoise audio before sending to the + transcription model. + snr_threshold (float): + Signal-to-Noise Ratio (SNR) threshold for the denoiser. Here + SNR means the loudness of the speech signal. Audio with an + SNR below this threshold, meaning the speech is too quiet, + will be prevented from being sent to the transcription + model. + + If snr_threshold=0, no filtering will be applied. + """ + + denoise_audio: bool = proto.Field( + proto.BOOL, + number=1, + ) + snr_threshold: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class RecognitionConfig(proto.Message): + r"""Provides information to the Recognizer that specifies how to + process the recognition request. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + auto_decoding_config (google.cloud.speech_v2.types.AutoDetectDecodingConfig): + Automatically detect decoding parameters. + Preferred for supported formats. + + This field is a member of `oneof`_ ``decoding_config``. + explicit_decoding_config (google.cloud.speech_v2.types.ExplicitDecodingConfig): + Explicitly specified decoding parameters. + Required if using headerless PCM audio + (linear16, mulaw, alaw). + + This field is a member of `oneof`_ ``decoding_config``. + model (str): + Optional. Which model to use for recognition requests. + Select the model best suited to your domain to get best + results. + + Guidance for choosing which model to use can be found in the + `Transcription Models + Documentation `__ + and the models supported in each region can be found in the + `Table Of Supported + Models `__. + language_codes (MutableSequence[str]): + Optional. The language of the supplied audio as a + `BCP-47 `__ + language tag. Language tags are normalized to BCP-47 before + they are used eg "en-us" becomes "en-US". + + Supported languages for each model are listed in the `Table + of Supported + Models `__. + + If additional languages are provided, recognition result + will contain recognition in the most likely language + detected. The recognition result will include the language + tag of the language detected in the audio. + features (google.cloud.speech_v2.types.RecognitionFeatures): + Speech recognition features to enable. + adaptation (google.cloud.speech_v2.types.SpeechAdaptation): + Speech adaptation context that weights + recognizer predictions for specific words and + phrases. + transcript_normalization (google.cloud.speech_v2.types.TranscriptNormalization): + Optional. 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. + translation_config (google.cloud.speech_v2.types.TranslationConfig): + Optional. Optional configuration used to + automatically run translation on the given audio + to the desired language for supported models. + denoiser_config (google.cloud.speech_v2.types.DenoiserConfig): + Optional. Optional denoiser config. May not + be supported for all models and may have no + effect. + """ + + auto_decoding_config: "AutoDetectDecodingConfig" = proto.Field( + proto.MESSAGE, + number=7, + oneof="decoding_config", + message="AutoDetectDecodingConfig", + ) + explicit_decoding_config: "ExplicitDecodingConfig" = proto.Field( + proto.MESSAGE, + number=8, + oneof="decoding_config", + message="ExplicitDecodingConfig", + ) + model: str = proto.Field( + proto.STRING, + number=9, + ) + language_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + features: "RecognitionFeatures" = proto.Field( + proto.MESSAGE, + number=2, + message="RecognitionFeatures", + ) + adaptation: "SpeechAdaptation" = proto.Field( + proto.MESSAGE, + number=6, + message="SpeechAdaptation", + ) + transcript_normalization: "TranscriptNormalization" = proto.Field( + proto.MESSAGE, + number=11, + message="TranscriptNormalization", + ) + translation_config: "TranslationConfig" = proto.Field( + proto.MESSAGE, + number=15, + message="TranslationConfig", + ) + denoiser_config: "DenoiserConfig" = proto.Field( + proto.MESSAGE, + number=16, + message="DenoiserConfig", + ) + + +class RecognizeRequest(proto.Message): + r"""Request message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] method. Either + ``content`` or ``uri`` must be supplied. Supplying both or neither + returns [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. See + `content + limits `__. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + recognizer (str): + Required. The name of the Recognizer to use during + recognition. The expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + The {recognizer} segment may be set to ``_`` to use an empty + implicit Recognizer. + config (google.cloud.speech_v2.types.RecognitionConfig): + Features and audio metadata to use for the Automatic Speech + Recognition. This field in combination with the + [config_mask][google.cloud.speech.v2.RecognizeRequest.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource. + config_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields in + [config][google.cloud.speech.v2.RecognizeRequest.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all non-default valued fields in + [config][google.cloud.speech.v2.RecognizeRequest.config] + override the values in the recognizer for this recognition + request. If a mask is provided, only the fields listed in + the mask override the config in the recognizer for this + recognition request. If a wildcard (``*``) is provided, + [config][google.cloud.speech.v2.RecognizeRequest.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + content (bytes): + The audio data bytes encoded as specified in + [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. + As with all bytes fields, proto buffers use a pure binary + representation, whereas JSON representations use base64. + + This field is a member of `oneof`_ ``audio_source``. + uri (str): + URI that points to a file that contains audio data bytes as + specified in + [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. + The file must not be compressed (for example, gzip). + Currently, only Google Cloud Storage URIs are supported, + which must be specified in the following format: + ``gs://bucket_name/object_name`` (other URI formats return + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For + more information, see `Request + URIs `__. + + This field is a member of `oneof`_ ``audio_source``. + """ + + recognizer: str = proto.Field( + proto.STRING, + number=3, + ) + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + config_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=8, + message=field_mask_pb2.FieldMask, + ) + content: bytes = proto.Field( + proto.BYTES, + number=5, + oneof="audio_source", + ) + uri: str = proto.Field( + proto.STRING, + number=6, + oneof="audio_source", + ) + + +class RecognitionResponseMetadata(proto.Message): + r"""Metadata about the recognition request and response. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + request_id (str): + Global request identifier auto-generated by + the API. + total_billed_duration (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + corresponding request. + prompt (str): + Optional. Output only. Provides the prompt + used for the recognition request. + + This field is a member of `oneof`_ ``_prompt``. + """ + + request_id: str = proto.Field( + proto.STRING, + number=9, + ) + total_billed_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + prompt: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + + +class SpeechRecognitionAlternative(proto.Message): + r"""Alternative hypotheses (a.k.a. n-best list). + + Attributes: + transcript (str): + Transcript text representing the words that + the user spoke. + confidence (float): + The confidence estimate between 0.0 and 1.0. A higher number + indicates an estimated greater likelihood that the + recognized words are correct. This field is set only for the + top alternative of a non-streaming result or, of a streaming + result where + [is_final][google.cloud.speech.v2.StreamingRecognitionResult.is_final] + is set to ``true``. This field is not guaranteed to be + accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + words (MutableSequence[google.cloud.speech_v2.types.WordInfo]): + A list of word-specific information for each recognized + word. When the + [SpeakerDiarizationConfig][google.cloud.speech.v2.SpeakerDiarizationConfig] + is set, you will see all the words from the beginning of the + audio. + """ + + transcript: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + words: MutableSequence["WordInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="WordInfo", + ) + + +class WordInfo(proto.Message): + r"""Word-specific information for recognized words. + + Attributes: + start_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the start of the spoken word. This field is + only set if + [enable_word_time_offsets][google.cloud.speech.v2.RecognitionFeatures.enable_word_time_offsets] + is ``true`` and only in the top hypothesis. This is an + experimental feature and the accuracy of the time offset can + vary. + end_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the end of the spoken word. This field is + only set if + [enable_word_time_offsets][google.cloud.speech.v2.RecognitionFeatures.enable_word_time_offsets] + is ``true`` and only in the top hypothesis. This is an + experimental feature and the accuracy of the time offset can + vary. + word (str): + The word corresponding to this set of + information. + confidence (float): + The confidence estimate between 0.0 and 1.0. A higher number + indicates an estimated greater likelihood that the + recognized words are correct. This field is set only for the + top alternative of a non-streaming result or, of a streaming + result where + [is_final][google.cloud.speech.v2.StreamingRecognitionResult.is_final] + is set to ``true``. This field is not guaranteed to be + accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + speaker_label (str): + A distinct label is assigned for every speaker within the + audio. This field specifies which one of those speakers was + detected to have spoken this word. ``speaker_label`` is set + if + [SpeakerDiarizationConfig][google.cloud.speech.v2.SpeakerDiarizationConfig] + is given and only in the top alternative. + """ + + start_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + word: str = proto.Field( + proto.STRING, + number=3, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=4, + ) + speaker_label: str = proto.Field( + proto.STRING, + number=6, + ) + + +class SpeechRecognitionResult(proto.Message): + r"""A speech recognition result corresponding to a portion of the + audio. + + Attributes: + alternatives (MutableSequence[google.cloud.speech_v2.types.SpeechRecognitionAlternative]): + May contain one or more recognition + hypotheses. These alternatives are ordered in + terms of accuracy, with the top (first) + alternative being the most probable, as ranked + by the recognizer. + channel_tag (int): + For multi-channel audio, this is the channel number + corresponding to the recognized result for the audio from + that channel. For ``audio_channel_count`` = ``N``, its + output values can range from ``1`` to ``N``. + result_end_offset (google.protobuf.duration_pb2.Duration): + Time offset of the end of this result + relative to the beginning of the audio. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives: MutableSequence["SpeechRecognitionAlternative"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SpeechRecognitionAlternative", + ) + channel_tag: int = proto.Field( + proto.INT32, + number=2, + ) + result_end_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + language_code: str = proto.Field( + proto.STRING, + number=5, + ) + + +class RecognizeResponse(proto.Message): + r"""Response message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] method. + + Attributes: + results (MutableSequence[google.cloud.speech_v2.types.SpeechRecognitionResult]): + Sequential list of transcription results + corresponding to sequential portions of audio. + metadata (google.cloud.speech_v2.types.RecognitionResponseMetadata): + Metadata about the recognition. + """ + + results: MutableSequence["SpeechRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SpeechRecognitionResult", + ) + metadata: "RecognitionResponseMetadata" = proto.Field( + proto.MESSAGE, + number=2, + message="RecognitionResponseMetadata", + ) + + +class StreamingRecognitionFeatures(proto.Message): + r"""Available recognition features specific to streaming + recognition requests. + + Attributes: + enable_voice_activity_events (bool): + If ``true``, responses with voice activity speech events + will be returned as they are detected. + interim_results (bool): + Whether or not to stream interim results to + the client. If set to true, interim results will + be streamed to the client. Otherwise, only the + final response will be streamed back. + voice_activity_timeout (google.cloud.speech_v2.types.StreamingRecognitionFeatures.VoiceActivityTimeout): + If set, the server will automatically close the stream after + the specified duration has elapsed after the last + VOICE_ACTIVITY speech event has been sent. The field + ``voice_activity_events`` must also be set to true. + endpointing_sensitivity (google.cloud.speech_v2.types.StreamingRecognitionFeatures.EndpointingSensitivity): + Optional. Endpointing sensitivity for this + stream. + """ + + class EndpointingSensitivity(proto.Enum): + r"""Endpointing sensitivity is intended for applications that + want to minimize result latency, possibly at the expense of + quality. Some utterances may be broken up into multiple + fragments. + + Values: + ENDPOINTING_SENSITIVITY_UNSPECIFIED (0): + If no value is specified, the values for + ENDPOINTING_SENSITIVITY_STANDARD will be used. + ENDPOINTING_SENSITIVITY_STANDARD (1): + Standard sensitivity, no optimization for + latency. + ENDPOINTING_SENSITIVITY_SUPERSHORT (2): + Super short sensitivity, optimized for super + short utterances like single words ("Yes", "No", + "Hello", etc.) or a single phrase, command or + short query (e.g. "check balance", "five + dollars", "call Mom"). + ENDPOINTING_SENSITIVITY_SHORT (3): + Short sensitivity, optimized for short + utterances like single sentences. (e.g. "Remind + me to call the dentist tomorrow morning at + nine", "Navigate to the nearest coffee shop that + is currently open") + """ + + ENDPOINTING_SENSITIVITY_UNSPECIFIED = 0 + ENDPOINTING_SENSITIVITY_STANDARD = 1 + ENDPOINTING_SENSITIVITY_SUPERSHORT = 2 + ENDPOINTING_SENSITIVITY_SHORT = 3 + + class VoiceActivityTimeout(proto.Message): + r"""Events that a timeout can be set on for voice activity. + + Attributes: + speech_start_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream if no speech + begins. If this is set and no speech is detected + in this duration at the start of the stream, the + server will close the stream. + speech_end_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream after speech + ends. If this is set and no speech is detected + in this duration after speech was detected, the + server will close the stream. + """ + + speech_start_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + speech_end_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + enable_voice_activity_events: bool = proto.Field( + proto.BOOL, + number=1, + ) + interim_results: bool = proto.Field( + proto.BOOL, + number=2, + ) + voice_activity_timeout: VoiceActivityTimeout = proto.Field( + proto.MESSAGE, + number=3, + message=VoiceActivityTimeout, + ) + endpointing_sensitivity: EndpointingSensitivity = proto.Field( + proto.ENUM, + number=8, + enum=EndpointingSensitivity, + ) + + +class StreamingRecognitionConfig(proto.Message): + r"""Provides configuration information for the StreamingRecognize + request. + + Attributes: + config (google.cloud.speech_v2.types.RecognitionConfig): + Required. Features and audio metadata to use for the + Automatic Speech Recognition. This field in combination with + the + [config_mask][google.cloud.speech.v2.StreamingRecognitionConfig.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource. + config_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields in + [config][google.cloud.speech.v2.StreamingRecognitionConfig.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all non-default valued fields in + [config][google.cloud.speech.v2.StreamingRecognitionConfig.config] + override the values in the Recognizer for this recognition + request. If a mask is provided, only the fields listed in + the mask override the config in the Recognizer for this + recognition request. If a wildcard (``*``) is provided, + [config][google.cloud.speech.v2.StreamingRecognitionConfig.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + streaming_features (google.cloud.speech_v2.types.StreamingRecognitionFeatures): + Speech recognition features to enable + specific to streaming audio recognition + requests. + """ + + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RecognitionConfig", + ) + config_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + streaming_features: "StreamingRecognitionFeatures" = proto.Field( + proto.MESSAGE, + number=2, + message="StreamingRecognitionFeatures", + ) + + +class StreamingRecognizeRequest(proto.Message): + r"""Request message for the + [StreamingRecognize][google.cloud.speech.v2.Speech.StreamingRecognize] + method. Multiple + [StreamingRecognizeRequest][google.cloud.speech.v2.StreamingRecognizeRequest] + messages are sent in one call. + + If the [Recognizer][google.cloud.speech.v2.Recognizer] referenced by + [recognizer][google.cloud.speech.v2.StreamingRecognizeRequest.recognizer] + contains a fully specified request configuration then the stream may + only contain messages with only + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio] set. + + Otherwise the first message must contain a + [recognizer][google.cloud.speech.v2.StreamingRecognizeRequest.recognizer] + and a + [streaming_config][google.cloud.speech.v2.StreamingRecognizeRequest.streaming_config] + message that together fully specify the request configuration and + must not contain + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio]. All + subsequent messages must only have + [audio][google.cloud.speech.v2.StreamingRecognizeRequest.audio] set. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + recognizer (str): + Required. The name of the Recognizer to use during + recognition. The expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + The {recognizer} segment may be set to ``_`` to use an empty + implicit Recognizer. + streaming_config (google.cloud.speech_v2.types.StreamingRecognitionConfig): + StreamingRecognitionConfig to be used in this + recognition attempt. If provided, it will + override the default RecognitionConfig stored in + the Recognizer. + + This field is a member of `oneof`_ ``streaming_request``. + audio (bytes): + Inline audio bytes to be Recognized. + Maximum size for this field is 15 KB per + request. + + This field is a member of `oneof`_ ``streaming_request``. + """ + + recognizer: str = proto.Field( + proto.STRING, + number=3, + ) + streaming_config: "StreamingRecognitionConfig" = proto.Field( + proto.MESSAGE, + number=6, + oneof="streaming_request", + message="StreamingRecognitionConfig", + ) + audio: bytes = proto.Field( + proto.BYTES, + number=5, + oneof="streaming_request", + ) + + +class BatchRecognizeRequest(proto.Message): + r"""Request message for the + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + method. + + Attributes: + recognizer (str): + Required. The name of the Recognizer to use during + recognition. The expected format is + ``projects/{project}/locations/{location}/recognizers/{recognizer}``. + The {recognizer} segment may be set to ``_`` to use an empty + implicit Recognizer. + config (google.cloud.speech_v2.types.RecognitionConfig): + Features and audio metadata to use for the Automatic Speech + Recognition. This field in combination with the + [config_mask][google.cloud.speech.v2.BatchRecognizeRequest.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource. + config_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields in + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all given fields in + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + override the values in the recognizer for this recognition + request. If a mask is provided, only the fields listed in + the mask override the config in the recognizer for this + recognition request. If a wildcard (``*``) is provided, + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + files (MutableSequence[google.cloud.speech_v2.types.BatchRecognizeFileMetadata]): + Audio files with file metadata for ASR. + The maximum number of files allowed to be + specified is 15. + recognition_output_config (google.cloud.speech_v2.types.RecognitionOutputConfig): + Configuration options for where to output the + transcripts of each file. + processing_strategy (google.cloud.speech_v2.types.BatchRecognizeRequest.ProcessingStrategy): + Processing strategy to use for this request. + """ + + class ProcessingStrategy(proto.Enum): + r"""Possible processing strategies for batch requests. + + Values: + PROCESSING_STRATEGY_UNSPECIFIED (0): + Default value for the processing strategy. + The request is processed as soon as its + received. + DYNAMIC_BATCHING (1): + If selected, processes the request during + lower utilization periods for a price discount. + The request is fulfilled within 24 hours. + """ + + PROCESSING_STRATEGY_UNSPECIFIED = 0 + DYNAMIC_BATCHING = 1 + + recognizer: str = proto.Field( + proto.STRING, + number=1, + ) + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="RecognitionConfig", + ) + config_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + files: MutableSequence["BatchRecognizeFileMetadata"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="BatchRecognizeFileMetadata", + ) + recognition_output_config: "RecognitionOutputConfig" = proto.Field( + proto.MESSAGE, + number=6, + message="RecognitionOutputConfig", + ) + processing_strategy: ProcessingStrategy = proto.Field( + proto.ENUM, + number=7, + enum=ProcessingStrategy, + ) + + +class GcsOutputConfig(proto.Message): + r"""Output configurations for Cloud Storage. + + Attributes: + uri (str): + The Cloud Storage URI prefix with which + recognition results will be written. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InlineOutputConfig(proto.Message): + r"""Output configurations for inline response.""" + + +class NativeOutputFileFormatConfig(proto.Message): + r"""Output configurations for serialized ``BatchRecognizeResults`` + protos. + + """ + + +class VttOutputFileFormatConfig(proto.Message): + r"""Output configurations for + `WebVTT `__ formatted subtitle file. + + """ + + +class SrtOutputFileFormatConfig(proto.Message): + r"""Output configurations `SubRip + Text `__ + formatted subtitle file. + + """ + + +class OutputFormatConfig(proto.Message): + r"""Configuration for the format of the results stored to ``output``. + + Attributes: + native (google.cloud.speech_v2.types.NativeOutputFileFormatConfig): + Configuration for the native output format. + If this field is set or if no other output + format field is set, then transcripts will be + written to the sink in the native format. + vtt (google.cloud.speech_v2.types.VttOutputFileFormatConfig): + Configuration for the VTT output format. If + this field is set, then transcripts will be + written to the sink in the VTT format. + srt (google.cloud.speech_v2.types.SrtOutputFileFormatConfig): + Configuration for the SRT output format. If + this field is set, then transcripts will be + written to the sink in the SRT format. + """ + + native: "NativeOutputFileFormatConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="NativeOutputFileFormatConfig", + ) + vtt: "VttOutputFileFormatConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="VttOutputFileFormatConfig", + ) + srt: "SrtOutputFileFormatConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="SrtOutputFileFormatConfig", + ) + + +class RecognitionOutputConfig(proto.Message): + r"""Configuration options for the output(s) of recognition. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_output_config (google.cloud.speech_v2.types.GcsOutputConfig): + If this message is populated, recognition + results are written to the provided Google Cloud + Storage URI. + + This field is a member of `oneof`_ ``output``. + inline_response_config (google.cloud.speech_v2.types.InlineOutputConfig): + If this message is populated, recognition results are + provided in the + [BatchRecognizeResponse][google.cloud.speech.v2.BatchRecognizeResponse] + message of the Operation when completed. This is only + supported when calling + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + with just one audio file. + + This field is a member of `oneof`_ ``output``. + output_format_config (google.cloud.speech_v2.types.OutputFormatConfig): + Optional. Configuration for the format of the results stored + to ``output``. If unspecified transcripts will be written in + the ``NATIVE`` format only. + """ + + gcs_output_config: "GcsOutputConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="output", + message="GcsOutputConfig", + ) + inline_response_config: "InlineOutputConfig" = proto.Field( + proto.MESSAGE, + number=2, + oneof="output", + message="InlineOutputConfig", + ) + output_format_config: "OutputFormatConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="OutputFormatConfig", + ) + + +class BatchRecognizeResponse(proto.Message): + r"""Response message for + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] that + is packaged into a longrunning + [Operation][google.longrunning.Operation]. + + Attributes: + results (MutableMapping[str, google.cloud.speech_v2.types.BatchRecognizeFileResult]): + Map from filename to the final result for + that file. + total_billed_duration (google.protobuf.duration_pb2.Duration): + When available, billed audio seconds for the + corresponding request. + """ + + results: MutableMapping[str, "BatchRecognizeFileResult"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="BatchRecognizeFileResult", + ) + total_billed_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class BatchRecognizeResults(proto.Message): + r"""Output type for Cloud Storage of BatchRecognize transcripts. + Though this proto isn't returned in this API anywhere, the Cloud + Storage transcripts will be this proto serialized and should be + parsed as such. + + Attributes: + results (MutableSequence[google.cloud.speech_v2.types.SpeechRecognitionResult]): + Sequential list of transcription results + corresponding to sequential portions of audio. + metadata (google.cloud.speech_v2.types.RecognitionResponseMetadata): + Metadata about the recognition. + """ + + results: MutableSequence["SpeechRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SpeechRecognitionResult", + ) + metadata: "RecognitionResponseMetadata" = proto.Field( + proto.MESSAGE, + number=2, + message="RecognitionResponseMetadata", + ) + + +class CloudStorageResult(proto.Message): + r"""Final results written to Cloud Storage. + + Attributes: + uri (str): + The Cloud Storage URI to which recognition + results were written. + vtt_format_uri (str): + The Cloud Storage URI to which recognition results were + written as VTT formatted captions. This is populated only + when ``VTT`` output is requested. + srt_format_uri (str): + The Cloud Storage URI to which recognition results were + written as SRT formatted captions. This is populated only + when ``SRT`` output is requested. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + vtt_format_uri: str = proto.Field( + proto.STRING, + number=2, + ) + srt_format_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class InlineResult(proto.Message): + r"""Final results returned inline in the recognition response. + + Attributes: + transcript (google.cloud.speech_v2.types.BatchRecognizeResults): + The transcript for the audio file. + vtt_captions (str): + The transcript for the audio file as VTT formatted captions. + This is populated only when ``VTT`` output is requested. + srt_captions (str): + The transcript for the audio file as SRT formatted captions. + This is populated only when ``SRT`` output is requested. + """ + + transcript: "BatchRecognizeResults" = proto.Field( + proto.MESSAGE, + number=1, + message="BatchRecognizeResults", + ) + vtt_captions: str = proto.Field( + proto.STRING, + number=2, + ) + srt_captions: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchRecognizeFileResult(proto.Message): + r"""Final results for a single file. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + error (google.rpc.status_pb2.Status): + Error if one was encountered. + metadata (google.cloud.speech_v2.types.RecognitionResponseMetadata): + + cloud_storage_result (google.cloud.speech_v2.types.CloudStorageResult): + Recognition results written to Cloud Storage. This is + populated only when + [GcsOutputConfig][google.cloud.speech.v2.GcsOutputConfig] is + set in the + [RecognitionOutputConfig][[google.cloud.speech.v2.RecognitionOutputConfig]. + + This field is a member of `oneof`_ ``result``. + inline_result (google.cloud.speech_v2.types.InlineResult): + Recognition results. This is populated only when + [InlineOutputConfig][google.cloud.speech.v2.InlineOutputConfig] + is set in the + [RecognitionOutputConfig][[google.cloud.speech.v2.RecognitionOutputConfig]. + + This field is a member of `oneof`_ ``result``. + uri (str): + Deprecated. Use ``cloud_storage_result.native_format_uri`` + instead. + transcript (google.cloud.speech_v2.types.BatchRecognizeResults): + Deprecated. Use ``inline_result.transcript`` instead. + """ + + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + metadata: "RecognitionResponseMetadata" = proto.Field( + proto.MESSAGE, + number=3, + message="RecognitionResponseMetadata", + ) + cloud_storage_result: "CloudStorageResult" = proto.Field( + proto.MESSAGE, + number=5, + oneof="result", + message="CloudStorageResult", + ) + inline_result: "InlineResult" = proto.Field( + proto.MESSAGE, + number=6, + oneof="result", + message="InlineResult", + ) + uri: str = proto.Field( + proto.STRING, + number=1, + ) + transcript: "BatchRecognizeResults" = proto.Field( + proto.MESSAGE, + number=4, + message="BatchRecognizeResults", + ) + + +class BatchRecognizeTranscriptionMetadata(proto.Message): + r"""Metadata about transcription for a single file (for example, + progress percent). + + Attributes: + progress_percent (int): + How much of the file has been transcribed so + far. + error (google.rpc.status_pb2.Status): + Error if one was encountered. + uri (str): + The Cloud Storage URI to which recognition + results will be written. + """ + + progress_percent: int = proto.Field( + proto.INT32, + number=1, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchRecognizeMetadata(proto.Message): + r"""Operation metadata for + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize]. + + Attributes: + transcription_metadata (MutableMapping[str, google.cloud.speech_v2.types.BatchRecognizeTranscriptionMetadata]): + Map from provided filename to the + transcription metadata for that file. + """ + + transcription_metadata: MutableMapping[ + str, "BatchRecognizeTranscriptionMetadata" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="BatchRecognizeTranscriptionMetadata", + ) + + +class BatchRecognizeFileMetadata(proto.Message): + r"""Metadata about a single file in a batch for BatchRecognize. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Cloud Storage URI for the audio file. + + This field is a member of `oneof`_ ``audio_source``. + config (google.cloud.speech_v2.types.RecognitionConfig): + Features and audio metadata to use for the Automatic Speech + Recognition. This field in combination with the + [config_mask][google.cloud.speech.v2.BatchRecognizeFileMetadata.config_mask] + field can be used to override parts of the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the Recognizer resource as well as the + [config][google.cloud.speech.v2.BatchRecognizeRequest.config] + at the request level. + config_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields in + [config][google.cloud.speech.v2.BatchRecognizeFileMetadata.config] + that override the values in the + [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config] + of the recognizer during this recognition request. If no + mask is provided, all non-default valued fields in + [config][google.cloud.speech.v2.BatchRecognizeFileMetadata.config] + override the values in the recognizer for this recognition + request. If a mask is provided, only the fields listed in + the mask override the config in the recognizer for this + recognition request. If a wildcard (``*``) is provided, + [config][google.cloud.speech.v2.BatchRecognizeFileMetadata.config] + completely overrides and replaces the config in the + recognizer for this recognition request. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + oneof="audio_source", + ) + config: "RecognitionConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="RecognitionConfig", + ) + config_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class StreamingRecognitionResult(proto.Message): + r"""A streaming speech recognition result corresponding to a + portion of the audio that is currently being processed. + + Attributes: + alternatives (MutableSequence[google.cloud.speech_v2.types.SpeechRecognitionAlternative]): + May contain one or more recognition + hypotheses. These alternatives are ordered in + terms of accuracy, with the top (first) + alternative being the most probable, as ranked + by the recognizer. + is_final (bool): + If ``false``, this + [StreamingRecognitionResult][google.cloud.speech.v2.StreamingRecognitionResult] + represents an interim result that may change. If ``true``, + this is the final time the speech service will return this + particular + [StreamingRecognitionResult][google.cloud.speech.v2.StreamingRecognitionResult], + the recognizer will not return any further hypotheses for + this portion of the transcript and corresponding audio. + stability (float): + An estimate of the likelihood that the recognizer will not + change its guess about this interim result. Values range + from 0.0 (completely unstable) to 1.0 (completely stable). + This field is only provided for interim results + ([is_final][google.cloud.speech.v2.StreamingRecognitionResult.is_final]=\ ``false``). + The default of 0.0 is a sentinel value indicating + ``stability`` was not set. + result_end_offset (google.protobuf.duration_pb2.Duration): + Time offset of the end of this result + relative to the beginning of the audio. + channel_tag (int): + For multi-channel audio, this is the channel number + corresponding to the recognized result for the audio from + that channel. For ``audio_channel_count`` = ``N``, its + output values can range from ``1`` to ``N``. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives: MutableSequence["SpeechRecognitionAlternative"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SpeechRecognitionAlternative", + ) + is_final: bool = proto.Field( + proto.BOOL, + number=2, + ) + stability: float = proto.Field( + proto.FLOAT, + number=3, + ) + result_end_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + channel_tag: int = proto.Field( + proto.INT32, + number=5, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + + +class StreamingRecognizeResponse(proto.Message): + r"""``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 then no messages are + streamed back to the client. + + Here are some examples of ``StreamingRecognizeResponse``\ s 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``. + + Attributes: + results (MutableSequence[google.cloud.speech_v2.types.StreamingRecognitionResult]): + This repeated list contains zero or more results that + correspond to consecutive portions of the audio currently + being processed. It contains zero or one + [is_final][google.cloud.speech.v2.StreamingRecognitionResult.is_final]=\ ``true`` + result (the newly settled portion), followed by zero or more + [is_final][google.cloud.speech.v2.StreamingRecognitionResult.is_final]=\ ``false`` + results (the interim results). + speech_event_type (google.cloud.speech_v2.types.StreamingRecognizeResponse.SpeechEventType): + Indicates the type of speech event. + speech_event_offset (google.protobuf.duration_pb2.Duration): + Time offset between the beginning of the + audio and event emission. + metadata (google.cloud.speech_v2.types.RecognitionResponseMetadata): + Metadata about the recognition. + """ + + class SpeechEventType(proto.Enum): + r"""Indicates the type of speech event. + + Values: + SPEECH_EVENT_TYPE_UNSPECIFIED (0): + No speech event specified. + END_OF_SINGLE_UTTERANCE (1): + This event indicates that the server has detected the end of + the user's speech utterance and expects no additional + speech. Therefore, the server will not process additional + audio and will close the gRPC bidirectional stream. This + event is only sent if there was a force cutoff due to + silence being detected early. This event is only available + through the ``latest_short`` + [model][google.cloud.speech.v2.Recognizer.model]. + SPEECH_ACTIVITY_BEGIN (2): + This event indicates that the server has detected the + beginning of human voice activity in the stream. This event + can be returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_END (3): + This event indicates that the server has detected the end of + human voice activity in the stream. This event can be + returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + """ + + SPEECH_EVENT_TYPE_UNSPECIFIED = 0 + END_OF_SINGLE_UTTERANCE = 1 + SPEECH_ACTIVITY_BEGIN = 2 + SPEECH_ACTIVITY_END = 3 + + results: MutableSequence["StreamingRecognitionResult"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="StreamingRecognitionResult", + ) + speech_event_type: SpeechEventType = proto.Field( + proto.ENUM, + number=3, + enum=SpeechEventType, + ) + speech_event_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + metadata: "RecognitionResponseMetadata" = proto.Field( + proto.MESSAGE, + number=5, + message="RecognitionResponseMetadata", + ) + + +class Config(proto.Message): + r"""Message representing the config for the Speech-to-Text API. This + includes an optional `KMS + key `__ + with which incoming data will be encrypted. + + Attributes: + name (str): + Output only. Identifier. The name of the config resource. + There is exactly one config resource per project per + location. The expected format is + ``projects/{project}/locations/{location}/config``. + kms_key_name (str): + Optional. An optional `KMS key + name `__ + that if present, will be used to encrypt Speech-to-Text + resources at-rest. Updating this key will not encrypt + existing resources using this key; only new resources will + be encrypted using this key. The expected format is + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + resource was modified. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=2, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class GetConfigRequest(proto.Message): + r"""Request message for the + [GetConfig][google.cloud.speech.v2.Speech.GetConfig] method. + + Attributes: + name (str): + Required. The name of the config to retrieve. There is + exactly one config resource per project per location. The + expected format is + ``projects/{project}/locations/{location}/config``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateConfigRequest(proto.Message): + r"""Request message for the + [UpdateConfig][google.cloud.speech.v2.Speech.UpdateConfig] method. + + Attributes: + config (google.cloud.speech_v2.types.Config): + Required. The config to update. + + The config's ``name`` field is used to identify the config + to be updated. The expected format is + ``projects/{project}/locations/{location}/config``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + """ + + config: "Config" = proto.Field( + proto.MESSAGE, + number=1, + message="Config", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CustomClass(proto.Message): + r"""CustomClass for biasing in speech recognition. Used to define + a set of words or phrases that represents a common concept or + theme likely to appear in your audio, for example a list of + passenger ship names. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + CustomClass. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}``. + uid (str): + Output only. System-assigned unique + identifier for the CustomClass. + display_name (str): + Optional. User-settable, human-readable name + for the CustomClass. Must be 63 characters or + less. + items (MutableSequence[google.cloud.speech_v2.types.CustomClass.ClassItem]): + A collection of class items. + state (google.cloud.speech_v2.types.CustomClass.State): + Output only. The CustomClass lifecycle state. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + resource was modified. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this resource + was requested for deletion. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this resource + will be purged. + annotations (MutableMapping[str, str]): + Optional. 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. + 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. + reconciling (bool): + Output only. Whether or not this CustomClass + is in the process of being updated. + kms_key_name (str): + Output only. The `KMS key + name `__ + with which the CustomClass 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 `__ + with which the CustomClass is encrypted. The expected format + is + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}``. + """ + + 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, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + items: MutableSequence[ClassItem] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=ClassItem, + ) + state: State = proto.Field( + proto.ENUM, + number=15, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=12, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=13, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +class PhraseSet(proto.Message): + r"""PhraseSet for biasing in speech recognition. A PhraseSet is + used to provide "hints" to the speech recognizer to favor + specific words and phrases in the results. + + Attributes: + name (str): + Output only. Identifier. The resource name of the PhraseSet. + Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}``. + uid (str): + Output only. System-assigned unique + identifier for the PhraseSet. + phrases (MutableSequence[google.cloud.speech_v2.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. Valid + ``boost`` values are 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. + display_name (str): + User-settable, human-readable name for the + PhraseSet. Must be 63 characters or less. + state (google.cloud.speech_v2.types.PhraseSet.State): + Output only. The PhraseSet lifecycle state. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + resource was modified. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this resource + was requested for deletion. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this resource + will be purged. + annotations (MutableMapping[str, str]): + 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. + 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. + reconciling (bool): + Output only. Whether or not this PhraseSet is + in the process of being updated. + kms_key_name (str): + Output only. The `KMS key + name `__ + with which 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 `__ + with which the PhraseSet is encrypted. The expected format + is + ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}``. + """ + + class State(proto.Enum): + r"""Set of states that define the lifecycle of a PhraseSet. + + 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 PhraseSet has been deleted. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 2 + DELETED = 4 + + class Phrase(proto.Message): + r"""A Phrase contains 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. + + List items can also include CustomClass references containing + groups of words that represent common concepts that occur in + natural language. + + 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 values would correspond to anti-biasing. + Anti-biasing is not enabled, so negative boost + values will return an error. Boost values must + be between 0 and 20. Any values outside that + range will return an error. 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, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + phrases: MutableSequence[Phrase] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Phrase, + ) + boost: float = proto.Field( + proto.FLOAT, + number=4, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + state: State = proto.Field( + proto.ENUM, + number=15, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=12, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=13, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +class CreateCustomClassRequest(proto.Message): + r"""Request message for the + [CreateCustomClass][google.cloud.speech.v2.Speech.CreateCustomClass] + method. + + Attributes: + custom_class (google.cloud.speech_v2.types.CustomClass): + Required. The CustomClass to create. + validate_only (bool): + If set, validate the request and preview the + CustomClass, but do not actually create it. + custom_class_id (str): + The ID to use for the CustomClass, which will become the + final component of the CustomClass's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + parent (str): + Required. The project and location where this CustomClass + will be created. The expected format is + ``projects/{project}/locations/{location}``. + """ + + custom_class: "CustomClass" = proto.Field( + proto.MESSAGE, + number=1, + message="CustomClass", + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + custom_class_id: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListCustomClassesRequest(proto.Message): + r"""Request message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + + Attributes: + parent (str): + Required. The project and location of CustomClass resources + to list. The expected format is + ``projects/{project}/locations/{location}``. + page_size (int): + Number of results per requests. A valid page_size ranges + from 0 to 100 inclusive. If the page_size is zero or + unspecified, a page size of 5 will be chosen. If the page + size exceeds 100, it will be coerced down to 100. Note that + a call might return fewer results than the requested page + size. + page_token (str): + A page token, received from a previous + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + must match the call that provided the page token. + show_deleted (bool): + Whether, or not, to show resources that have + been deleted. + """ + + 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, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListCustomClassesResponse(proto.Message): + r"""Response message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + + Attributes: + custom_classes (MutableSequence[google.cloud.speech_v2.types.CustomClass]): + The list of requested CustomClasses. + next_page_token (str): + A token, which can be sent as + [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. This token expires after 72 hours. + """ + + @property + def raw_page(self): + return self + + custom_classes: MutableSequence["CustomClass"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="CustomClass", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetCustomClassRequest(proto.Message): + r"""Request message for the + [GetCustomClass][google.cloud.speech.v2.Speech.GetCustomClass] + method. + + Attributes: + name (str): + Required. The name of the CustomClass to retrieve. The + expected format is + ``projects/{project}/locations/{location}/customClasses/{custom_class}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateCustomClassRequest(proto.Message): + r"""Request message for the + [UpdateCustomClass][google.cloud.speech.v2.Speech.UpdateCustomClass] + method. + + Attributes: + custom_class (google.cloud.speech_v2.types.CustomClass): + Required. The CustomClass to update. + + The CustomClass's ``name`` field is used to identify the + CustomClass to update. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If empty, + all fields are considered for update. + validate_only (bool): + If set, validate the request and preview the + updated CustomClass, but do not actually update + it. + """ + + custom_class: "CustomClass" = proto.Field( + proto.MESSAGE, + number=1, + message="CustomClass", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteCustomClassRequest(proto.Message): + r"""Request message for the + [DeleteCustomClass][google.cloud.speech.v2.Speech.DeleteCustomClass] + method. + + Attributes: + name (str): + Required. The name of the CustomClass to delete. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + validate_only (bool): + If set, validate the request and preview the + deleted CustomClass, but do not actually delete + it. + allow_missing (bool): + If set to true, and the CustomClass is not + found, the request will succeed and be a no-op + (no Operation is recorded in this case). + etag (str): + 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. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UndeleteCustomClassRequest(proto.Message): + r"""Request message for the + [UndeleteCustomClass][google.cloud.speech.v2.Speech.UndeleteCustomClass] + method. + + Attributes: + name (str): + Required. The name of the CustomClass to undelete. Format: + ``projects/{project}/locations/{location}/customClasses/{custom_class}`` + validate_only (bool): + If set, validate the request and preview the + undeleted CustomClass, but do not actually + undelete it. + etag (str): + 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. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CreatePhraseSetRequest(proto.Message): + r"""Request message for the + [CreatePhraseSet][google.cloud.speech.v2.Speech.CreatePhraseSet] + method. + + Attributes: + phrase_set (google.cloud.speech_v2.types.PhraseSet): + Required. The PhraseSet to create. + validate_only (bool): + If set, validate the request and preview the + PhraseSet, but do not actually create it. + phrase_set_id (str): + The ID to use for the PhraseSet, which will become the final + component of the PhraseSet's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + parent (str): + Required. The project and location where this PhraseSet will + be created. The expected format is + ``projects/{project}/locations/{location}``. + """ + + phrase_set: "PhraseSet" = proto.Field( + proto.MESSAGE, + number=1, + message="PhraseSet", + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + phrase_set_id: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPhraseSetsRequest(proto.Message): + r"""Request message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + + Attributes: + parent (str): + Required. The project and location of PhraseSet resources to + list. The expected format is + ``projects/{project}/locations/{location}``. + page_size (int): + The maximum number of PhraseSets to return. + The service may return fewer than this value. If + unspecified, at most 5 PhraseSets will be + returned. The maximum value is 100; values above + 100 will be coerced to 100. + page_token (str): + A page token, received from a previous + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + must match the call that provided the page token. + show_deleted (bool): + Whether, or not, to show resources that have + been deleted. + """ + + 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, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListPhraseSetsResponse(proto.Message): + r"""Response message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + + Attributes: + phrase_sets (MutableSequence[google.cloud.speech_v2.types.PhraseSet]): + The list of requested PhraseSets. + next_page_token (str): + A token, which can be sent as + [page_token][google.cloud.speech.v2.ListPhraseSetsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. This token expires after 72 hours. + """ + + @property + def raw_page(self): + return self + + phrase_sets: MutableSequence["PhraseSet"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="PhraseSet", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPhraseSetRequest(proto.Message): + r"""Request message for the + [GetPhraseSet][google.cloud.speech.v2.Speech.GetPhraseSet] method. + + Attributes: + name (str): + Required. The name of the PhraseSet to retrieve. The + expected format is + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePhraseSetRequest(proto.Message): + r"""Request message for the + [UpdatePhraseSet][google.cloud.speech.v2.Speech.UpdatePhraseSet] + method. + + Attributes: + phrase_set (google.cloud.speech_v2.types.PhraseSet): + Required. The PhraseSet to update. + + The PhraseSet's ``name`` field is used to identify the + PhraseSet to update. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to update. If empty, all non-default + valued fields are considered for update. Use ``*`` to update + the entire PhraseSet resource. + validate_only (bool): + If set, validate the request and preview the + updated PhraseSet, but do not actually update + it. + """ + + phrase_set: "PhraseSet" = proto.Field( + proto.MESSAGE, + number=1, + message="PhraseSet", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeletePhraseSetRequest(proto.Message): + r"""Request message for the + [DeletePhraseSet][google.cloud.speech.v2.Speech.DeletePhraseSet] + method. + + Attributes: + name (str): + Required. The name of the PhraseSet to delete. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + validate_only (bool): + If set, validate the request and preview the + deleted PhraseSet, but do not actually delete + it. + allow_missing (bool): + If set to true, and the PhraseSet is not + found, the request will succeed and be a no-op + (no Operation is recorded in this case). + etag (str): + 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. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UndeletePhraseSetRequest(proto.Message): + r"""Request message for the + [UndeletePhraseSet][google.cloud.speech.v2.Speech.UndeletePhraseSet] + method. + + Attributes: + name (str): + Required. The name of the PhraseSet to undelete. Format: + ``projects/{project}/locations/{location}/phraseSets/{phrase_set}`` + validate_only (bool): + If set, validate the request and preview the + undeleted PhraseSet, but do not actually + undelete it. + etag (str): + 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. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/locations_metadata.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/locations_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..d28a125849dcf48060b1f22be115e90a569c7abf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/speech_v2/types/locations_metadata.py @@ -0,0 +1,170 @@ +# -*- 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 + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.speech.v2", + manifest={ + "ModelFeature", + "ModelFeatures", + "ModelMetadata", + "LanguageMetadata", + "AccessMetadata", + "LocationsMetadata", + }, +) + + +class ModelFeature(proto.Message): + r"""Represents a singular feature of a model. If the feature is + ``recognizer``, the release_state of the feature represents the + release_state of the model + + Attributes: + feature (str): + The name of the feature (Note: the feature can be + ``recognizer``) + release_state (str): + The release state of the feature + """ + + feature: str = proto.Field( + proto.STRING, + number=1, + ) + release_state: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ModelFeatures(proto.Message): + r"""Represents the collection of features belonging to a model + + Attributes: + model_feature (MutableSequence[google.cloud.speech_v2.types.ModelFeature]): + Repeated field that contains all features of + the model + """ + + model_feature: MutableSequence["ModelFeature"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ModelFeature", + ) + + +class ModelMetadata(proto.Message): + r"""The metadata about the models in a given region for a + specific locale. Currently this is just the features of the + model + + Attributes: + model_features (MutableMapping[str, google.cloud.speech_v2.types.ModelFeatures]): + Map of the model name -> features of that + model + """ + + model_features: MutableMapping[str, "ModelFeatures"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="ModelFeatures", + ) + + +class LanguageMetadata(proto.Message): + r"""The metadata about locales available in a given region. + Currently this is just the models that are available for each + locale + + Attributes: + models (MutableMapping[str, google.cloud.speech_v2.types.ModelMetadata]): + Map of locale (language code) -> models + """ + + models: MutableMapping[str, "ModelMetadata"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="ModelMetadata", + ) + + +class AccessMetadata(proto.Message): + r"""The access metadata for a particular region. This can be + applied if the org policy for the given project disallows a + particular region. + + Attributes: + constraint_type (google.cloud.speech_v2.types.AccessMetadata.ConstraintType): + Describes the different types of constraints + that are applied. + """ + + class ConstraintType(proto.Enum): + r"""Describes the different types of constraints that can be + applied on a region. + + Values: + CONSTRAINT_TYPE_UNSPECIFIED (0): + Unspecified constraint applied. + RESOURCE_LOCATIONS_ORG_POLICY_CREATE_CONSTRAINT (1): + The project's org policy disallows the given + region. + """ + + CONSTRAINT_TYPE_UNSPECIFIED = 0 + RESOURCE_LOCATIONS_ORG_POLICY_CREATE_CONSTRAINT = 1 + + constraint_type: ConstraintType = proto.Field( + proto.ENUM, + number=1, + enum=ConstraintType, + ) + + +class LocationsMetadata(proto.Message): + r"""Main metadata for the Locations API for STT V2. Currently + this is just the metadata about locales, models, and features + + Attributes: + languages (google.cloud.speech_v2.types.LanguageMetadata): + Information about available locales, models, + and features represented in the hierarchical + structure of locales -> models -> features + access_metadata (google.cloud.speech_v2.types.AccessMetadata): + Information about access metadata for the + region and given project. + """ + + languages: "LanguageMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="LanguageMetadata", + ) + access_metadata: "AccessMetadata" = proto.Field( + proto.MESSAGE, + number=2, + message="AccessMetadata", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a387d1271f937d0138b3145289f498db6dd1b2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/__init__.py @@ -0,0 +1,20 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .sqlalchemy_spanner import SpannerDialect + +from .version import __version__ + + +__all__ = (SpannerDialect, __version__) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/_opentelemetry_tracing.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/_opentelemetry_tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..960442c57d09fa5b4c98edb2cd80bcc8d47faa27 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/_opentelemetry_tracing.py @@ -0,0 +1,74 @@ +# Copyright 2021 Google LLC All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Manages OpenTelemetry trace creation and handling""" + +import collections +import os + +from contextlib import contextmanager + +from google.api_core.exceptions import GoogleAPICallError +from google.cloud.spanner_v1 import SpannerClient + +try: + from opentelemetry import trace + from opentelemetry.trace.status import Status, StatusCode + + HAS_OPENTELEMETRY_INSTALLED = True + tracer = trace.get_tracer(__name__) +except ImportError: + HAS_OPENTELEMETRY_INSTALLED = False + tracer = None + + +@contextmanager +def trace_call(name, extra_attributes=None): + if not HAS_OPENTELEMETRY_INSTALLED: + # Empty context manager. Users will have to check if the generated value + # is None or a span + yield None + return + + # Set base attributes that we know for every trace created + attributes = { + "db.type": "spanner", + "db.engine": "sqlalchemy_spanner", + "db.url": SpannerClient.DEFAULT_ENDPOINT, + "net.host.name": SpannerClient.DEFAULT_ENDPOINT, + } + + if extra_attributes: + if os.environ.get("SQLALCHEMY_SPANNER_TRACE_HIDE_QUERY_PARAMETERS"): + extra_attributes.pop("db.params", None) + + # Stringify "db.params" sequence values before sending to OpenTelemetry, + # otherwise OpenTelemetry may log a Warning if types differ. + if isinstance(extra_attributes, dict): + for k, v in extra_attributes.items(): + if k == "db.params" and isinstance(v, collections.abc.Sequence): + extra_attributes[k] = [str(e) for e in v] + + attributes.update(extra_attributes) + + with tracer.start_as_current_span( + name, kind=trace.SpanKind.CLIENT, attributes=attributes + ) as span: + try: + yield span + except GoogleAPICallError as error: + span.set_status(Status(StatusCode.ERROR)) + span.record_exception(error) + raise + span.set_status(Status(StatusCode.OK)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/dml.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/dml.py new file mode 100644 index 0000000000000000000000000000000000000000..311aee0db487dea1450929adaecf60384c85dfc8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/dml.py @@ -0,0 +1,26 @@ +# Copyright 2024 Google LLC All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from sqlalchemy import Insert, insert +from sqlalchemy.sql._typing import _DMLTableArgument + + +def insert_or_update(table: _DMLTableArgument) -> Insert: + """Construct a Spanner-specific insert-or-update statement.""" + return insert(table).prefix_with("OR UPDATE") + + +def insert_or_ignore(table: _DMLTableArgument) -> Insert: + """Construct a Spanner-specific insert-or-ignore statement.""" + return insert(table).prefix_with("OR IGNORE") diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/provision.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/provision.py new file mode 100644 index 0000000000000000000000000000000000000000..f56aaccf70b50de4283d0e362c8d784dd3947c68 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/provision.py @@ -0,0 +1,20 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from sqlalchemy.testing.provision import temp_table_keyword_args + + +@temp_table_keyword_args.for_db("spanner") # pragma: no cover +def _spanner_temp_table_keyword_args(cfg, eng): + return {"prefixes": ["TEMPORARY"]} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/requirements.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..04d21dc8d0955d4650828ac2d6aaaeb863ff8a1e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/requirements.py @@ -0,0 +1,119 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from sqlalchemy.testing import exclusions +from sqlalchemy.testing.requirements import SuiteRequirements +from sqlalchemy.testing.exclusions import against, only_on + + +class Requirements(SuiteRequirements): # pragma: no cover + @property + def json_type(self): + return exclusions.open() + + @property + def computed_columns(self): + return exclusions.open() + + @property + def computed_columns_stored(self): + return exclusions.open() + + @property + def sane_rowcount(self): + return exclusions.closed() + + @property + def sane_multi_rowcount(self): + return exclusions.closed() + + @property + def foreign_key_constraint_name_reflection(self): + return exclusions.open() + + @property + def schema_reflection(self): + return exclusions.open() + + @property + def array_type(self): + return only_on([lambda config: against(config, "postgresql")]) + + @property + def uuid_data_type(self): + """Return databases that support the UUID datatype.""" + return only_on(("postgresql >= 8.3", "mariadb >= 10.7.0")) + + @property + def implicitly_named_constraints(self): + return exclusions.open() + + @property + def autocommit(self): + return exclusions.open() + + @property + def order_by_collation(self): + return exclusions.open() + + @property + def implements_get_lastrowid(self): + return exclusions.closed() + + @property + def ctes(self): + return exclusions.open() + + @property + def isolation_level(self): + return exclusions.open() + + @property + def sequences(self): + return exclusions.open() + + @property + def temporary_tables(self): + """Target database supports temporary tables.""" + return exclusions.closed() + + def get_order_by_collation(self, _): + """Get the default collation name. + + Returns: + str: Collation name. + """ + return '"unicode"' + + def get_isolation_levels(self, _): + """Get isolation levels supported by the dialect. + + Returns: + dict: isolation levels description. + """ + return { + "default": "SERIALIZABLE", + "supported": ["SERIALIZABLE", "REPEATABLE READ", "AUTOCOMMIT"], + } + + @property + def precision_numerics_enotation_large(self): + """target backend supports Decimal() objects using E notation + to represent very large values.""" + return exclusions.open() + + @property + def views(self): + """Target database must support VIEWs.""" + return exclusions.open() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/sqlalchemy_spanner.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/sqlalchemy_spanner.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ca59bd07123b8274402ab877a3b6ffb440e098 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/sqlalchemy_spanner.py @@ -0,0 +1,1926 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import base64 + +import re + +from alembic.ddl.base import ( + ColumnNullable, + ColumnType, + alter_column, + alter_table, + format_server_default, + format_type, +) +from google.api_core.client_options import ClientOptions +from google.auth.credentials import AnonymousCredentials +from google.cloud.spanner_v1 import Client, TransactionOptions +from sqlalchemy.exc import NoSuchTableError +from sqlalchemy.sql import elements +from sqlalchemy import ForeignKeyConstraint, types, TypeDecorator, PickleType +from sqlalchemy.engine.base import Engine +from sqlalchemy.engine.default import DefaultDialect, DefaultExecutionContext +from sqlalchemy.event import listens_for +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.pool import Pool +from sqlalchemy.sql.compiler import ( + selectable, + DDLCompiler, + GenericTypeCompiler, + IdentifierPreparer, + SQLCompiler, + OPERATORS, + RESERVED_WORDS, +) +from sqlalchemy.sql.default_comparator import operator_lookup +from sqlalchemy.sql.operators import json_getitem_op +from sqlalchemy.sql import expression + +from google.cloud.spanner_v1.data_types import JsonObject +from google.cloud import spanner_dbapi +from google.cloud.sqlalchemy_spanner._opentelemetry_tracing import trace_call +from google.cloud.sqlalchemy_spanner import version as sqlalchemy_spanner_version +import sqlalchemy + +USING_SQLACLCHEMY_20 = False +if sqlalchemy.__version__.split(".")[0] == "2": + USING_SQLACLCHEMY_20 = True + +if USING_SQLACLCHEMY_20: + from sqlalchemy.engine.reflection import ObjectKind + + +@listens_for(Pool, "reset") +def reset_connection(dbapi_conn, connection_record, reset_state=None): + """An event of returning a connection back to a pool.""" + if hasattr(dbapi_conn, "connection"): + dbapi_conn = dbapi_conn.connection + if isinstance(dbapi_conn, spanner_dbapi.Connection): + if dbapi_conn.inside_transaction: + dbapi_conn.rollback() + + dbapi_conn.staleness = None + dbapi_conn.read_only = False + + +# register a method to get a single value of a JSON object +OPERATORS[json_getitem_op] = operator_lookup["json_getitem_op"] + + +# PickleType that can be used with Spanner. +# Binary values are automatically encoded/decoded to/from base64. +# Usage: +# class User(Base): +# __tablename__ = 'users' +# +# user_id = Column(Integer, primary_key=True) +# username = Column(String(50), nullable=False) +# preferences = Column(PickleType(impl=SpannerPickleType)) +class SpannerPickleType(TypeDecorator): + impl = PickleType + + def bind_processor(self, dialect): + def process(value): + if value is None: + return None + return base64.standard_b64encode(value) + + return process + + def result_processor(self, dialect, coltype): + def process(value): + if value is None: + return None + return base64.standard_b64decode(value) + + return process + + +# Spanner-to-SQLAlchemy types map +_type_map = { + "BOOL": types.Boolean, + "BYTES": types.LargeBinary, + "DATE": types.DATE, + "DATETIME": types.DATETIME, + "FLOAT32": types.REAL, + "FLOAT64": types.Float, + "INT64": types.BIGINT, + "NUMERIC": types.NUMERIC(precision=38, scale=9), + "STRING": types.String, + "TIME": types.TIME, + "TIMESTAMP": types.TIMESTAMP, + "ARRAY": types.ARRAY, + "JSON": types.JSON, +} + + +_type_map_inv = { + types.Boolean: "BOOL", + types.BINARY: "BYTES(MAX)", + types.LargeBinary: "BYTES(MAX)", + types.DATE: "DATE", + types.DATETIME: "DATETIME", + types.REAL: "FLOAT32", + types.Float: "FLOAT64", + types.BIGINT: "INT64", + types.DECIMAL: "NUMERIC", + types.String: "STRING", + types.TIME: "TIME", + types.TIMESTAMP: "TIMESTAMP", + types.Integer: "INT64", + types.NullType: "INT64", +} + +_compound_keywords = { + selectable.CompoundSelect.UNION: "UNION DISTINCT", + selectable.CompoundSelect.UNION_ALL: "UNION ALL", + selectable.CompoundSelect.EXCEPT: "EXCEPT DISTINCT", + selectable.CompoundSelect.EXCEPT_ALL: "EXCEPT ALL", + selectable.CompoundSelect.INTERSECT: "INTERSECT DISTINCT", + selectable.CompoundSelect.INTERSECT_ALL: "INTERSECT ALL", +} + +_max_size = 2621440 + + +def int_from_size(size_str): + """Convert a string column length to an integer value. + + Args: + size_str (str): The column length or the 'MAX' keyword. + + Returns: + int: The column length value. + """ + return _max_size if size_str == "MAX" else int(size_str) + + +def engine_to_connection(function): + """ + Decorator to initiate a connection to a + database in case of an engine-related use. + """ + + def wrapper(self, connection, *args, **kwargs): + """ + Args: + connection (Union[ + sqlalchemy.engine.base.Connection, + sqlalchemy.engine.Engine + ]): + SQLAlchemy connection or engine object. + """ + if isinstance(connection, Engine): + connection = connection.connect() + + return function(self, connection, *args, **kwargs) + + return wrapper + + +class SpannerExecutionContext(DefaultExecutionContext): + def pre_exec(self): + """ + Apply execution options to the DB API connection before + executing the next SQL operation. + """ + super(SpannerExecutionContext, self).pre_exec() + + read_only = self.execution_options.get("read_only") + if read_only is not None: + self._dbapi_connection.connection.read_only = read_only + + staleness = self.execution_options.get("staleness") + if staleness is not None: + self._dbapi_connection.connection.staleness = staleness + + priority = self.execution_options.get("request_priority") + if priority is not None: + self._dbapi_connection.connection.request_priority = priority + + transaction_tag = self.execution_options.get("transaction_tag") + if transaction_tag: + self._dbapi_connection.connection.transaction_tag = transaction_tag + + request_tag = self.execution_options.get("request_tag") + if request_tag: + self.cursor.request_tag = request_tag + + ignore_transaction_warnings = self.execution_options.get( + "ignore_transaction_warnings" + ) + if ignore_transaction_warnings is not None: + conn = self._dbapi_connection.connection + if conn is not None and hasattr(conn, "_connection_variables"): + conn._connection_variables[ + "ignore_transaction_warnings" + ] = ignore_transaction_warnings + + def fire_sequence(self, seq, type_): + """Builds a statement for fetching next value of the sequence.""" + return self._execute_scalar( + ( + "SELECT GET_NEXT_SEQUENCE_VALUE(SEQUENCE %s)" + % self.identifier_preparer.format_sequence(seq) + ), + type_, + ) + + +class SpannerIdentifierPreparer(IdentifierPreparer): + """Identifiers compiler. + + In Cloud Spanner backticks "`" are used for keywords escaping. + """ + + reserved_words = RESERVED_WORDS.copy() + reserved_words.update(spanner_dbapi.parse_utils.SPANNER_RESERVED_KEYWORDS) + reserved_words_lc = set(map(str.lower, reserved_words)) + + def __init__(self, dialect): + super(SpannerIdentifierPreparer, self).__init__( + dialect, initial_quote="`", final_quote="`" + ) + + def _requires_quotes(self, value): + """Return True if the given identifier requires quoting.""" + lc_value = value.lower() + if lc_value == '"unicode"': # don't escape default Spanner colation + return False + + return ( + lc_value in self.reserved_words_lc + or value[0] in self.illegal_initial_characters + or not self.legal_characters.match(str(value)) + or (lc_value != value) + ) + + +class SpannerSQLCompiler(SQLCompiler): + """Spanner SQL statements compiler.""" + + compound_keywords = _compound_keywords + + def __init__(self, *args, **kwargs): + self.tablealiases = {} + super().__init__(*args, **kwargs) + + def get_from_hint_text(self, _, text): + """Return a hint text. + + Overriden to avoid adding square brackets to the hint text. + + Args: + text (str): The hint text. + """ + return text + + def visit_now_func(self, func, **kwargs): + return "current_timestamp" + + def visit_empty_set_expr(self, type_, **kw): + """Return an empty set expression of the given type. + + Args: + type_ (sqlalchemy.sql.sqltypes.SchemaType): + A SQLAlchemy data type. + + Returns: + str: A query to select an empty set of the given type. + """ + return "SELECT CAST(1 AS {}) FROM (SELECT 1) WHERE 1 != 1".format( + _type_map_inv[type(type_[0])] + ) + + def visit_like_op_binary(self, binary, operator, **kw): + """Build a LIKE clause.""" + if binary.modifiers.get("escape", None): + raise NotImplementedError("ESCAPE keyword is not supported by Spanner") + + # TODO: use ternary here, not "and"/ "or" + return "%s LIKE %s" % ( + binary.left._compiler_dispatch(self, **kw), + binary.right._compiler_dispatch(self, **kw), + ) + + def _generate_generic_binary(self, binary, opstring, eager_grouping=False, **kw): + """The method is overriden to process JSON data type cases.""" + _in_binary = kw.get("_in_binary", False) + + kw["_in_binary"] = True + + if isinstance(opstring, str): + text = ( + binary.left._compiler_dispatch( + self, eager_grouping=eager_grouping, **kw + ) + + opstring + + binary.right._compiler_dispatch( + self, eager_grouping=eager_grouping, **kw + ) + ) + if _in_binary and eager_grouping: + text = "(%s)" % text + else: + # got JSON data + right_value = getattr( + binary.right, "value", None + ) or binary.right._compiler_dispatch( + self, eager_grouping=eager_grouping, **kw + ) + + text = ( + binary.left._compiler_dispatch( + self, eager_grouping=eager_grouping, **kw + ) + + """, "$.""" + + str(right_value) + + '"' + ) + text = "JSON_VALUE(%s)" % text + + return text + + def visit_json_path_getitem_op_binary(self, binary, operator, **kw): + """Build a JSON_VALUE() function call.""" + expr = """JSON_VALUE(%s, "$.%s")""" + + return expr % ( + self.process(binary.left, **kw), + self.process(binary.right, **kw), + ) + + def render_literal_value(self, value, type_): + """Render the value of a bind parameter as a quoted literal. + + This is used for statement sections that do not accept bind parameters + on the target driver/database. + + This should be implemented by subclasses using the quoting services + of the DBAPI. + + Cloud spanner supports prefixed backslash to escape non-alphanumeric characters + in string. Override the method to add additional escape before using it to + generate a SQL statement. + """ + if value is None and not type_.should_evaluate_none: + # issue #10535 - handle NULL in the compiler without placing + # this onto each type, except for "evaluate None" types + # (e.g. JSON) + return self.process(elements.Null._instance()) + + raw = ["\\", "'", '"', "\n", "\t", "\r"] + if isinstance(value, str) and any(single in value for single in raw): + value = 'r"""{}"""'.format(value) + return value + else: + processor = type_._cached_literal_processor(self.dialect) + if processor: + return processor(value) + else: + raise NotImplementedError( + "Don't know how to literal-quote value %r" % value + ) + + def limit_clause(self, select, **kw): + """Build LIMIT-OFFSET clause. + + Spanner doesn't support using OFFSET without a LIMIT + clause. It also doesn't support negative LIMITs, while + SQLAlchemy support both. + + The method builds LIMIT-OFFSET clauses as usual, with + only difference: when OFFSET is used without an explicit + LIMIT, the dialect compiles a statement with a LIMIT + set to the biggest integer value. + + Args: + (sqlalchemy.sql.selectable.Select): Select clause object. + + Returns: + str: LIMIT-OFFSET clause. + """ + text = "" + if select._limit_clause is not None: + text += "\n LIMIT " + self.process(select._limit_clause, **kw) + if select._offset_clause is not None: + if select._limit_clause is None: + text += f"\n LIMIT {9223372036854775807-select._offset}" + text += " OFFSET " + self.process(select._offset_clause, **kw) + return text + + def returning_clause(self, stmt, returning_cols, **kw): + # Set the spanner_is_returning flag which is passed to visit_column. + columns = [ + self._label_select_column( + None, c, True, False, {"spanner_is_returning": True} + ) + for c in expression._select_iterables( + filter( + lambda col: not col.dialect_options.get("spanner", {}).get( + "exclude_from_returning", False + ), + returning_cols, + ) + ) + ] + + return "THEN RETURN " + ", ".join(columns) + + def visit_sequence(self, seq, **kw): + """Builds a statement for fetching next value of the sequence.""" + return " GET_NEXT_SEQUENCE_VALUE(SEQUENCE %s)" % self.preparer.format_sequence( + seq + ) + + def visit_table(self, table, spanner_aliased=False, iscrud=False, **kwargs): + """Produces the table name. + + Schema names are not allowed in Spanner SELECT statements. We + need to avoid generating SQL like + + SELECT schema.tbl.id + FROM schema.tbl + + To do so, we alias the table in order to produce SQL like: + + SELECT tbl_1.id, tbl_1.col + FROM schema.tbl AS tbl_1 + + And do similar for UPDATE and DELETE statements. + + This closely mirrors the mssql dialect which also avoids + schema-qualified columns in SELECTs, although the behaviour is + currently behind a deprecated 'legacy_schema_aliasing' flag. + """ + if spanner_aliased is table or self.isinsert: + return super().visit_table(table, **kwargs) + + # Add an alias for schema-qualified tables. + # Tables in the default schema are not aliased and follow the + # standard SQLAlchemy code path. + alias = self._schema_aliased_table(table) + if alias is not None: + return self.process(alias, spanner_aliased=table, **kwargs) + else: + return super().visit_table(table, **kwargs) + + def visit_alias(self, alias, **kw): + """Produces alias statements.""" + # translate for schema-qualified table aliases + kw["spanner_aliased"] = alias.element + return super().visit_alias(alias, **kw) + + def visit_column( + self, column, add_to_result_map=None, spanner_is_returning=False, **kw + ): + """Produces column expressions. + + In tandem with visit_table, replaces schema-qualified column + names with column names qualified against an alias. + """ + if column.table is not None and not self.isinsert or self.is_subquery(): + # translate for schema-qualified table aliases + t = self._schema_aliased_table(column.table) + if t is not None: + converted = elements._corresponding_column_or_error(t, column) + if add_to_result_map is not None: + add_to_result_map( + column.name, + column.name, + (column, column.name, column.key), + column.type, + ) + + return super().visit_column(converted, **kw) + if spanner_is_returning: + # Set include_table=False because although table names are + # allowed in RETURNING clauses, schema names are not. We + # can't use the same aliasing trick above that we use with + # other statements, because INSERT statements don't result + # in visit_table calls and INSERT table names can't be + # aliased. Statements like: + # + # INSERT INTO table (id, name) + # SELECT id, name FROM another_table + # THEN RETURN another_table.id + # + # aren't legal, so the columns remain unambiguous when not + # qualified by table name. + kw["include_table"] = False + + return super().visit_column(column, add_to_result_map=add_to_result_map, **kw) + + def _schema_aliased_table(self, table): + """Creates an alias for the table if it is schema-qualified. + + If the table is schema-qualified, returns an alias for the + table and caches the alias for future references to the + table. If the table is not schema-qualified, returns None. + """ + if getattr(table, "schema", None) is not None: + if table not in self.tablealiases: + self.tablealiases[table] = table.alias() + return self.tablealiases[table] + else: + return None + + +class SpannerDDLCompiler(DDLCompiler): + """Spanner DDL statements compiler.""" + + def get_column_specification(self, column, **kwargs): + """Build new column specifications. + + Overridden to move the NOT NULL statement to front + of a computed column expression definitions. + """ + colspec = ( + self.preparer.format_column(column) + + " " + + self.dialect.type_compiler.process(column.type, type_expression=column) + ) + if not column.nullable: + colspec += " NOT NULL" + + has_identity = ( + hasattr(column, "identity") + and column.identity is not None + and self.dialect.supports_identity_columns + ) + default = self.get_column_default_string(column) + + if ( + column.primary_key + and column is column.table._autoincrement_column + and not has_identity + and default is None + ): + if ( + hasattr(self.dialect, "use_auto_increment") + and self.dialect.use_auto_increment + ): + colspec += " AUTO_INCREMENT" + else: + sequence_kind = getattr( + self.dialect, "default_sequence_kind", "BIT_REVERSED_POSITIVE" + ) + colspec += " GENERATED BY DEFAULT AS IDENTITY (%s)" % sequence_kind + elif has_identity: + colspec += " " + self.process(column.identity) + elif default is not None: + colspec += f" DEFAULT {default}" + elif hasattr(column, "computed") and column.computed is not None: + colspec += " " + self.process(column.computed) + + if column.dialect_options.get("spanner", {}).get( + "allow_commit_timestamp", False + ): + colspec += " OPTIONS (allow_commit_timestamp=true)" + + return colspec + + def get_column_default_string(self, column): + default = super().get_column_default_string(column) + if default is not None: + return f"({default})" + + return default + + def visit_computed_column(self, generated, **kw): + """Computed column operator.""" + text = "AS (%s) STORED" % self.sql_compiler.process( + generated.sqltext, include_table=False, literal_binds=True + ) + return text + + def visit_drop_table(self, drop_table, **kw): + """ + Cloud Spanner doesn't drop tables which have indexes + or foreign key constraints. This method builds several DDL + statements separated by semicolons to drop the indexes and + foreign keys constraints of the table before the DROP TABLE + statement. + + Args: + (sqlalchemy.schema.DropTable): DROP TABLE statement object. + + Returns: + str: + DDL statements separated by semicolons, which will + sequentially drop indexes, foreign keys constraints + and then the table itself. + """ + constrs = "" + for cons in drop_table.element.constraints: + if isinstance(cons, ForeignKeyConstraint) and cons.name: + effective_schema = self.preparer.schema_for_object(drop_table.element) + if effective_schema: + table = ( + f"{self.preparer.quote_schema(effective_schema)}" + "." + f"{self.preparer.quote(drop_table.element.name)}" + ) + else: + table = self.preparer.quote(drop_table.element.name) + constrs += "ALTER TABLE {table} DROP CONSTRAINT {constr};".format( + table=table, + constr=self.preparer.quote(cons.name), + ) + + indexes = "" + for index in drop_table.element.indexes: + indexes += "DROP INDEX {};".format(self.preparer.quote(index.name)) + + return indexes + constrs + super().visit_drop_table(drop_table) + + def visit_primary_key_constraint(self, constraint, **kw): + """Build primary key definition. + + Primary key in Spanner is defined outside of a table columns definition, see: + https://cloud.google.com/spanner/docs/getting-started/python#create_a_database + + The method returns None to omit primary key in a table columns definition. + """ + return None + + def visit_unique_constraint(self, constraint, **kw): + """Unique constraints in Spanner are defined with indexes: + https://cloud.google.com/spanner/docs/secondary-indexes#unique-indexes + + The method throws an exception to notify user that in + Spanner unique constraints are done with unique indexes. + """ + raise spanner_dbapi.exceptions.ProgrammingError( + "Spanner doesn't support direct UNIQUE constraints creation. " + "Create UNIQUE indexes instead." + ) + + def visit_foreign_key_constraint(self, constraint, **kw): + text = super().visit_foreign_key_constraint(constraint, **kw) + if constraint.dialect_options.get("spanner", {}).get("not_enforced", False): + text += " NOT ENFORCED" + return text + + def post_create_table(self, table): + """Build statements to be executed after CREATE TABLE. + + Includes "primary key" and "interleaved table" statements generation. + + Args: + table (sqlalchemy.schema.Table): Table to create. + + Returns: + str: primary key difinition to add to the table CREATE request. + """ + cols = [col.name for col in table.primary_key.columns] + post_cmds = " PRIMARY KEY ({})".format(", ".join(cols)) + + if "TEMPORARY" in table._prefixes: + raise NotImplementedError("Temporary tables are not supported.") + + if table.kwargs.get("spanner_interleave_in"): + post_cmds += ",\nINTERLEAVE IN PARENT {}".format( + table.kwargs["spanner_interleave_in"] + ) + + if table.kwargs.get("spanner_interleave_on_delete_cascade"): + post_cmds += " ON DELETE CASCADE" + + return post_cmds + + def visit_create_index( + self, create, include_schema=True, include_table_schema=True, **kw + ): + text = super().visit_create_index( + create, include_schema, include_table_schema, **kw + ) + index = create.element + if "spanner" in index.dialect_options: + options = index.dialect_options["spanner"] + if "storing" in options: + storing = options["storing"] + storing_columns = [ + index.table.c[col] if isinstance(col, str) else col + for col in storing + ] + text += " STORING (%s)" % ", ".join( + [self.preparer.quote(c.name) for c in storing_columns] + ) + + interleave_in = options.get("interleave_in") + if interleave_in is not None: + text += f", INTERLEAVE IN {self.preparer.quote(interleave_in)}" + + if options.get("null_filtered", False): + text = re.sub( + r"(^\s*CREATE\s+(?:UNIQUE\s+)?)INDEX", + r"\1NULL_FILTERED INDEX", + text, + flags=re.IGNORECASE, + ) + + return text + + def get_identity_options(self, identity_options): + text = ["bit_reversed_positive"] + if identity_options.start is not None: + text.append("start counter with %d" % identity_options.start) + return " ".join(text) + + def get_sequence_options(self, identity_options): + text = ["sequence_kind = 'bit_reversed_positive'"] + if identity_options.start is not None: + text.append("start_with_counter = %d" % identity_options.start) + return ", ".join(text) + + def visit_create_sequence(self, create, prefix=None, **kw): + """Builds a ``CREATE SEQUENCE`` statement for the sequence.""" + text = "CREATE SEQUENCE %s" % self.preparer.format_sequence(create.element) + options = self.get_sequence_options(create.element) + if options: + text += " OPTIONS (" + options + ")" + return text + + def visit_drop_sequence(self, drop, **kw): + """Builds a ``DROP SEQUENCE`` statement for the sequence.""" + return "DROP SEQUENCE %s" % self.preparer.format_sequence(drop.element) + + +class SpannerTypeCompiler(GenericTypeCompiler): + """Spanner types compiler. + + Maps SQLAlchemy types to Spanner data types. + """ + + def visit_INTEGER(self, type_, **kw): + return "INT64" + + def visit_DOUBLE(self, type_, **kw): + return "FLOAT64" + + def visit_FLOAT(self, type_, **kw): + # Note: This was added before Spanner supported FLOAT32. + # Changing this now to generate a FLOAT32 would be a breaking change. + # Users therefore have to use REAL to generate a FLOAT32 column. + return "FLOAT64" + + def visit_REAL(self, type_, **kw): + return "FLOAT32" + + def visit_TEXT(self, type_, **kw): + return "STRING({})".format(type_.length or "MAX") + + def visit_ARRAY(self, type_, **kw): + return "ARRAY<{}>".format(self.process(type_.item_type, **kw)) + + def visit_BINARY(self, type_, **kw): # pragma: no cover + """ + The BINARY type is superseded by large_binary in + newer versions of SQLAlchemy (>1.4). + """ + return "BYTES({})".format(type_.length or "MAX") + + def visit_large_binary(self, type_, **kw): # pragma: no cover + return "BYTES({})".format(type_.length or "MAX") + + def visit_DECIMAL(self, type_, **kw): + return "NUMERIC" + + def visit_VARCHAR(self, type_, **kw): + return "STRING({})".format(type_.length or "MAX") + + def visit_CHAR(self, type_, **kw): + return "STRING({})".format(type_.length or "MAX") + + def visit_BOOLEAN(self, type_, **kw): + return "BOOL" + + def visit_DATETIME(self, type_, **kw): + return "TIMESTAMP" + + def visit_NUMERIC(self, type_, **kw): + return "NUMERIC" + + def visit_BIGINT(self, type_, **kw): + return "INT64" + + def visit_JSON(self, type_, **kw): + return "JSON" + + +class SpannerDialect(DefaultDialect): + """Cloud Spanner dialect. + + Represents an API layer to control Cloud Spanner database with SQLAlchemy API. + """ + + name = "spanner+spanner" + driver = "spanner" + positional = False + paramstyle = "format" + encoding = "utf-8" + max_identifier_length = 256 + _legacy_binary_type_literal_encoding = "utf-8" + _default_isolation_level = "SERIALIZABLE" + + execute_sequence_format = list + + supports_alter = True + supports_sane_rowcount = False + supports_sane_multi_rowcount = False + supports_default_values = False + supports_sequences = True + sequences_optional = False + supports_identity_columns = True + supports_native_boolean = True + supports_native_decimal = True + supports_statement_cache = True + # Spanner uses protos for enums. Creating a column like + # Column("an_enum", Enum("A", "B", "C")) will result in a String + # column. Setting supports_native_enum to False allows SQLAlchemy + # to generate check constraints to enforce the enum values if the + # create_constraint=True flag is passed to the Enum constructor. + supports_native_enum = False + + postfetch_lastrowid = False + insert_returning = True + update_returning = True + delete_returning = True + supports_multivalues_insert = True + use_insertmanyvalues = True + + ddl_compiler = SpannerDDLCompiler + preparer = SpannerIdentifierPreparer + statement_compiler = SpannerSQLCompiler + type_compiler = SpannerTypeCompiler + execution_ctx_cls = SpannerExecutionContext + _json_serializer = JsonObject + _json_deserializer = JsonObject + + @classmethod + def dbapi(cls): + """A pointer to the Cloud Spanner DB API package. + + Used to initiate connections to the Cloud Spanner databases. + """ + return spanner_dbapi + + @classmethod + def import_dbapi(cls): + """A pointer to the Cloud Spanner DB API package. + + Used to initiate connections to the Cloud Spanner databases. + """ + return spanner_dbapi + + @property + def default_isolation_level(self): + """Default isolation level name. + + Returns: + str: default isolation level. + """ + return self._default_isolation_level + + @default_isolation_level.setter + def default_isolation_level(self, value): + self._default_isolation_level = value + + def _check_unicode_returns(self, connection, additional_tests=None): + """Ensure requests are returning Unicode responses.""" + return True + + def _get_default_schema_name(self, _): + """Get default Cloud Spanner schema name. + + Returns: + str: Schema name. + """ + return "" + + def _get_table_type_query(self, kind, append_query): + """ + Generates WHERE condition for Kind of Object. + Spanner supports Table and View. + """ + if not USING_SQLACLCHEMY_20: + return "" + + kind = ObjectKind.TABLE if kind is None else kind + if kind == ObjectKind.MATERIALIZED_VIEW: + raise NotImplementedError("Spanner does not support MATERIALIZED VIEWS") + switch_case = { + ObjectKind.ANY: ["BASE TABLE", "VIEW"], + ObjectKind.TABLE: ["BASE TABLE"], + ObjectKind.VIEW: ["VIEW"], + ObjectKind.ANY_VIEW: ["VIEW"], + } + + table_type_query = "" + for table_type in switch_case[kind]: + query = f"t.table_type = '{table_type}'" + if table_type_query != "": + table_type_query = table_type_query + " OR " + query + else: + table_type_query = query + + table_type_query = "(" + table_type_query + ") " + if append_query: + table_type_query = table_type_query + " AND " + return table_type_query + + def _get_table_filter_query( + self, filter_names, info_schema_table, append_query=False + ): + """ + Generates WHERE query for tables or views for which + information is reflected. + """ + table_filter_query = "" + if filter_names is not None: + for table_name in filter_names: + query = f"{info_schema_table}.table_name = '{table_name}'" + if table_filter_query != "": + table_filter_query = table_filter_query + " OR " + query + else: + table_filter_query = query + table_filter_query = "(" + table_filter_query + ") " + if append_query: + table_filter_query = table_filter_query + " AND " + + return table_filter_query + + def create_connect_args(self, url): + """Parse connection args from the given URL. + + The method prepares args suitable to send to the DB API `connect()` function. + + The given URL follows the style: + `spanner:///projects/{project-id}/instances/{instance-id}/databases/{database-id}` + or `spanner:///projects/{project-id}/instances/{instance-id}`. For the latter, + database operations will be not be possible and if required a new engine with + database-id set will need to be created. + """ + match = re.match( + ( + r"^projects/(?P.+?)/instances/" + "(?P.+?)(/databases/(?P.+)|$)" + ), + url.database, + ) + dist_version = sqlalchemy_spanner_version.__version__ + options = {"user_agent": f"gl-sqlalchemy-spanner/{dist_version}"} + connect_opts = url.translate_connect_args() + if ( + "host" in connect_opts + and "port" in connect_opts + and "password" in connect_opts + ): + # Create a test client that connects to a local Spanner (mock) server. + if ( + connect_opts["host"] == "localhost" + and connect_opts["password"] == "AnonymousCredentials" + ): + client = Client( + project=match.group("project"), + credentials=AnonymousCredentials(), + client_options=ClientOptions( + api_endpoint=f"{connect_opts['host']}:{connect_opts['port']}", + ), + ) + options["client"] = client + return ( + [match.group("instance"), match.group("database"), match.group("project")], + options, + ) + + @engine_to_connection + def get_view_names(self, connection, schema=None, **kw): + """ + Gets a list of view names. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + schema (str): Optional. Schema name + + Returns: + list: List of view names. + """ + sql = """ + SELECT table_name + FROM information_schema.views + WHERE TABLE_SCHEMA='{}' + """.format( + schema or "" + ) + + all_views = [] + with connection.connection.database.snapshot() as snap: + rows = list(snap.execute_sql(sql)) + for view in rows: + all_views.append(view[0]) + + return all_views + + @engine_to_connection + def get_sequence_names(self, connection, schema=None, **kw): + """ + Return a list of all sequence names available in the database. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + schema (str): Optional. Schema name + + Returns: + list: List of sequence names. + """ + sql = """ + SELECT name + FROM information_schema.sequences + WHERE SCHEMA='{}' + """.format( + schema or "" + ) + all_sequences = [] + with connection.connection.database.snapshot() as snap: + rows = list(snap.execute_sql(sql)) + for seq in rows: + all_sequences.append(seq[0]) + + return all_sequences + + @engine_to_connection + def get_view_definition(self, connection, view_name, schema=None, **kw): + """ + Gets definition of a particular view. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + view_name (str): Name of the view. + schema (str): Optional. Schema name + + Returns: + str: Definition of view. + """ + sql = """ + SELECT view_definition + FROM information_schema.views + WHERE TABLE_SCHEMA='{schema_name}' AND TABLE_NAME='{view_name}' + """.format( + schema_name=schema or "", view_name=view_name + ) + + with connection.connection.database.snapshot() as snap: + rows = list(snap.execute_sql(sql)) + if rows == []: + raise NoSuchTableError(f"{schema if schema else ''}.{view_name}") + result = rows[0][0] + + return result + + @engine_to_connection + def get_multi_columns( + self, connection, schema=None, filter_names=None, scope=None, kind=None, **kw + ): + """ + Return information about columns in all objects in the given + schema. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + schema (str): Optional. Schema name + filter_names (Sequence[str]): Optional. Optionally return information + only for the objects listed here. + scope (sqlalchemy.engine.reflection.ObjectScope): Optional. Specifies + if columns of default, temporary or any tables + should be reflected. Spanner does not support temporary. + kind (sqlalchemy.engine.reflection.ObjectKind): Optional. Specifies the + type of objects to reflect. + + Returns: + dictionary: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing the + definition of a database column. + The schema is ``None`` if no schema is provided. + """ + table_filter_query = self._get_table_filter_query(filter_names, "col", True) + schema_filter_query = " col.table_schema = '{schema}' AND ".format( + schema=schema or "" + ) + table_type_query = self._get_table_type_query(kind, True) + + sql = """ + SELECT col.table_schema, col.table_name, col.column_name, + col.spanner_type, col.is_nullable, col.generation_expression, + col.column_default + FROM information_schema.columns as col + JOIN information_schema.tables AS t + USING (TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME) + WHERE + {table_filter_query} + {table_type_query} + {schema_filter_query} + col.table_catalog = '' + ORDER BY + col.table_catalog, + col.table_schema, + col.table_name, + col.ordinal_position + """.format( + table_filter_query=table_filter_query, + table_type_query=table_type_query, + schema_filter_query=schema_filter_query, + ) + with connection.connection.database.snapshot() as snap: + columns = list(snap.execute_sql(sql)) + result_dict = {} + + for col in columns: + column_info = { + "name": col[2], + "type": self._designate_type(col[3]), + "nullable": col[4] == "YES", + "default": col[6] if col[6] is not None else None, + } + + if col[5] is not None: + column_info["computed"] = { + "persisted": True, + "sqltext": col[5], + } + col[0] = col[0] or None + table_info = result_dict.get((col[0], col[1]), []) + table_info.append(column_info) + result_dict[(col[0], col[1])] = table_info + + return result_dict + + @engine_to_connection + def get_columns(self, connection, table_name, schema=None, **kw): + """Get the table columns description. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + table_name (str): Name of the table to introspect. + schema (str): Optional. Schema name + + Returns: + list: The table every column dict-like description. + """ + kind = None if not USING_SQLACLCHEMY_20 else ObjectKind.ANY + dict = self.get_multi_columns( + connection, schema=schema, filter_names=[table_name], kind=kind + ) + schema = schema or None + return dict.get((schema, table_name), []) + + def _designate_type(self, str_repr): + """ + Designate an SQLAlchemy data type from a Spanner + string representation. + + Args: + str_repr (str): String representation of a type. + + Returns: + An SQLAlchemy data type. + """ + if str_repr.startswith("STRING"): + end = str_repr.index(")") + size = int_from_size(str_repr[7:end]) + return _type_map["STRING"](length=size) + # add test creating a table with bytes + elif str_repr.startswith("BYTES"): + end = str_repr.index(")") + size = int_from_size(str_repr[6:end]) + return _type_map["BYTES"](length=size) + elif str_repr.startswith("ARRAY"): + inner_type_str = str_repr[6:-1] + inner_type = self._designate_type(inner_type_str) + return _type_map["ARRAY"](inner_type) + else: + return _type_map[str_repr] + + @engine_to_connection + def get_multi_indexes( + self, connection, schema=None, filter_names=None, scope=None, kind=None, **kw + ): + """ + Return information about indexes in all objects + in the given schema. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + schema (str): Optional. Schema name. + filter_names (Sequence[str]): Optional. Optionally return information + only for the objects listed here. + scope (sqlalchemy.engine.reflection.ObjectScope): Optional. Specifies + if columns of default, temporary or any tables + should be reflected. Spanner does not support temporary. + kind (sqlalchemy.engine.reflection.ObjectKind): Optional. Specifies the + type of objects to reflect. + + Returns: + dictionary: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing the + definition of an index. + The schema is ``None`` if no schema is provided. + """ + table_filter_query = self._get_table_filter_query(filter_names, "i", True) + schema_filter_query = " i.table_schema = '{schema}' AND ".format( + schema=schema or "" + ) + table_type_query = self._get_table_type_query(kind, True) + + sql = """ + SELECT + i.table_schema, + i.table_name, + i.index_name, + ARRAY( + SELECT ic.column_name + FROM information_schema.index_columns ic + WHERE ic.index_name = i.index_name + AND ic.table_catalog = i.table_catalog + AND ic.table_schema = i.table_schema + AND ic.table_name = i.table_name + AND ic.column_ordering is not null + ORDER BY ic.ordinal_position + ) as columns, + i.is_unique, + ARRAY( + SELECT ic.column_ordering + FROM information_schema.index_columns ic + WHERE ic.index_name = i.index_name + AND ic.table_catalog = i.table_catalog + AND ic.table_schema = i.table_schema + AND ic.table_name = i.table_name + AND ic.column_ordering is not null + ORDER BY ic.ordinal_position + ) as column_orderings, + ARRAY( + SELECT storing.column_name + FROM information_schema.index_columns storing + WHERE storing.index_name = i.index_name + AND storing.table_catalog = i.table_catalog + AND storing.table_schema = i.table_schema + AND storing.table_name = i.table_name + AND storing.column_ordering is null + ORDER BY storing.ordinal_position + ) as storing_columns, + FROM information_schema.indexes as i + JOIN information_schema.tables AS t + ON i.table_catalog = t.table_catalog + AND i.table_schema = t.table_schema + AND i.table_name = t.table_name + WHERE + {table_filter_query} + {table_type_query} + {schema_filter_query} + i.index_type != 'PRIMARY_KEY' + AND i.spanner_is_managed = FALSE + GROUP BY i.table_catalog, i.table_schema, i.table_name, + i.index_name, i.is_unique + ORDER BY i.index_name + """.format( + table_filter_query=table_filter_query, + table_type_query=table_type_query, + schema_filter_query=schema_filter_query, + ) + + with connection.connection.database.snapshot() as snap: + rows = list(snap.execute_sql(sql)) + result_dict = {} + + for row in rows: + dialect_options = {} + include_columns = row[6] + if include_columns: + dialect_options["spanner_storing"] = include_columns + index_info = { + "name": row[2], + "column_names": row[3], + "unique": row[4], + "column_sorting": { + col: order.lower() for col, order in zip(row[3], row[5]) + }, + "include_columns": include_columns if include_columns else [], + "dialect_options": dialect_options, + } + row[0] = row[0] or None + table_info = result_dict.get((row[0], row[1]), []) + table_info.append(index_info) + result_dict[(row[0], row[1])] = table_info + + return result_dict + + @engine_to_connection + def get_indexes(self, connection, table_name, schema=None, **kw): + """Get the table indexes. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + table_name (str): Name of the table to introspect. + schema (str): Optional. Schema name + + Returns: + list: List with indexes description. + """ + kind = None if not USING_SQLACLCHEMY_20 else ObjectKind.ANY + dict = self.get_multi_indexes( + connection, schema=schema, filter_names=[table_name], kind=kind + ) + schema = schema or None + return dict.get((schema, table_name), []) + + @engine_to_connection + def get_multi_pk_constraint( + self, connection, schema=None, filter_names=None, scope=None, kind=None, **kw + ): + """ + Return information about primary key constraints in + all tables in the given schema. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + schema (str): Optional. Schema name + filter_names (Sequence[str]): Optional. Optionally return information + only for the objects listed here. + scope (sqlalchemy.engine.reflection.ObjectScope): Optional. Specifies + if columns of default, temporary or any tables + should be reflected. Spanner does not support temporary. + kind (sqlalchemy.engine.reflection.ObjectKind): Optional. Specifies the + type of objects to reflect. + + Returns: + dictionary: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing the + definition of a primary key constraint. + The schema is ``None`` if no schema is provided. + """ + table_filter_query = self._get_table_filter_query(filter_names, "tc", True) + schema_filter_query = " tc.table_schema = '{schema}' AND ".format( + schema=schema or "" + ) + table_type_query = self._get_table_type_query(kind, True) + + sql = """ + SELECT tc.table_schema, tc.table_name, kcu.column_name + FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc + JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu + USING (TABLE_CATALOG, TABLE_SCHEMA, CONSTRAINT_NAME) + JOIN information_schema.tables AS t + ON tc.TABLE_CATALOG = t.TABLE_CATALOG + AND tc.TABLE_SCHEMA = t.TABLE_SCHEMA + AND tc.TABLE_NAME = t.TABLE_NAME + WHERE {table_filter_query} {table_type_query} + {schema_filter_query} tc.CONSTRAINT_TYPE = "PRIMARY KEY" + ORDER BY tc.table_catalog ASC, tc.table_schema ASC, + tc.table_name ASC, kcu.ordinal_position ASC + """.format( + table_filter_query=table_filter_query, + table_type_query=table_type_query, + schema_filter_query=schema_filter_query, + ) + + with connection.connection.database.snapshot() as snap: + rows = list(snap.execute_sql(sql)) + result_dict = {} + + for row in rows: + row[0] = row[0] or None + table_info = result_dict.get( + (row[0], row[1]), {"constrained_columns": []} + ) + table_info["constrained_columns"].append(row[2]) + result_dict[(row[0], row[1])] = table_info + + return result_dict + + @engine_to_connection + def get_pk_constraint(self, connection, table_name, schema=None, **kw): + """Get the table primary key constraint. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + table_name (str): Name of the table to introspect. + schema (str): Optional. Schema name + + Returns: + dict: Dict with the primary key constraint description. + """ + kind = None if not USING_SQLACLCHEMY_20 else ObjectKind.ANY + dict = self.get_multi_pk_constraint( + connection, schema=schema, filter_names=[table_name], kind=kind + ) + schema = schema or None + return dict.get((schema, table_name), []) + + @engine_to_connection + def get_schema_names(self, connection, **kw): + """Get all the schemas in the database. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + + Returns: + list: Schema names. + """ + schemas = [] + with connection.connection.database.snapshot() as snap: + rows = snap.execute_sql( + "SELECT schema_name FROM information_schema.schemata" + ) + + for row in rows: + schemas.append(row[0]) + + return schemas + + @engine_to_connection + def get_multi_foreign_keys( + self, connection, schema=None, filter_names=None, scope=None, kind=None, **kw + ): + """ + Return information about foreign_keys in all tables + in the given schema. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + schema (str): Optional. Schema name + filter_names (Sequence[str]): Optional. Optionally return information + only for the objects listed here. + scope (sqlalchemy.engine.reflection.ObjectScope): Optional. Specifies + if columns of default, temporary or any tables + should be reflected. Spanner does not support temporary. + kind (sqlalchemy.engine.reflection.ObjectKind): Optional. Specifies the + type of objects to reflect. + + Returns: + dictionary: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing + a foreign key definition. + The schema is ``None`` if no schema is provided. + """ + table_filter_query = self._get_table_filter_query(filter_names, "tc", True) + schema_filter_query = " tc.table_schema = '{schema}' AND".format( + schema=schema or "" + ) + table_type_query = self._get_table_type_query(kind, True) + + sql = """ + SELECT + tc.table_schema, + tc.table_name, + tc.constraint_name, + tc_uq.table_name, + tc_uq.table_schema, + -- Find the corresponding pairs of columns for the foreign key constraint + -- and its related unique constraint. + ARRAY( + SELECT (kcu.column_name, kcu_uq.column_name) + FROM information_schema.key_column_usage AS kcu + JOIN information_schema.key_column_usage AS kcu_uq + ON kcu_uq.constraint_catalog = rc.unique_constraint_catalog + AND kcu_uq.constraint_schema = rc.unique_constraint_schema + AND kcu_uq.constraint_name = rc.unique_constraint_name + AND kcu_uq.ordinal_position = kcu.ordinal_position + WHERE + kcu.constraint_catalog = tc.constraint_catalog + AND kcu.constraint_schema = tc.constraint_schema + AND kcu.constraint_name = tc.constraint_name + ORDER BY kcu.ordinal_position + ) + FROM information_schema.table_constraints AS tc + -- Join the foreign key constraint for the referring table. + JOIN information_schema.referential_constraints AS rc + ON rc.constraint_catalog = tc.constraint_catalog + AND rc.constraint_schema = tc.constraint_schema + AND rc.constraint_name = tc.constraint_name + -- Join the corresponding unique constraint on the referenced table. + JOIN information_schema.table_constraints AS tc_uq + ON tc_uq.constraint_catalog = rc.unique_constraint_catalog + AND tc_uq.constraint_schema = rc.unique_constraint_schema + AND tc_uq.constraint_name = rc.unique_constraint_name + -- Join in the tables view so WHERE filters can reference fields in it. + JOIN information_schema.tables AS t + ON t.table_catalog = tc.table_catalog + AND t.table_schema = tc.table_schema + AND t.table_name = tc.table_name + WHERE + {table_filter_query} + {table_type_query} + {schema_filter_query} + tc.constraint_type = "FOREIGN KEY" + """.format( + table_filter_query=table_filter_query, + table_type_query=table_type_query, + schema_filter_query=schema_filter_query, + ) + + with connection.connection.database.snapshot() as snap: + rows = list(snap.execute_sql(sql)) + result_dict = {} + + for row in rows: + row[0] = row[0] or None + table_info = result_dict.get((row[0], row[1]), []) + + constrained_columns, referred_columns = zip(*row[5]) + fk_info = { + "name": row[2], + "referred_table": row[3], + "referred_schema": row[4] or None, + "referred_columns": list(referred_columns), + "constrained_columns": list(constrained_columns), + } + + table_info.append(fk_info) + result_dict[(row[0], row[1])] = table_info + + return result_dict + + @engine_to_connection + def get_foreign_keys(self, connection, table_name, schema=None, **kw): + """Get the table foreign key constraints. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + table_name (str): Name of the table to introspect. + schema (str): Optional. Schema name + + Returns: + list: Dicts, each of which describes a foreign key constraint. + """ + kind = None if not USING_SQLACLCHEMY_20 else ObjectKind.ANY + dict = self.get_multi_foreign_keys( + connection, schema=schema, filter_names=[table_name], kind=kind + ) + schema = schema or None + return dict.get((schema, table_name), []) + + @engine_to_connection + def get_table_names(self, connection, schema=None, **kw): + """Get all the tables from the given schema. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + schema (str): Optional. Schema name. + + Returns: + list: Names of the tables within the given schema. + """ + sql = """ +SELECT table_name +FROM information_schema.tables +WHERE table_type = 'BASE TABLE' AND table_schema = '{schema}' +""".format( + schema=schema or "" + ) + + table_names = [] + with connection.connection.database.snapshot() as snap: + rows = snap.execute_sql(sql) + + for row in rows: + table_names.append(row[0]) + + return table_names + + @engine_to_connection + def get_unique_constraints(self, connection, table_name, schema=None, **kw): + """Get the table unique constraints. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + table_name (str): Name of the table to introspect. + schema (str): Optional. Schema name + + Returns: + dict: Dict with the unique constraints' descriptions. + """ + sql = """ +SELECT ccu.CONSTRAINT_NAME, ccu.COLUMN_NAME +FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc +JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu + USING (TABLE_CATALOG, TABLE_SCHEMA, CONSTRAINT_NAME) +WHERE + tc.TABLE_NAME="{table_name}" + AND tc.TABLE_SCHEMA="{table_schema}" + AND tc.CONSTRAINT_TYPE = "UNIQUE" + AND tc.CONSTRAINT_NAME IS NOT NULL +""".format( + table_schema=schema or "", table_name=table_name + ) + + cols = [] + with connection.connection.database.snapshot() as snap: + rows = snap.execute_sql(sql) + + for row in rows: + cols.append({"name": row[0], "column_names": [row[1]]}) + + return cols + + @engine_to_connection + def has_table(self, connection, table_name, schema=None, **kw): + """Check if the given table exists. + + The method is used by SQLAlchemy introspection systems. + + Args: + connection (sqlalchemy.engine.base.Connection): + SQLAlchemy connection or engine object. + table_name (str): Name of the table to introspect. + schema (str): Optional. Schema name. + + Returns: + bool: True, if the given table exists, False otherwise. + """ + with connection.connection.database.snapshot() as snap: + rows = snap.execute_sql( + """ +SELECT true +FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_SCHEMA="{table_schema}" AND TABLE_NAME="{table_name}" +LIMIT 1 +""".format( + table_schema=schema or "", table_name=table_name + ) + ) + + for _ in rows: + return True + + return False + + @engine_to_connection + def has_sequence(self, connection, sequence_name, schema=None, **kw): + """Check the existence of a particular sequence in the database. + + Given a :class:`_engine.Connection` object and a string + `sequence_name`, return True if the given sequence exists in + the database, False otherwise. + """ + + with connection.connection.database.snapshot() as snap: + rows = snap.execute_sql( + """ + SELECT true + FROM INFORMATION_SCHEMA.SEQUENCES + WHERE NAME="{sequence_name}" + AND SCHEMA="{schema}" + LIMIT 1 + """.format( + sequence_name=sequence_name, schema=schema or "" + ) + ) + + for _ in rows: + return True + + return False + + def set_isolation_level(self, conn_proxy, level): + """Set the connection isolation level. + + Args: + conn_proxy ( + Union[ + sqlalchemy.pool._ConnectionFairy, + spanner_dbapi.connection.Connection, + ] + ): + Database connection proxy object or the connection itself. + level (string): Isolation level. + """ + if isinstance(conn_proxy, spanner_dbapi.Connection): + conn = conn_proxy + else: + conn = conn_proxy.connection + + if level == "AUTOCOMMIT": + conn.autocommit = True + else: + if isinstance(level, str): + level = self._string_to_isolation_level(level) + conn.isolation_level = level + conn.autocommit = False + + def get_isolation_level(self, conn_proxy): + """Get the connection isolation level. + + Args: + conn_proxy ( + Union[ + sqlalchemy.pool._ConnectionFairy, + spanner_dbapi.connection.Connection, + ] + ): + Database connection proxy object or the connection itself. + + Returns: + str: the connection isolation level. + """ + if isinstance(conn_proxy, spanner_dbapi.Connection): + conn = conn_proxy + else: + conn = conn_proxy.connection + + if conn.autocommit: + return "AUTOCOMMIT" + + level = conn.isolation_level + if level == TransactionOptions.IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED: + level = TransactionOptions.IsolationLevel.SERIALIZABLE + if isinstance(level, TransactionOptions.IsolationLevel): + level = self._isolation_level_to_string(level) + + return level + + def _string_to_isolation_level(self, name): + try: + # SQLAlchemy guarantees that the isolation level string will: + # 1. Be all upper case. + # 2. Contain spaces instead of underscores. + # We change the spaces into underscores to get the enum value. + return TransactionOptions.IsolationLevel[name.replace(" ", "_")] + except KeyError: + raise ValueError("Invalid isolation level name '%s'" % name) + + def _isolation_level_to_string(self, level): + # SQLAlchemy expects isolation level names to contain spaces, + # and not underscores, so we remove those before returning. + return level.name.replace("_", " ") + + def do_rollback(self, dbapi_connection): + """ + To prevent rollback exception, don't rollback + committed/rolled back transactions. + """ + if not isinstance(dbapi_connection, spanner_dbapi.Connection): + dbapi_connection = dbapi_connection.connection + + if dbapi_connection._transaction and ( + dbapi_connection._transaction.rolled_back + or dbapi_connection._transaction.committed + ): + pass + else: + trace_attributes = { + "db.instance": dbapi_connection.database.name + if dbapi_connection.database + else "" + } + with trace_call("SpannerSqlAlchemy.Rollback", trace_attributes): + dbapi_connection.rollback() + + def do_commit(self, dbapi_connection): + trace_attributes = { + "db.instance": dbapi_connection.database.name + if dbapi_connection.database + else "" + } + with trace_call("SpannerSqlAlchemy.Commit", trace_attributes): + dbapi_connection.commit() + + def do_close(self, dbapi_connection): + trace_attributes = { + "db.instance": dbapi_connection.database.name + if dbapi_connection.database + else "" + } + with trace_call("SpannerSqlAlchemy.Close", trace_attributes): + dbapi_connection.close() + + def do_executemany(self, cursor, statement, parameters, context=None): + trace_attributes = { + "db.statement": statement, + "db.params": parameters, + "db.instance": cursor.connection.database.name, + } + with trace_call("SpannerSqlAlchemy.ExecuteMany", trace_attributes): + cursor.executemany(statement, parameters) + + def do_execute(self, cursor, statement, parameters, context=None): + trace_attributes = { + "db.statement": statement, + "db.params": parameters, + "db.instance": cursor.connection.database.name, + } + with trace_call("SpannerSqlAlchemy.Execute", trace_attributes): + cursor.execute(statement, parameters) + + def do_execute_no_params(self, cursor, statement, context=None): + trace_attributes = { + "db.statement": statement, + "db.instance": cursor.connection.database.name, + } + with trace_call("SpannerSqlAlchemy.ExecuteNoParams", trace_attributes): + cursor.execute(statement) + + +# Alembic ALTER operation override +@compiles(ColumnNullable, "spanner+spanner") +def visit_column_nullable( + element: "ColumnNullable", compiler: "SpannerDDLCompiler", **kw +) -> str: + return _format_alter_column( + compiler, + element.table_name, + element.schema, + element.column_name, + element.existing_type, + element.nullable, + element.existing_server_default, + ) + + +# Alembic ALTER operation override +@compiles(ColumnType, "spanner+spanner") +def visit_column_type( + element: "ColumnType", compiler: "SpannerDDLCompiler", **kw +) -> str: + return _format_alter_column( + compiler, + element.table_name, + element.schema, + element.column_name, + element.type_, + element.existing_nullable, + element.existing_server_default, + ) + + +def _format_alter_column( + compiler, table_name, schema, column_name, type_, nullable, server_default +): + # Older versions of SQLAlchemy pass in a boolean to indicate whether there + # is an existing DEFAULT constraint, instead of the actual DEFAULT constraint + # expression. In those cases, we do not want to explicitly include the DEFAULT + # constraint in the expression that is generated here. + if isinstance(server_default, bool): + server_default = None + return "%s %s %s%s%s" % ( + alter_table(compiler, table_name, schema), + alter_column(compiler, column_name), + format_type(compiler, type_), + "" if nullable else " NOT NULL", + ( + "" + if server_default is None + else f" DEFAULT {format_server_default(compiler, server_default)}" + ), + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ab25bf0dae31553186289949acfeb7052f2fb504 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/sqlalchemy_spanner/version.py @@ -0,0 +1,7 @@ +# Copyright 2021 Google LLC +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +__version__ = "1.17.3" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e9c47f4a03b5b716d4c2a36cc2a6135fea59c3a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__init__.py @@ -0,0 +1,41 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shortcut methods for getting set up with Google Cloud Storage. + +You'll typically use these to get started with the API: + +.. literalinclude:: snippets.py + :start-after: START storage_get_started + :end-before: END storage_get_started + :dedent: 4 + +The main concepts with this API are: + +- :class:`~google.cloud.storage.bucket.Bucket` which represents a particular + bucket (akin to a mounted disk on a computer). + +- :class:`~google.cloud.storage.blob.Blob` which represents a pointer to a + particular entity in Cloud Storage (akin to a file path on a remote + machine). +""" + +from google.cloud.storage.version import __version__ +from google.cloud.storage.batch import Batch +from google.cloud.storage.blob import Blob +from google.cloud.storage.bucket import Bucket +from google.cloud.storage.client import Client + + +__all__ = ["__version__", "Batch", "Blob", "Bucket", "Client"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2ff903af4385201521225b17efdb825401c218c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_helpers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3ec11f78306999f8ba676ed21e225175b5e0154 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_helpers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_http.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_http.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3164f7d88726680c83af11c39f6a01325b1c66af Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_http.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_opentelemetry_tracing.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_opentelemetry_tracing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5277587797d858713d2d32e4e5e0abfa20251227 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_opentelemetry_tracing.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_signing.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_signing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bba3de1eb0ec066d6fe98e0ab9c1044669c9072f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/_signing.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/acl.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/acl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27c507cacf1f4048539235241f3c6aaf6d6f45a6 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/acl.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/batch.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a901855b9960a91a6e59f78ee61d77ae149443d7 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/batch.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/blob.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/blob.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04f1ed7163f913d84a564187cf8fecb9aca853aa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/blob.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdf8ff806a479d0bc8f6b0888d5e08232a47952ed85c08a574084bf02ebfcbad +size 192333 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/bucket.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/bucket.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b88f0633ff796f1222c1b6467b69d62b67bc7f46 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/bucket.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:635396f3d4b9ff1cfa3a45161ae39b02989aa29388c9d55ec9e970aa958bcd70 +size 172464 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/client.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fad4eb91ab4bee9b797767fb262a37aa1be7e97f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/client.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/constants.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b88be60ede487e37d2769070c54e1040aa6615ff Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/constants.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/exceptions.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c6715f3b94a66be5b75f98090ee5f828c0c77c3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/exceptions.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/fileio.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/fileio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..831502d9ad00d1bc23325004e318dcc05d71cc32 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/fileio.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/hmac_key.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/hmac_key.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a94992ca0ad0b32e3178d9d475ba1c610167eea Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/hmac_key.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/ip_filter.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/ip_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d460546dda8ad965892adbfeed236d5851d86f38 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/ip_filter.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/notification.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/notification.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29fa48c03536aab8b484bce5128ed960a3f7ea94 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/notification.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/retry.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/retry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a847f9b0e5077c906db8a3e071828c83489c4f7 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/retry.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/version.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6f7b2659a9d138e0f2554dd81c4f8b9d9c71745 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/version.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/_utils.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e81a4bc754c840e0bb660deb9a038ad2de64bdf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/_utils.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio._utils import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio._utils has been moved to google.cloud.storage.asyncio._utils. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_abstract_object_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_abstract_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..538241bd22eca4d67accad1448757e37499c8cbd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_abstract_object_stream.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.async_abstract_object_stream import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.async_abstract_object_stream has been moved to google.cloud.storage.asyncio.async_abstract_object_stream. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_appendable_object_writer.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_appendable_object_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..53b8136430a28fa28f98d2a424400180a54d290d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_appendable_object_writer.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.async_appendable_object_writer import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.async_appendable_object_writer has been moved to google.cloud.storage.asyncio.async_appendable_object_writer. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_grpc_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_grpc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..558ff0c5a88b741dff37255ca8d606e55eb2411f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_grpc_client.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.async_grpc_client import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.async_grpc_client has been moved to google.cloud.storage.asyncio.async_grpc_client. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_multi_range_downloader.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_multi_range_downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc2c7c2bab550ca3bf1dbef8dca48c7c4152ff8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_multi_range_downloader.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.async_multi_range_downloader import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.async_multi_range_downloader has been moved to google.cloud.storage.asyncio.async_multi_range_downloader. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_read_object_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_read_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..cb39386f2b1be023b1c265144c491459cc92dc00 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_read_object_stream.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.async_read_object_stream import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.async_read_object_stream has been moved to google.cloud.storage.asyncio.async_read_object_stream. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_write_object_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_write_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..132e2c9d07bee19650179add7a5534afbeece2b9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/async_write_object_stream.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.async_write_object_stream import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.async_write_object_stream has been moved to google.cloud.storage.asyncio.async_write_object_stream. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..092986f58b36327d099b2497839d7423a277ce73 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/_helpers.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.retry._helpers import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.retry._helpers has been moved to google.cloud.storage.asyncio.retry._helpers. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/base_strategy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/base_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..58c58136cf84121dd9c065f232c01bd33c89c569 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/base_strategy.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.retry.base_strategy import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.retry.base_strategy has been moved to google.cloud.storage.asyncio.retry.base_strategy. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/bidi_stream_retry_manager.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/bidi_stream_retry_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..331ee13263993e2a0784fa38a2aaa020dbc614c5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/bidi_stream_retry_manager.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.retry.bidi_stream_retry_manager import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.retry.bidi_stream_retry_manager has been moved to google.cloud.storage.asyncio.retry.bidi_stream_retry_manager. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/reads_resumption_strategy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/reads_resumption_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7051b6a9a6a3b570f7514a104feab78fb75675 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/reads_resumption_strategy.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.retry.reads_resumption_strategy import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.retry.reads_resumption_strategy has been moved to google.cloud.storage.asyncio.retry.reads_resumption_strategy. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/writes_resumption_strategy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/writes_resumption_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..7d2493841bdeb22541c960f3d9b65cc06bcc29ec --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/asyncio/retry/writes_resumption_strategy.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.asyncio.retry.writes_resumption_strategy import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.asyncio.retry.writes_resumption_strategy has been moved to google.cloud.storage.asyncio.retry.writes_resumption_strategy. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/grpc_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/grpc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..99ecbe04443c3e8f6ccc48b6a3f00122902f5e52 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_experimental/grpc_client.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.grpc_client import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.grpc_client has been moved to google.cloud.storage.grpc_client. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..24f72ad7142af785d6b85601f7ad3f1a4bfe54f2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_helpers.py @@ -0,0 +1,684 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helper functions for Cloud Storage utility classes. + +These are *not* part of the API. +""" + +import base64 +import datetime +from hashlib import md5 +import os +import sys +import secrets +from urllib.parse import urlsplit +from urllib.parse import urlunsplit +from uuid import uuid4 + +from google.auth import environment_vars +from google.cloud.storage.constants import _DEFAULT_TIMEOUT +from google.cloud.storage.retry import DEFAULT_RETRY +from google.cloud.storage.retry import DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED + + +STORAGE_EMULATOR_ENV_VAR = "STORAGE_EMULATOR_HOST" # Despite name, includes scheme. +"""Environment variable defining host for Storage emulator.""" + +_API_ENDPOINT_OVERRIDE_ENV_VAR = "API_ENDPOINT_OVERRIDE" # Includes scheme. +"""This is an experimental configuration variable. Use api_endpoint instead.""" + +_API_VERSION_OVERRIDE_ENV_VAR = "API_VERSION_OVERRIDE" +"""This is an experimental configuration variable used for internal testing.""" + +_DEFAULT_UNIVERSE_DOMAIN = "googleapis.com" + +_STORAGE_HOST_TEMPLATE = "storage.{universe_domain}" + +_TRUE_DEFAULT_STORAGE_HOST = _STORAGE_HOST_TEMPLATE.format( + universe_domain=_DEFAULT_UNIVERSE_DOMAIN +) + +_DEFAULT_SCHEME = "https://" + +_API_VERSION = os.getenv(_API_VERSION_OVERRIDE_ENV_VAR, "v1") +"""API version of the default storage host""" + +# etag match parameters in snake case and equivalent header +_ETAG_MATCH_PARAMETERS = ( + ("if_etag_match", "If-Match"), + ("if_etag_not_match", "If-None-Match"), +) + +# generation match parameters in camel and snake cases +_GENERATION_MATCH_PARAMETERS = ( + ("if_generation_match", "ifGenerationMatch"), + ("if_generation_not_match", "ifGenerationNotMatch"), + ("if_metageneration_match", "ifMetagenerationMatch"), + ("if_metageneration_not_match", "ifMetagenerationNotMatch"), + ("if_source_generation_match", "ifSourceGenerationMatch"), + ("if_source_generation_not_match", "ifSourceGenerationNotMatch"), + ("if_source_metageneration_match", "ifSourceMetagenerationMatch"), + ("if_source_metageneration_not_match", "ifSourceMetagenerationNotMatch"), +) + +# _NOW() returns the current local date and time. +# It is preferred to use timezone-aware datetimes _NOW(_UTC), +# which returns the current UTC date and time. +_NOW = datetime.datetime.now +_UTC = datetime.timezone.utc + + +def _get_storage_emulator_override(): + return os.environ.get(STORAGE_EMULATOR_ENV_VAR, None) + + +def _get_default_storage_base_url(): + return os.getenv( + _API_ENDPOINT_OVERRIDE_ENV_VAR, _DEFAULT_SCHEME + _TRUE_DEFAULT_STORAGE_HOST + ) + + +def _get_api_endpoint_override(): + """This is an experimental configuration variable. Use api_endpoint instead.""" + if _get_default_storage_base_url() != _DEFAULT_SCHEME + _TRUE_DEFAULT_STORAGE_HOST: + return _get_default_storage_base_url() + return None + + +def _virtual_hosted_style_base_url(url, bucket, trailing_slash=False): + """Returns the scheme and netloc sections of the url, with the bucket + prepended to the netloc. + + Not intended for use with netlocs which include a username and password. + """ + parsed_url = urlsplit(url) + new_netloc = f"{bucket}.{parsed_url.netloc}" + base_url = urlunsplit( + (parsed_url.scheme, new_netloc, "/" if trailing_slash else "", "", "") + ) + return base_url + + +def _get_environ_project(): + return os.getenv( + environment_vars.PROJECT, + os.getenv(environment_vars.LEGACY_PROJECT), + ) + + +def _validate_name(name): + """Pre-flight ``Bucket`` name validation. + + :type name: str or :data:`NoneType` + :param name: Proposed bucket name. + + :rtype: str or :data:`NoneType` + :returns: ``name`` if valid. + """ + if name is None: + return + + # The first and last characters must be alphanumeric. + if not all([name[0].isalnum(), name[-1].isalnum()]): + raise ValueError("Bucket names must start and end with a number or letter.") + return name + + +class _PropertyMixin(object): + """Abstract mixin for cloud storage classes with associated properties. + + Non-abstract subclasses should implement: + - path + - client + - user_project + + :type name: str + :param name: The name of the object. Bucket names must start and end with a + number or letter. + """ + + def __init__(self, name=None): + self.name = name + self._properties = {} + self._changes = set() + + @property + def path(self): + """Abstract getter for the object path.""" + raise NotImplementedError + + @property + def client(self): + """Abstract getter for the object client.""" + raise NotImplementedError + + @property + def user_project(self): + """Abstract getter for the object user_project.""" + raise NotImplementedError + + def _require_client(self, client): + """Check client or verify over-ride. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current object. + + :rtype: :class:`google.cloud.storage.client.Client` + :returns: The client passed in or the currently bound client. + """ + if client is None: + client = self.client + return client + + def _encryption_headers(self): + """Return any encryption headers needed to fetch the object. + + .. note:: + Defined here because :meth:`reload` calls it, but this method is + really only relevant for :class:`~google.cloud.storage.blob.Blob`. + + :rtype: dict + :returns: a mapping of encryption-related headers. + """ + return {} + + @property + def _query_params(self): + """Default query parameters.""" + params = {} + if self.user_project is not None: + params["userProject"] = self.user_project + return params + + def reload( + self, + client=None, + projection="noAcl", + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + soft_deleted=None, + ): + """Reload properties from Cloud Storage. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current object. + + :type projection: str + :param projection: (Optional) If used, must be 'full' or 'noAcl'. + Defaults to ``'noAcl'``. Specifies the set of + properties to return. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]]) + :param if_etag_not_match: (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type soft_deleted: bool + :param soft_deleted: + (Optional) If True, looks for a soft-deleted object. Will only return + the object metadata if the object exists and is in a soft-deleted state. + :attr:`generation` is required to be set on the blob if ``soft_deleted`` is set to True. + See: https://cloud.google.com/storage/docs/soft-delete + """ + client = self._require_client(client) + query_params = self._query_params + # Pass only '?projection=noAcl' here because 'acl' and related + # are handled via custom endpoints. + query_params["projection"] = projection + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + if soft_deleted is not None: + query_params["softDeleted"] = soft_deleted + # Soft delete reload requires a generation, even for targets + # that don't include them in default query params (buckets). + query_params["generation"] = self.generation + headers = self._encryption_headers() + _add_etag_match_headers( + headers, if_etag_match=if_etag_match, if_etag_not_match=if_etag_not_match + ) + api_response = client._get_resource( + self.path, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=self, + ) + self._set_properties(api_response) + + def _patch_property(self, name, value): + """Update field of this object's properties. + + This method will only update the field provided and will not + touch the other fields. + + It **will not** reload the properties from the server. The behavior is + local only and syncing occurs via :meth:`patch`. + + :type name: str + :param name: The field name to update. + + :type value: object + :param value: The value being updated. + """ + self._changes.add(name) + self._properties[name] = value + + def _set_properties(self, value): + """Set the properties for the current object. + + :type value: dict or :class:`google.cloud.storage.batch._FutureDict` + :param value: The properties to be set. + """ + self._properties = value + # If the values are reset, the changes must as well. + self._changes = set() + + def patch( + self, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + override_unlocked_retention=False, + ): + """Sends all changed properties in a PATCH request. + + Updates the ``_properties`` with the response from the backend. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current object. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type override_unlocked_retention: bool + :param override_unlocked_retention: + (Optional) override_unlocked_retention must be set to True if the operation includes + a retention property that changes the mode from Unlocked to Locked, reduces the + retainUntilTime, or removes the retention configuration from the object. See: + https://cloud.google.com/storage/docs/json_api/v1/objects/patch + """ + client = self._require_client(client) + query_params = self._query_params + # Pass '?projection=full' here because 'PATCH' documented not + # to work properly w/ 'noAcl'. + query_params["projection"] = "full" + if override_unlocked_retention: + query_params["overrideUnlockedRetention"] = override_unlocked_retention + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + update_properties = {key: self._properties[key] for key in self._changes} + + # Make the API call. + api_response = client._patch_resource( + self.path, + update_properties, + query_params=query_params, + _target_object=self, + timeout=timeout, + retry=retry, + ) + self._set_properties(api_response) + + def update( + self, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + override_unlocked_retention=False, + ): + """Sends all properties in a PUT request. + + Updates the ``_properties`` with the response from the backend. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current object. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type override_unlocked_retention: bool + :param override_unlocked_retention: + (Optional) override_unlocked_retention must be set to True if the operation includes + a retention property that changes the mode from Unlocked to Locked, reduces the + retainUntilTime, or removes the retention configuration from the object. See: + https://cloud.google.com/storage/docs/json_api/v1/objects/patch + """ + client = self._require_client(client) + + query_params = self._query_params + query_params["projection"] = "full" + if override_unlocked_retention: + query_params["overrideUnlockedRetention"] = override_unlocked_retention + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + + api_response = client._put_resource( + self.path, + self._properties, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=self, + ) + self._set_properties(api_response) + + +def _scalar_property(fieldname): + """Create a property descriptor around the :class:`_PropertyMixin` helpers.""" + + def _getter(self): + """Scalar property getter.""" + return self._properties.get(fieldname) + + def _setter(self, value): + """Scalar property setter.""" + self._patch_property(fieldname, value) + + return property(_getter, _setter) + + +def _write_buffer_to_hash(buffer_object, hash_obj, digest_block_size=8192): + """Read blocks from a buffer and update a hash with them. + + :type buffer_object: bytes buffer + :param buffer_object: Buffer containing bytes used to update a hash object. + + :type hash_obj: object that implements update + :param hash_obj: A hash object (MD5 or CRC32-C). + + :type digest_block_size: int + :param digest_block_size: The block size to write to the hash. + Defaults to 8192. + """ + block = buffer_object.read(digest_block_size) + + while len(block) > 0: + hash_obj.update(block) + # Update the block for the next iteration. + block = buffer_object.read(digest_block_size) + + +def _base64_md5hash(buffer_object): + """Get MD5 hash of bytes (as base64). + + :type buffer_object: bytes buffer + :param buffer_object: Buffer containing bytes used to compute an MD5 + hash (as base64). + + :rtype: str + :returns: A base64 encoded digest of the MD5 hash. + """ + if sys.version_info >= (3, 9): + hash_obj = md5(usedforsecurity=False) + else: + hash_obj = md5() + _write_buffer_to_hash(buffer_object, hash_obj) + digest_bytes = hash_obj.digest() + return base64.b64encode(digest_bytes) + + +def _add_etag_match_headers(headers, **match_parameters): + """Add generation match parameters into the given parameters list. + + :type headers: dict + :param headers: Headers dict. + + :type match_parameters: dict + :param match_parameters: if*etag*match parameters to add. + """ + for snakecase_name, header_name in _ETAG_MATCH_PARAMETERS: + value = match_parameters.get(snakecase_name) + + if value is not None: + if isinstance(value, str): + value = [value] + headers[header_name] = ", ".join(value) + + +def _add_generation_match_parameters(parameters, **match_parameters): + """Add generation match parameters into the given parameters list. + + :type parameters: list or dict + :param parameters: Parameters list or dict. + + :type match_parameters: dict + :param match_parameters: if*generation*match parameters to add. + + :raises: :exc:`ValueError` if ``parameters`` is not a ``list()`` + or a ``dict()``. + """ + for snakecase_name, camelcase_name in _GENERATION_MATCH_PARAMETERS: + value = match_parameters.get(snakecase_name) + + if value is not None: + if isinstance(parameters, list): + parameters.append((camelcase_name, value)) + + elif isinstance(parameters, dict): + parameters[camelcase_name] = value + + else: + raise ValueError( + "`parameters` argument should be a dict() or a list()." + ) + + +def _raise_if_more_than_one_set(**kwargs): + """Raise ``ValueError`` exception if more than one parameter was set. + + :type error: :exc:`ValueError` + :param error: Description of which fields were set + + :raises: :class:`~ValueError` containing the fields that were set + """ + if sum(arg is not None for arg in kwargs.values()) > 1: + escaped_keys = [f"'{name}'" for name in kwargs.keys()] + + keys_but_last = ", ".join(escaped_keys[:-1]) + last_key = escaped_keys[-1] + + msg = f"Pass at most one of {keys_but_last} and {last_key}" + + raise ValueError(msg) + + +def _bucket_bound_hostname_url(host, scheme=None): + """Helper to build bucket bound hostname URL. + + :type host: str + :param host: Host name. + + :type scheme: str + :param scheme: (Optional) Web scheme. If passed, use it + as a scheme in the result URL. + + :rtype: str + :returns: A bucket bound hostname URL. + """ + url_parts = urlsplit(host) + if url_parts.scheme and url_parts.netloc: + return host + + return f"{scheme}://{host}" + + +def _get_invocation_id(): + return "gccl-invocation-id/" + str(uuid4()) + + +def _get_default_headers( + user_agent, + content_type="application/json; charset=UTF-8", + x_upload_content_type=None, + command=None, +): + """Get the headers for a request. + + :type user_agent: str + :param user_agent: The user-agent for requests. + + :type command: str + :param command: + (Optional) Information about which interface for the operation was + used, to be included in the X-Goog-API-Client header. Please leave + as None unless otherwise directed. + + :rtype: dict + :returns: The headers to be used for the request. + """ + x_goog_api_client = f"{user_agent} {_get_invocation_id()}" + + if command: + x_goog_api_client += f" gccl-gcs-cmd/{command}" + + return { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "User-Agent": user_agent, + "X-Goog-API-Client": x_goog_api_client, + "content-type": content_type, + "x-upload-content-type": x_upload_content_type or content_type, + } + + +def generate_random_56_bit_integer(): + """Generates a secure 56 bit random integer. + + + If 64 bit int is used, sometimes the random int generated is greater than + max positive value of signed 64 bit int which is 2^63 -1 causing overflow + issues. + + :rtype: int + :returns: A secure random 56 bit integer. + """ + # 7 bytes * 8 bits/byte = 56 bits + random_bytes = secrets.token_bytes(7) + # Convert bytes to an integer + return int.from_bytes(random_bytes, "big") diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_http.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_http.py new file mode 100644 index 0000000000000000000000000000000000000000..aea13cc574e7b63d1c7dcd9791efecbf7b5d52f1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_http.py @@ -0,0 +1,90 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Create / interact with Google Cloud Storage connections.""" + +import functools +from google.cloud import _http +from google.cloud.storage import __version__ +from google.cloud.storage import _helpers +from google.cloud.storage._opentelemetry_tracing import create_trace_span + + +class Connection(_http.JSONConnection): + """A connection to Google Cloud Storage via the JSON REST API. + + Mutual TLS will be enabled if the "GOOGLE_API_USE_CLIENT_CERTIFICATE" + environment variable is set to the exact string "true" (case-sensitive). + + Mutual TLS is not compatible with any API endpoint or universe domain + override at this time. If such settings are enabled along with + "GOOGLE_API_USE_CLIENT_CERTIFICATE", a ValueError will be raised. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: The client that owns the current connection. + + :type client_info: :class:`~google.api_core.client_info.ClientInfo` + :param client_info: (Optional) instance used to generate user agent. + + :type api_endpoint: str + :param api_endpoint: (Optional) api endpoint to use. + """ + + DEFAULT_API_ENDPOINT = _helpers._get_default_storage_base_url() + DEFAULT_API_MTLS_ENDPOINT = "https://storage.mtls.googleapis.com" + + def __init__(self, client, client_info=None, api_endpoint=None): + super(Connection, self).__init__(client, client_info) + self.API_BASE_URL = api_endpoint or self.DEFAULT_API_ENDPOINT + self.API_BASE_MTLS_URL = self.DEFAULT_API_MTLS_ENDPOINT + self.ALLOW_AUTO_SWITCH_TO_MTLS_URL = api_endpoint is None + self._client_info.client_library_version = __version__ + + # TODO: When metrics all use gccl, this should be removed #9552 + if self._client_info.user_agent is None: # pragma: no branch + self._client_info.user_agent = "" + agent_version = f"gcloud-python/{__version__}" + if agent_version not in self._client_info.user_agent: + self._client_info.user_agent += f" {agent_version} " + + API_VERSION = _helpers._API_VERSION + """The version of the API, used in building the API call's URL.""" + + API_URL_TEMPLATE = "{api_base_url}/storage/{api_version}{path}" + """A template for the URL of a particular API call.""" + + def api_request(self, *args, **kwargs): + retry = kwargs.pop("retry", None) + invocation_id = _helpers._get_invocation_id() + kwargs["extra_api_info"] = invocation_id + span_attributes = { + "gccl-invocation-id": invocation_id, + } + call = functools.partial(super(Connection, self).api_request, *args, **kwargs) + with create_trace_span( + name="Storage.Connection.api_request", + attributes=span_attributes, + client=self._client, + api_request=kwargs, + retry=retry, + ): + if retry: + # If this is a ConditionalRetryPolicy, check conditions. + try: + retry = retry.get_retry_policy_if_conditions_met(**kwargs) + except AttributeError: # This is not a ConditionalRetryPolicy. + pass + if retry: + call = retry(call) + return call() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..edab8f51d1aed7621542d12acd77965b81126328 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__init__.py @@ -0,0 +1,34 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for Google Media Downloads and Resumable Uploads. + +=========== +Subpackages +=========== + +Each subpackage is tailored to a specific transport library: + +* the :mod:`~google.cloud.storage._media.requests` subpackage uses the ``requests`` + transport library. + +.. _requests: http://docs.python-requests.org/ +""" + +from google.cloud.storage._media.common import UPLOAD_CHUNK_SIZE + + +__all__ = [ + "UPLOAD_CHUNK_SIZE", +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2619140e6d07663494da78a4762849e6953b438f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_download.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_download.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37b18db2f624d2c231c03dd0b1938c39bef7226d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_download.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_helpers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fce140ea498e079d992917d9df420281dad7afb8 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_helpers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_upload.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_upload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a42f4dfdd217bfe824018e0ac51902f6302995f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/_upload.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/common.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..369c67f3be6857b501f661e108c8462fb59569fa Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/__pycache__/common.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_download.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_download.py new file mode 100644 index 0000000000000000000000000000000000000000..422b98041a5517f85bb8ef9397cf1f03d6d21a22 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_download.py @@ -0,0 +1,625 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Virtual bases classes for downloading media from Google APIs.""" + + +import http.client +import re + +from google.cloud.storage._media import _helpers +from google.cloud.storage.exceptions import InvalidResponse +from google.cloud.storage.retry import DEFAULT_RETRY + + +_CONTENT_RANGE_RE = re.compile( + r"bytes (?P\d+)-(?P\d+)/(?P\d+)", + flags=re.IGNORECASE, +) +_ACCEPTABLE_STATUS_CODES = (http.client.OK, http.client.PARTIAL_CONTENT) +_GET = "GET" +_ZERO_CONTENT_RANGE_HEADER = "bytes */0" + + +class DownloadBase(object): + """Base class for download helpers. + + Defines core shared behavior across different download types. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. + end (int): The last byte in a range to be downloaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + retry (Optional[google.api_core.retry.Retry]): How to retry the RPC. + A None value will disable retries. A google.api_core.retry.Retry + value will enable retries, and the object will configure backoff and + timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + """ + + def __init__( + self, + media_url, + stream=None, + start=None, + end=None, + headers=None, + retry=DEFAULT_RETRY, + ): + self.media_url = media_url + self._stream = stream + self.start = start + self.end = end + if headers is None: + headers = {} + self._headers = headers + self._finished = False + self._retry_strategy = retry + + @property + def finished(self): + """bool: Flag indicating if the download has completed.""" + return self._finished + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class Download(DownloadBase): + """Helper to manage downloading a resource from a Google API. + + "Slices" of the resource can be retrieved by specifying a range + with ``start`` and / or ``end``. However, in typical usage, neither + ``start`` nor ``end`` is expected to be provided. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. If not + provided, but ``end`` is provided, will download from the + beginning to ``end`` of the media. + end (int): The last byte in a range to be downloaded. If not + provided, but ``start`` is provided, will download from the + ``start`` to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum (Optional[str]): The type of checksum to compute to verify + the integrity of the object. The response headers must contain + a checksum of the requested type. If the headers lack an + appropriate checksum (for instance in the case of transcoded or + ranged downloads where the remote service does not know the + correct checksum) an INFO-level log will be emitted. Supported + values are "md5", "crc32c", "auto" and None. The default is "auto", + which will try to detect if the C extension for crc32c is installed + and fall back to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + single_shot_download (Optional[bool]): If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + """ + + def __init__( + self, + media_url, + stream=None, + start=None, + end=None, + headers=None, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + super(Download, self).__init__( + media_url, stream=stream, start=start, end=end, headers=headers, retry=retry + ) + self.checksum = checksum + if self.checksum == "auto": + self.checksum = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + self.single_shot_download = single_shot_download + self._bytes_downloaded = 0 + self._expected_checksum = None + self._checksum_object = None + self._object_generation = None + + def _prepare_request(self): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always GET) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + Raises: + ValueError: If the current :class:`Download` has already + finished. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("A download can only be used once.") + + add_bytes_range(self.start, self.end, self._headers) + return _GET, self.media_url, None, self._headers + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Tombstone the current Download so it cannot be used again. + self._finished = True + _helpers.require_status_code( + response, _ACCEPTABLE_STATUS_CODES, self._get_status_code + ) + + def consume(self, transport, timeout=None): + """Consume the resource to be downloaded. + + If a ``stream`` is attached to this download, then the downloaded + resource will be written to the stream. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class ChunkedDownload(DownloadBase): + """Download a resource in chunks from a Google API. + + Args: + media_url (str): The URL containing the media to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each + request. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + will be used to concatenate chunks of the resource as they are + downloaded. + start (int): The first byte in a range to be downloaded. If not + provided, defaults to ``0``. + end (int): The last byte in a range to be downloaded. If not + provided, will download to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with each request, e.g. headers for data encryption + key headers. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each request. + + Raises: + ValueError: If ``start`` is negative. + """ + + def __init__( + self, + media_url, + chunk_size, + stream, + start=0, + end=None, + headers=None, + retry=DEFAULT_RETRY, + ): + if start < 0: + raise ValueError( + "On a chunked download the starting " "value cannot be negative." + ) + super(ChunkedDownload, self).__init__( + media_url, + stream=stream, + start=start, + end=end, + headers=headers, + retry=retry, + ) + self.chunk_size = chunk_size + self._bytes_downloaded = 0 + self._total_bytes = None + self._invalid = False + + @property + def bytes_downloaded(self): + """int: Number of bytes that have been downloaded.""" + return self._bytes_downloaded + + @property + def total_bytes(self): + """Optional[int]: The total number of bytes to be downloaded.""" + return self._total_bytes + + @property + def invalid(self): + """bool: Indicates if the download is in an invalid state. + + This will occur if a call to :meth:`consume_next_chunk` fails. + """ + return self._invalid + + def _get_byte_range(self): + """Determines the byte range for the next request. + + Returns: + Tuple[int, int]: The pair of begin and end byte for the next + chunked request. + """ + curr_start = self.start + self.bytes_downloaded + curr_end = curr_start + self.chunk_size - 1 + # Make sure ``curr_end`` does not exceed ``end``. + if self.end is not None: + curr_end = min(curr_end, self.end) + # Make sure ``curr_end`` does not exceed ``total_bytes - 1``. + if self.total_bytes is not None: + curr_end = min(curr_end, self.total_bytes - 1) + return curr_start, curr_end + + def _prepare_request(self): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used multiple times, so ``headers`` will + be mutated in between requests. However, we don't make a copy + since the same keys are being updated. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always GET) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + Raises: + ValueError: If the current download has finished. + ValueError: If the current download is invalid. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("Download has finished.") + if self.invalid: + raise ValueError("Download is invalid and cannot be re-used.") + + curr_start, curr_end = self._get_byte_range() + add_bytes_range(curr_start, curr_end, self._headers) + return _GET, self.media_url, None, self._headers + + def _make_invalid(self): + """Simple setter for ``invalid``. + + This is intended to be passed along as a callback to helpers that + raise an exception so they can mark this instance as invalid before + raising. + """ + self._invalid = True + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to write + a chunk to ``stream``. However, this will (almost) certainly not be + network I/O. + + Updates the current state after consuming a chunk. First, + increments ``bytes_downloaded`` by the number of bytes in the + ``content-length`` header. + + If ``total_bytes`` is already set, this assumes (but does not check) + that we already have the correct value and doesn't bother to check + that it agrees with the headers. + + We expect the **total** length to be in the ``content-range`` header, + but this header is only present on requests which sent the ``range`` + header. This response header should be of the form + ``bytes {start}-{end}/{total}`` and ``{end} - {start} + 1`` + should be the same as the ``Content-Length``. + + Args: + response (object): The HTTP response object (need headers). + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the number + of bytes in the body doesn't match the content length header. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Verify the response before updating the current instance. + if _check_for_zero_content_range( + response, self._get_status_code, self._get_headers + ): + self._finished = True + return + + _helpers.require_status_code( + response, + _ACCEPTABLE_STATUS_CODES, + self._get_status_code, + callback=self._make_invalid, + ) + headers = self._get_headers(response) + response_body = self._get_body(response) + + start_byte, end_byte, total_bytes = get_range_info( + response, self._get_headers, callback=self._make_invalid + ) + + transfer_encoding = headers.get("transfer-encoding") + + if transfer_encoding is None: + content_length = _helpers.header_required( + response, + "content-length", + self._get_headers, + callback=self._make_invalid, + ) + num_bytes = int(content_length) + if len(response_body) != num_bytes: + self._make_invalid() + raise InvalidResponse( + response, + "Response is different size than content-length", + "Expected", + num_bytes, + "Received", + len(response_body), + ) + else: + # 'content-length' header not allowed with chunked encoding. + num_bytes = end_byte - start_byte + 1 + + # First update ``bytes_downloaded``. + self._bytes_downloaded += num_bytes + # If the end byte is past ``end`` or ``total_bytes - 1`` we are done. + if self.end is not None and end_byte >= self.end: + self._finished = True + elif end_byte >= total_bytes - 1: + self._finished = True + # NOTE: We only use ``total_bytes`` if not already known. + if self.total_bytes is None: + self._total_bytes = total_bytes + # Write the response body to the stream. + self._stream.write(response_body) + + def consume_next_chunk(self, transport, timeout=None): + """Consume the next chunk of the resource to be downloaded. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +def add_bytes_range(start, end, headers): + """Add a bytes range to a header dictionary. + + Some possible inputs and the corresponding bytes ranges:: + + >>> headers = {} + >>> add_bytes_range(None, None, headers) + >>> headers + {} + >>> add_bytes_range(500, 999, headers) + >>> headers['range'] + 'bytes=500-999' + >>> add_bytes_range(None, 499, headers) + >>> headers['range'] + 'bytes=0-499' + >>> add_bytes_range(-500, None, headers) + >>> headers['range'] + 'bytes=-500' + >>> add_bytes_range(9500, None, headers) + >>> headers['range'] + 'bytes=9500-' + + Args: + start (Optional[int]): The first byte in a range. Can be zero, + positive, negative or :data:`None`. + end (Optional[int]): The last byte in a range. Assumed to be + positive. + headers (Mapping[str, str]): A headers mapping which can have the + bytes range added if at least one of ``start`` or ``end`` + is not :data:`None`. + """ + if start is None: + if end is None: + # No range to add. + return + else: + # NOTE: This assumes ``end`` is non-negative. + bytes_range = "0-{:d}".format(end) + else: + if end is None: + if start < 0: + bytes_range = "{:d}".format(start) + else: + bytes_range = "{:d}-".format(start) + else: + # NOTE: This is invalid if ``start < 0``. + bytes_range = "{:d}-{:d}".format(start, end) + + headers[_helpers.RANGE_HEADER] = "bytes=" + bytes_range + + +def get_range_info(response, get_headers, callback=_helpers.do_nothing): + """Get the start, end and total bytes from a content range header. + + Args: + response (object): An HTTP response object. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + Tuple[int, int, int]: The start byte, end byte and total bytes. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the + ``Content-Range`` header is not of the form + ``bytes {start}-{end}/{total}``. + """ + content_range = _helpers.header_required( + response, _helpers.CONTENT_RANGE_HEADER, get_headers, callback=callback + ) + match = _CONTENT_RANGE_RE.match(content_range) + if match is None: + callback() + raise InvalidResponse( + response, + "Unexpected content-range header", + content_range, + 'Expected to be of the form "bytes {start}-{end}/{total}"', + ) + + return ( + int(match.group("start_byte")), + int(match.group("end_byte")), + int(match.group("total_bytes")), + ) + + +def _check_for_zero_content_range(response, get_status_code, get_headers): + """Validate if response status code is 416 and content range is zero. + + This is the special case for handling zero bytes files. + + Args: + response (object): An HTTP response object. + get_status_code (Callable[Any, int]): Helper to get a status code + from a response. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + + Returns: + bool: True if content range total bytes is zero, false otherwise. + """ + if get_status_code(response) == http.client.REQUESTED_RANGE_NOT_SATISFIABLE: + content_range = _helpers.header_required( + response, + _helpers.CONTENT_RANGE_HEADER, + get_headers, + callback=_helpers.do_nothing, + ) + if content_range == _ZERO_CONTENT_RANGE_HEADER: + return True + return False diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c07101edabbab8db274515d82dade061812a27f5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_helpers.py @@ -0,0 +1,383 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared utilities used by both downloads and uploads.""" + +from __future__ import absolute_import + +import base64 +import hashlib +import logging + +from urllib.parse import parse_qs +from urllib.parse import urlencode +from urllib.parse import urlsplit +from urllib.parse import urlunsplit + +from google.cloud.storage import retry +from google.cloud.storage.exceptions import InvalidResponse + + +RANGE_HEADER = "range" +CONTENT_RANGE_HEADER = "content-range" +CONTENT_ENCODING_HEADER = "content-encoding" + +_SLOW_CRC32C_WARNING = ( + "Currently using crcmod in pure python form. This is a slow " + "implementation. Python 3 has a faster implementation, `google-crc32c`, " + "which will be used if it is installed." +) +_GENERATION_HEADER = "x-goog-generation" +_HASH_HEADER = "x-goog-hash" +_STORED_CONTENT_ENCODING_HEADER = "x-goog-stored-content-encoding" + +_MISSING_CHECKSUM = """\ +No {checksum_type} checksum was returned from the service while downloading {} +(which happens for composite objects), so client-side content integrity +checking is not being performed.""" +_LOGGER = logging.getLogger(__name__) + + +def do_nothing(): + """Simple default callback.""" + + +def header_required(response, name, get_headers, callback=do_nothing): + """Checks that a specific header is in a headers dictionary. + + Args: + response (object): An HTTP response object, expected to have a + ``headers`` attribute that is a ``Mapping[str, str]``. + name (str): The name of a required header. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + str: The desired header. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the header + is missing. + """ + headers = get_headers(response) + if name not in headers: + callback() + raise InvalidResponse(response, "Response headers must contain header", name) + + return headers[name] + + +def require_status_code(response, status_codes, get_status_code, callback=do_nothing): + """Require a response has a status code among a list. + + Args: + response (object): The HTTP response object. + status_codes (tuple): The acceptable status codes. + get_status_code (Callable[Any, int]): Helper to get a status code + from a response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + int: The status code. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status code + is not one of the values in ``status_codes``. + """ + status_code = get_status_code(response) + if status_code not in status_codes: + if status_code not in retry._RETRYABLE_STATUS_CODES: + callback() + raise InvalidResponse( + response, + "Request failed with status code", + status_code, + "Expected one of", + *status_codes + ) + return status_code + + +def _get_metadata_key(checksum_type): + if checksum_type == "md5": + return "md5Hash" + else: + return checksum_type + + +def prepare_checksum_digest(digest_bytestring): + """Convert a checksum object into a digest encoded for an HTTP header. + + Args: + bytes: A checksum digest bytestring. + + Returns: + str: A base64 string representation of the input. + """ + encoded_digest = base64.b64encode(digest_bytestring) + # NOTE: ``b64encode`` returns ``bytes``, but HTTP headers expect ``str``. + return encoded_digest.decode("utf-8") + + +def _get_expected_checksum(response, get_headers, media_url, checksum_type): + """Get the expected checksum and checksum object for the download response. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + media_url (str): The URL containing the media to be downloaded. + checksum_type Optional(str): The checksum type to read from the headers, + exactly as it will appear in the headers (case-sensitive). Must be + "md5", "crc32c" or None. + + Returns: + Tuple (Optional[str], object): The expected checksum of the response, + if it can be detected from the ``X-Goog-Hash`` header, and the + appropriate checksum object for the expected checksum. + """ + if checksum_type not in ["md5", "crc32c", None]: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + elif checksum_type in ["md5", "crc32c"]: + headers = get_headers(response) + expected_checksum = _parse_checksum_header( + headers.get(_HASH_HEADER), response, checksum_label=checksum_type + ) + + if expected_checksum is None: + msg = _MISSING_CHECKSUM.format( + media_url, checksum_type=checksum_type.upper() + ) + _LOGGER.info(msg) + checksum_object = _DoNothingHash() + else: + checksum_object = _get_checksum_object(checksum_type) + else: + expected_checksum = None + checksum_object = _DoNothingHash() + + return (expected_checksum, checksum_object) + + +def _get_uploaded_checksum_from_headers(response, get_headers, checksum_type): + """Get the computed checksum and checksum object from the response headers. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + checksum_type Optional(str): The checksum type to read from the headers, + exactly as it will appear in the headers (case-sensitive). Must be + "md5", "crc32c" or None. + + Returns: + Tuple (Optional[str], object): The checksum of the response, + if it can be detected from the ``X-Goog-Hash`` header, and the + appropriate checksum object for the expected checksum. + """ + if checksum_type not in ["md5", "crc32c", None]: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + elif checksum_type in ["md5", "crc32c"]: + headers = get_headers(response) + remote_checksum = _parse_checksum_header( + headers.get(_HASH_HEADER), response, checksum_label=checksum_type + ) + else: + remote_checksum = None + + return remote_checksum + + +def _parse_checksum_header(header_value, response, checksum_label): + """Parses the checksum header from an ``X-Goog-Hash`` value. + + .. _header reference: https://cloud.google.com/storage/docs/\ + xml-api/reference-headers#xgooghash + + Expects ``header_value`` (if not :data:`None`) to be in one of the three + following formats: + + * ``crc32c=n03x6A==`` + * ``md5=Ojk9c3dhfxgoKVVHYwFbHQ==`` + * ``crc32c=n03x6A==,md5=Ojk9c3dhfxgoKVVHYwFbHQ==`` + + See the `header reference`_ for more information. + + Args: + header_value (Optional[str]): The ``X-Goog-Hash`` header from + a download response. + response (~requests.Response): The HTTP response object. + checksum_label (str): The label of the header value to read, as in the + examples above. Typically "md5" or "crc32c" + + Returns: + Optional[str]: The expected checksum of the response, if it + can be detected from the ``X-Goog-Hash`` header; otherwise, None. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If there are + multiple checksums of the requested type in ``header_value``. + """ + if header_value is None: + return None + + matches = [] + for checksum in header_value.split(","): + name, value = checksum.split("=", 1) + # Official docs say "," is the separator, but real-world responses have encountered ", " + if name.lstrip() == checksum_label: + matches.append(value) + + if len(matches) == 0: + return None + elif len(matches) == 1: + return matches[0] + else: + raise InvalidResponse( + response, + "X-Goog-Hash header had multiple ``{}`` values.".format(checksum_label), + header_value, + matches, + ) + + +def _get_checksum_object(checksum_type): + """Respond with a checksum object for a supported type, if not None. + + Raises ValueError if checksum_type is unsupported. + """ + if checksum_type == "md5": + return hashlib.md5() + elif checksum_type == "crc32c": + # In order to support platforms that don't have google_crc32c + # support, only perform the import on demand. + import google_crc32c + + return google_crc32c.Checksum() + elif checksum_type is None: + return None + else: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + + +def _is_crc32c_available_and_fast(): + """Return True if the google_crc32c C extension is installed. + + Return False if either the package is not installed, or if only the + pure-Python version is installed. + """ + try: + import google_crc32c + + if google_crc32c.implementation == "c": + return True + except Exception: + pass + return False + + +def _parse_generation_header(response, get_headers): + """Parses the generation header from an ``X-Goog-Generation`` value. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + + Returns: + Optional[long]: The object generation from the response, if it + can be detected from the ``X-Goog-Generation`` header; otherwise, None. + """ + headers = get_headers(response) + object_generation = headers.get(_GENERATION_HEADER, None) + + if object_generation is None: + return None + else: + return int(object_generation) + + +def _get_generation_from_url(media_url): + """Retrieve the object generation query param specified in the media url. + + Args: + media_url (str): The URL containing the media to be downloaded. + + Returns: + long: The object generation from the media url if exists; otherwise, None. + """ + + _, _, _, query, _ = urlsplit(media_url) + query_params = parse_qs(query) + object_generation = query_params.get("generation", None) + + if object_generation is None: + return None + else: + return int(object_generation[0]) + + +def add_query_parameters(media_url, query_params): + """Add query parameters to a base url. + + Args: + media_url (str): The URL containing the media to be downloaded. + query_params (dict): Names and values of the query parameters to add. + + Returns: + str: URL with additional query strings appended. + """ + + if len(query_params) == 0: + return media_url + + scheme, netloc, path, query, frag = urlsplit(media_url) + params = parse_qs(query) + new_params = {**params, **query_params} + query = urlencode(new_params, doseq=True) + return urlunsplit((scheme, netloc, path, query, frag)) + + +def _is_decompressive_transcoding(response, get_headers): + """Returns True if the object was served decompressed. This happens when the + "x-goog-stored-content-encoding" header is "gzip" and "content-encoding" header + is not "gzip". See more at: https://cloud.google.com/storage/docs/transcoding#transcoding_and_gzip + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + Returns: + bool: Returns True if decompressive transcoding has occurred; otherwise, False. + """ + headers = get_headers(response) + return ( + headers.get(_STORED_CONTENT_ENCODING_HEADER) == "gzip" + and headers.get(CONTENT_ENCODING_HEADER) != "gzip" + ) + + +class _DoNothingHash(object): + """Do-nothing hash object. + + Intended as a stand-in for ``hashlib.md5`` or a crc32c checksum + implementation in cases where it isn't necessary to compute the hash. + """ + + def update(self, unused_chunk): + """Do-nothing ``update`` method. + + Intended to match the interface of ``hashlib.md5`` and other checksums. + + Args: + unused_chunk (bytes): A chunk of data. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_upload.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..4a919d18ac84ce7d49708b7233cfc4344fca8080 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/_upload.py @@ -0,0 +1,1647 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Virtual bases classes for uploading media via Google APIs. + +Supported here are: + +* simple (media) uploads +* multipart uploads that contain both metadata and a small file as payload +* resumable uploads (with metadata as well) +""" + +import http.client +import json +import os +import random +import re +import sys +import urllib.parse + +from google.cloud.storage._media import _helpers +from google.cloud.storage._media import UPLOAD_CHUNK_SIZE +from google.cloud.storage.exceptions import InvalidResponse +from google.cloud.storage.exceptions import DataCorruption +from google.cloud.storage.retry import DEFAULT_RETRY + +from xml.etree import ElementTree + + +_CONTENT_TYPE_HEADER = "content-type" +_CONTENT_RANGE_TEMPLATE = "bytes {:d}-{:d}/{:d}" +_RANGE_UNKNOWN_TEMPLATE = "bytes {:d}-{:d}/*" +_EMPTY_RANGE_TEMPLATE = "bytes */{:d}" +_BOUNDARY_WIDTH = len(str(sys.maxsize - 1)) +_BOUNDARY_FORMAT = "==============={{:0{:d}d}}==".format(_BOUNDARY_WIDTH) +_MULTIPART_SEP = b"--" +_CRLF = b"\r\n" +_MULTIPART_BEGIN = b"\r\ncontent-type: application/json; charset=UTF-8\r\n\r\n" +_RELATED_HEADER = b'multipart/related; boundary="' +_BYTES_RANGE_RE = re.compile(r"bytes=0-(?P\d+)", flags=re.IGNORECASE) +_STREAM_ERROR_TEMPLATE = ( + "Bytes stream is in unexpected state. " + "The local stream has had {:d} bytes read from it while " + "{:d} bytes have already been updated (they should match)." +) +_STREAM_READ_PAST_TEMPLATE = ( + "{:d} bytes have been read from the stream, which exceeds " + "the expected total {:d}." +) +_DELETE = "DELETE" +_POST = "POST" +_PUT = "PUT" +_UPLOAD_CHECKSUM_MISMATCH_MESSAGE = ( + "The computed ``{}`` checksum, ``{}``, and the checksum reported by the " + "remote host, ``{}``, did not match." +) +_UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE = ( + "Response metadata had no ``{}`` value; checksum could not be validated." +) +_UPLOAD_HEADER_NO_APPROPRIATE_CHECKSUM_MESSAGE = ( + "Response headers had no ``{}`` value; checksum could not be validated." +) +_MPU_INITIATE_QUERY = "?uploads" +_MPU_PART_QUERY_TEMPLATE = "?partNumber={part}&uploadId={upload_id}" +_S3_COMPAT_XML_NAMESPACE = "{http://s3.amazonaws.com/doc/2006-03-01/}" +_UPLOAD_ID_NODE = "UploadId" +_MPU_FINAL_QUERY_TEMPLATE = "?uploadId={upload_id}" + + +class UploadBase(object): + """Base class for upload helpers. + + Defines core shared behavior across different upload types. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def __init__(self, upload_url, headers=None, retry=DEFAULT_RETRY): + self.upload_url = upload_url + if headers is None: + headers = {} + self._headers = headers + self._finished = False + self._retry_strategy = retry + + @property + def finished(self): + """bool: Flag indicating if the upload has completed.""" + return self._finished + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Tombstone the current upload so it cannot be used again (in either + # failure or success). + self._finished = True + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class SimpleUpload(UploadBase): + """Upload a resource to a Google API. + + A **simple** media upload sends no metadata and completes the upload + in a single request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def _prepare_request(self, data, content_type): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used only once, so ``headers`` will be + mutated by having a new key added to it. + + Args: + data (bytes): The resource content to be uploaded. + content_type (str): The content type for the request. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already finished. + TypeError: If ``data`` isn't bytes. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("An upload can only be used once.") + + if not isinstance(data, bytes): + raise TypeError("`data` must be bytes, received", type(data)) + self._headers[_CONTENT_TYPE_HEADER] = content_type + return _POST, self.upload_url, data, self._headers + + def transmit(self, transport, data, content_type, timeout=None): + """Transmit the resource to be uploaded. + + Args: + transport (object): An object which can make authenticated + requests. + data (bytes): The resource content to be uploaded. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class MultipartUpload(UploadBase): + """Upload a resource with metadata to a Google API. + + A **multipart** upload sends both metadata and the resource in a single + (multipart) request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The request metadata will be amended + to include the computed value. Using this option will override a + manually-set checksum value. Supported values are "md5", + "crc32c", "auto", and None. The default is "auto", which will try + to detect if the C extension for crc32c is installed and fall back + to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def __init__(self, upload_url, headers=None, checksum="auto", retry=DEFAULT_RETRY): + super(MultipartUpload, self).__init__(upload_url, headers=headers, retry=retry) + self._checksum_type = checksum + if self._checksum_type == "auto": + self._checksum_type = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + + def _prepare_request(self, data, metadata, content_type): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used only once, so ``headers`` will be + mutated by having a new key added to it. + + Args: + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already finished. + TypeError: If ``data`` isn't bytes. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("An upload can only be used once.") + + if not isinstance(data, bytes): + raise TypeError("`data` must be bytes, received", type(data)) + + checksum_object = _helpers._get_checksum_object(self._checksum_type) + if checksum_object is not None: + checksum_object.update(data) + actual_checksum = _helpers.prepare_checksum_digest(checksum_object.digest()) + metadata_key = _helpers._get_metadata_key(self._checksum_type) + metadata[metadata_key] = actual_checksum + + content, multipart_boundary = construct_multipart_request( + data, metadata, content_type + ) + multipart_content_type = _RELATED_HEADER + multipart_boundary + b'"' + self._headers[_CONTENT_TYPE_HEADER] = multipart_content_type + + return _POST, self.upload_url, content, self._headers + + def transmit(self, transport, data, metadata, content_type, timeout=None): + """Transmit the resource to be uploaded. + + Args: + transport (object): An object which can make authenticated + requests. + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class ResumableUpload(UploadBase): + """Initiate and fulfill a resumable upload to a Google API. + + A **resumable** upload sends an initial request with the resource metadata + and then gets assigned an upload ID / upload URL to send bytes to. + Using the upload URL, the upload is then done in chunks (determined by + the user) until all bytes have been uploaded. + + Args: + upload_url (str): The URL where the resumable upload will be initiated. + chunk_size (int): The size of each chunk used to upload the resource. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be checked + and google.cloud.storage.exceptions.DataCorruption will be raised on + a mismatch. The corrupted file will not be deleted from the remote + host automatically. Supported values are "md5", "crc32c", "auto", + and None. The default is "auto", which will try to detect if the C + extension for crc32c is installed and fall back to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + + Raises: + ValueError: If ``chunk_size`` is not a multiple of + :data:`.UPLOAD_CHUNK_SIZE`. + """ + + def __init__( + self, + upload_url, + chunk_size, + checksum="auto", + headers=None, + retry=DEFAULT_RETRY, + ): + super(ResumableUpload, self).__init__(upload_url, headers=headers, retry=retry) + if chunk_size % UPLOAD_CHUNK_SIZE != 0: + raise ValueError( + "{} KB must divide chunk size".format(UPLOAD_CHUNK_SIZE / 1024) + ) + self._chunk_size = chunk_size + self._stream = None + self._content_type = None + self._bytes_uploaded = 0 + self._bytes_checksummed = 0 + self._checksum_type = checksum + if self._checksum_type == "auto": + self._checksum_type = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + self._checksum_object = None + self._total_bytes = None + self._resumable_url = None + self._invalid = False + + @property + def invalid(self): + """bool: Indicates if the upload is in an invalid state. + + This will occur if a call to :meth:`transmit_next_chunk` fails. + To recover from such a failure, call :meth:`recover`. + """ + return self._invalid + + @property + def chunk_size(self): + """int: The size of each chunk used to upload the resource.""" + return self._chunk_size + + @property + def resumable_url(self): + """Optional[str]: The URL of the in-progress resumable upload.""" + return self._resumable_url + + @property + def bytes_uploaded(self): + """int: Number of bytes that have been uploaded.""" + return self._bytes_uploaded + + @property + def total_bytes(self): + """Optional[int]: The total number of bytes to be uploaded. + + If this upload is initiated (via :meth:`initiate`) with + ``stream_final=True``, this value will be populated based on the size + of the ``stream`` being uploaded. (By default ``stream_final=True``.) + + If this upload is initiated with ``stream_final=False``, + :attr:`total_bytes` will be :data:`None` since it cannot be + determined from the stream. + """ + return self._total_bytes + + def _prepare_initiate_request( + self, + stream, + metadata, + content_type, + total_bytes=None, + stream_final=True, + ): + """Prepare the contents of HTTP request to initiate upload. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already been initiated. + ValueError: If ``stream`` is not at the beginning. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.resumable_url is not None: + raise ValueError("This upload has already been initiated.") + if stream.tell() != 0: + raise ValueError("Stream must be at beginning.") + + self._stream = stream + self._content_type = content_type + + # Signed URL requires content type set directly - not through x-upload-content-type + parse_result = urllib.parse.urlparse(self.upload_url) + parsed_query = urllib.parse.parse_qs(parse_result.query) + if "x-goog-signature" in parsed_query or "X-Goog-Signature" in parsed_query: + # Deconstruct **self._headers first so that content type defined here takes priority + headers = {**self._headers, _CONTENT_TYPE_HEADER: content_type} + else: + # Deconstruct **self._headers first so that content type defined here takes priority + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: "application/json; charset=UTF-8", + "x-upload-content-type": content_type, + } + # Set the total bytes if possible. + if total_bytes is not None: + self._total_bytes = total_bytes + elif stream_final: + self._total_bytes = get_total_bytes(stream) + # Add the total bytes to the headers if set. + if self._total_bytes is not None: + content_length = "{:d}".format(self._total_bytes) + headers["x-upload-content-length"] = content_length + + payload = json.dumps(metadata).encode("utf-8") + return _POST, self.upload_url, payload, headers + + def _process_initiate_response(self, response): + """Process the response from an HTTP request that initiated upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + This method takes the URL from the ``Location`` header and stores it + for future use. Within that URL, we assume the ``upload_id`` query + parameter has been included, but we do not check. + + Args: + response (object): The HTTP response object (need headers). + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code( + response, + (http.client.OK, http.client.CREATED), + self._get_status_code, + callback=self._make_invalid, + ) + self._resumable_url = _helpers.header_required( + response, "location", self._get_headers + ) + + def initiate( + self, + transport, + stream, + metadata, + content_type, + total_bytes=None, + stream_final=True, + timeout=None, + ): + """Initiate a resumable upload. + + By default, this method assumes your ``stream`` is in a "final" + state ready to transmit. However, ``stream_final=False`` can be used + to indicate that the size of the resource is not known. This can happen + if bytes are being dynamically fed into ``stream``, e.g. if the stream + is attached to application logs. + + If ``stream_final=False`` is used, :attr:`chunk_size` bytes will be + read from the stream every time :meth:`transmit_next_chunk` is called. + If one of those reads produces strictly fewer bites than the chunk + size, the upload will be concluded. + + Args: + transport (object): An object which can make authenticated + requests. + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_request(self): + """Prepare the contents of HTTP request to upload a chunk. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to read + a chunk from ``stream`` (via :func:`get_next_chunk`). However, this + will (almost) certainly not be network I/O. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request + * headers for the request + + The headers incorporate the ``_headers`` on the current instance. + + Raises: + ValueError: If the current upload has finished. + ValueError: If the current upload is in an invalid state. + ValueError: If the current upload has not been initiated. + ValueError: If the location in the stream (i.e. ``stream.tell()``) + does not agree with ``bytes_uploaded``. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("Upload has finished.") + if self.invalid: + raise ValueError( + "Upload is in an invalid state. To recover call `recover()`." + ) + if self.resumable_url is None: + raise ValueError( + "This upload has not been initiated. Please call " + "initiate() before beginning to transmit chunks." + ) + + start_byte, payload, content_range = get_next_chunk( + self._stream, self._chunk_size, self._total_bytes + ) + if start_byte != self.bytes_uploaded: + msg = _STREAM_ERROR_TEMPLATE.format(start_byte, self.bytes_uploaded) + raise ValueError(msg) + + self._update_checksum(start_byte, payload) + + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: self._content_type, + _helpers.CONTENT_RANGE_HEADER: content_range, + } + if (start_byte + len(payload) == self._total_bytes) and ( + self._checksum_object is not None + ): + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + headers["x-goog-hash"] = f"{self._checksum_type}={local_checksum}" + return _PUT, self.resumable_url, payload, headers + + def _update_checksum(self, start_byte, payload): + """Update the checksum with the payload if not already updated. + + Because error recovery can result in bytes being transmitted more than + once, the checksum tracks the number of bytes checked in + self._bytes_checksummed and skips bytes that have already been summed. + """ + if not self._checksum_type: + return + + if not self._checksum_object: + self._checksum_object = _helpers._get_checksum_object(self._checksum_type) + + if start_byte < self._bytes_checksummed: + offset = self._bytes_checksummed - start_byte + data = payload[offset:] + else: + data = payload + + self._checksum_object.update(data) + self._bytes_checksummed += len(data) + + def _make_invalid(self): + """Simple setter for ``invalid``. + + This is intended to be passed along as a callback to helpers that + raise an exception so they can mark this instance as invalid before + raising. + """ + self._invalid = True + + def _process_resumable_response(self, response, bytes_sent): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + bytes_sent (int): The number of bytes sent in the request that + ``response`` was returned for. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is 308 and the ``range`` header is not of the form + ``bytes 0-{end}``. + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200 or 308. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + status_code = _helpers.require_status_code( + response, + (http.client.OK, http.client.PERMANENT_REDIRECT), + self._get_status_code, + callback=self._make_invalid, + ) + if status_code == http.client.OK: + # NOTE: We use the "local" information of ``bytes_sent`` to update + # ``bytes_uploaded``, but do not verify this against other + # state. However, there may be some other information: + # + # * a ``size`` key in JSON response body + # * the ``total_bytes`` attribute (if set) + # * ``stream.tell()`` (relying on fact that ``initiate()`` + # requires stream to be at the beginning) + self._bytes_uploaded = self._bytes_uploaded + bytes_sent + # Tombstone the current upload so it cannot be used again. + self._finished = True + # Validate the checksum. This can raise an exception on failure. + self._validate_checksum(response) + else: + bytes_range = _helpers.header_required( + response, + _helpers.RANGE_HEADER, + self._get_headers, + callback=self._make_invalid, + ) + match = _BYTES_RANGE_RE.match(bytes_range) + if match is None: + self._make_invalid() + raise InvalidResponse( + response, + 'Unexpected "range" header', + bytes_range, + 'Expected to be of the form "bytes=0-{end}"', + ) + self._bytes_uploaded = int(match.group("end_byte")) + 1 + + def _validate_checksum(self, response): + """Check the computed checksum, if any, against the recieved metadata. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the checksum + computed locally and the checksum reported by the remote host do + not match. + """ + if self._checksum_type is None: + return + metadata_key = _helpers._get_metadata_key(self._checksum_type) + metadata = response.json() + remote_checksum = metadata.get(metadata_key) + if remote_checksum is None: + raise InvalidResponse( + response, + _UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE.format(metadata_key), + self._get_headers(response), + ) + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + if local_checksum != remote_checksum: + raise DataCorruption( + response, + _UPLOAD_CHECKSUM_MISMATCH_MESSAGE.format( + self._checksum_type.upper(), local_checksum, remote_checksum + ), + ) + + def transmit_next_chunk(self, transport, timeout=None): + """Transmit the next chunk of the resource to be uploaded. + + If the current upload was initiated with ``stream_final=False``, + this method will dynamically determine if the upload has completed. + The upload will be considered complete if the stream produces + fewer than :attr:`chunk_size` bytes when a chunk is read from it. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_recover_request(self): + """Prepare the contents of HTTP request to recover from failure. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + We assume that the :attr:`resumable_url` is set (i.e. the only way + the upload can end up :attr:`invalid` is if it has been initiated. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + The headers **do not** incorporate the ``_headers`` on the + current instance. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + headers = {_helpers.CONTENT_RANGE_HEADER: "bytes */*"} + return _PUT, self.resumable_url, None, headers + + def _process_recover_response(self, response): + """Process the response from an HTTP request to recover from failure. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 308. + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is 308 and the ``range`` header is not of the form + ``bytes 0-{end}``. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code( + response, (http.client.PERMANENT_REDIRECT,), self._get_status_code + ) + headers = self._get_headers(response) + if _helpers.RANGE_HEADER in headers: + bytes_range = headers[_helpers.RANGE_HEADER] + match = _BYTES_RANGE_RE.match(bytes_range) + if match is None: + raise InvalidResponse( + response, + 'Unexpected "range" header', + bytes_range, + 'Expected to be of the form "bytes=0-{end}"', + ) + self._bytes_uploaded = int(match.group("end_byte")) + 1 + else: + # In this case, the upload has not "begun". + self._bytes_uploaded = 0 + + self._stream.seek(self._bytes_uploaded) + self._invalid = False + + def recover(self, transport): + """Recover from a failure. + + This method should be used when a :class:`ResumableUpload` is in an + :attr:`~ResumableUpload.invalid` state due to a request failure. + + This will verify the progress with the server and make sure the + current upload is in a valid state before :meth:`transmit_next_chunk` + can be used again. + + Args: + transport (object): An object which can make authenticated + requests. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class XMLMPUContainer(UploadBase): + """Initiate and close an upload using the XML MPU API. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with this container object, the + uploading of individual parts is handled separately, by XMLMPUPart objects + spawned from this container class. The XMLMPUPart objects are not + necessarily in the same process as the container, so they do not update the + container automatically. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). The + initiate, PUT, and finalization requests will all use this URL, with + varying query parameters. + filename (str): The name (path) of the file to upload. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + upload_id (Optional(str)): The ID of the upload from the initialization + response. + """ + + def __init__( + self, + upload_url, + filename, + headers=None, + upload_id=None, + retry=DEFAULT_RETRY, + ): + super().__init__(upload_url, headers=headers, retry=retry) + self._filename = filename + self._upload_id = upload_id + self._parts = {} + + @property + def upload_id(self): + return self._upload_id + + def register_part(self, part_number, etag): + """Register an uploaded part by part number and corresponding etag. + + XMLMPUPart objects represent individual parts, and their part number + and etag can be registered to the container object with this method + and therefore incorporated in the finalize() call to finish the upload. + + This method accepts part_number and etag, but not XMLMPUPart objects + themselves, to reduce the complexity involved in running XMLMPUPart + uploads in separate processes. + + Args: + part_number (int): The part number. Parts are assembled into the + final uploaded object with finalize() in order of their part + numbers. + etag (str): The etag included in the server response after upload. + """ + self._parts[part_number] = etag + + def _prepare_initiate_request(self, content_type): + """Prepare the contents of HTTP request to initiate upload. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already been initiated. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.upload_id is not None: + raise ValueError("This upload has already been initiated.") + + initiate_url = self.upload_url + _MPU_INITIATE_QUERY + + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: content_type, + } + return _POST, initiate_url, None, headers + + def _process_initiate_response(self, response): + """Process the response from an HTTP request that initiated the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + This method takes the URL from the ``Location`` header and stores it + for future use. Within that URL, we assume the ``upload_id`` query + parameter has been included, but we do not check. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + root = ElementTree.fromstring(response.text) + self._upload_id = root.find(_S3_COMPAT_XML_NAMESPACE + _UPLOAD_ID_NODE).text + + def initiate( + self, + transport, + content_type, + timeout=None, + ): + """Initiate an MPU and record the upload ID. + + Args: + transport (object): An object which can make authenticated + requests. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_finalize_request(self): + """Prepare the contents of an HTTP request to finalize the upload. + + All of the parts must be registered before calling this method. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the upload has not been initiated. + """ + if self.upload_id is None: + raise ValueError("This upload has not yet been initiated.") + + final_query = _MPU_FINAL_QUERY_TEMPLATE.format(upload_id=self._upload_id) + finalize_url = self.upload_url + final_query + final_xml_root = ElementTree.Element("CompleteMultipartUpload") + for part_number, etag in self._parts.items(): + part = ElementTree.SubElement(final_xml_root, "Part") # put in a loop + ElementTree.SubElement(part, "PartNumber").text = str(part_number) + ElementTree.SubElement(part, "ETag").text = etag + payload = ElementTree.tostring(final_xml_root) + return _POST, finalize_url, payload, self._headers + + def _process_finalize_response(self, response): + """Process the response from an HTTP request that finalized the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + self._finished = True + + def finalize( + self, + transport, + timeout=None, + ): + """Finalize an MPU request with all the parts. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_cancel_request(self): + """Prepare the contents of an HTTP request to cancel the upload. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always DELETE) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the upload has not been initiated. + """ + if self.upload_id is None: + raise ValueError("This upload has not yet been initiated.") + + cancel_query = _MPU_FINAL_QUERY_TEMPLATE.format(upload_id=self._upload_id) + cancel_url = self.upload_url + cancel_query + return _DELETE, cancel_url, None, self._headers + + def _process_cancel_response(self, response): + """Process the response from an HTTP request that canceled the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 204. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + + _helpers.require_status_code( + response, (http.client.NO_CONTENT,), self._get_status_code + ) + + def cancel( + self, + transport, + timeout=None, + ): + """Cancel an MPU request and permanently delete any uploaded parts. + + This cannot be undone. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class XMLMPUPart(UploadBase): + """Upload a single part of an existing XML MPU container. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with the container object, the + uploading of individual parts is handled separately by multiple objects + of this class. Once a part is uploaded, it can be registered with the + container with `container.register_part(part.part_number, part.etag)`. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). + upload_id (str): The ID of the upload from the initialization response. + filename (str): The name (path) of the file to upload. + start (int): The byte index of the beginning of the part. + end (int): The byte index of the end of the part. + part_number (int): The part number. Part numbers will be assembled in + sequential order when the container is finalized. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + checksum (Optional([str])): The type of checksum to compute to verify + the integrity of the object. The request headers will be amended + to include the computed value. Supported values are "md5", "crc32c", + "auto" and None. The default is "auto", which will try to detect if + the C extension for crc32c is installed and fall back to md5 + otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL of the object (without query parameters). + upload_id (str): The ID of the upload from the initialization response. + filename (str): The name (path) of the file to upload. + start (int): The byte index of the beginning of the part. + end (int): The byte index of the end of the part. + part_number (int): The part number. Part numbers will be assembled in + sequential order when the container is finalized. + etag (Optional(str)): The etag returned by the service after upload. + """ + + def __init__( + self, + upload_url, + upload_id, + filename, + start, + end, + part_number, + headers=None, + checksum="auto", + retry=DEFAULT_RETRY, + ): + super().__init__(upload_url, headers=headers, retry=retry) + self._filename = filename + self._start = start + self._end = end + self._upload_id = upload_id + self._part_number = part_number + self._etag = None + self._checksum_type = checksum + if self._checksum_type == "auto": + self._checksum_type = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + self._checksum_object = None + + @property + def part_number(self): + return self._part_number + + @property + def upload_id(self): + return self._upload_id + + @property + def filename(self): + return self._filename + + @property + def etag(self): + return self._etag + + @property + def start(self): + return self._start + + @property + def end(self): + return self._end + + def _prepare_upload_request(self): + """Prepare the contents of HTTP request to upload a part. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to read + a part from ``stream`` (via :func:`get_part_payload`). However, this + will (almost) certainly not be network I/O. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request + * headers for the request + + The headers incorporate the ``_headers`` on the current instance. + + Raises: + ValueError: If the current upload has finished. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("This part has already been uploaded.") + + with open(self._filename, "br") as f: + f.seek(self._start) + payload = f.read(self._end - self._start) + + self._checksum_object = _helpers._get_checksum_object(self._checksum_type) + if self._checksum_object is not None: + self._checksum_object.update(payload) + + part_query = _MPU_PART_QUERY_TEMPLATE.format( + part=self._part_number, upload_id=self._upload_id + ) + upload_url = self.upload_url + part_query + return _PUT, upload_url, payload, self._headers + + def _process_upload_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200 or the response is missing data. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Data corruption errors shouldn't be considered as invalid responses, + # So we handle them earlier than call to `_helpers.require_status_code`. + # If the response is 400, we check for data corruption errors. + if response.status_code == 400: + root = ElementTree.fromstring(response.text) + error_code = root.find("Code").text + error_message = root.find("Message").text + error_details = root.find("Details").text + if error_code in ["InvalidDigest", "BadDigest", "CrcMismatch"]: + raise DataCorruption( + response, + ( + "Checksum mismatch: checksum calculated by client and" + " server did not match. Error code: {error_code}," + " Error message: {error_message}," + " Error details: {error_details}" + ).format( + error_code=error_code, + error_message=error_message, + error_details=error_details, + ), + ) + + _helpers.require_status_code( + response, + (http.client.OK,), + self._get_status_code, + ) + + self._validate_checksum(response) + + etag = _helpers.header_required(response, "etag", self._get_headers) + self._etag = etag + self._finished = True + + def upload( + self, + transport, + timeout=None, + ): + """Upload the part. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _validate_checksum(self, response): + """Check the computed checksum, if any, against the response headers. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the checksum + computed locally and the checksum reported by the remote host do + not match. + """ + if self._checksum_type is None: + return + + remote_checksum = _helpers._get_uploaded_checksum_from_headers( + response, self._get_headers, self._checksum_type + ) + + if remote_checksum is None: + metadata_key = _helpers._get_metadata_key(self._checksum_type) + raise InvalidResponse( + response, + _UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE.format(metadata_key), + self._get_headers(response), + ) + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + if local_checksum != remote_checksum: + raise DataCorruption( + response, + _UPLOAD_CHECKSUM_MISMATCH_MESSAGE.format( + self._checksum_type.upper(), local_checksum, remote_checksum + ), + ) + + +def get_boundary(): + """Get a random boundary for a multipart request. + + Returns: + bytes: The boundary used to separate parts of a multipart request. + """ + random_int = random.randrange(sys.maxsize) + boundary = _BOUNDARY_FORMAT.format(random_int) + # NOTE: Neither % formatting nor .format() are available for byte strings + # in Python 3.4, so we must use unicode strings as templates. + return boundary.encode("utf-8") + + +def construct_multipart_request(data, metadata, content_type): + """Construct a multipart request body. + + Args: + data (bytes): The resource content (UTF-8 encoded as bytes) + to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[bytes, bytes]: The multipart request body and the boundary used + between each part. + """ + multipart_boundary = get_boundary() + json_bytes = json.dumps(metadata).encode("utf-8") + content_type = content_type.encode("utf-8") + # Combine the two parts into a multipart payload. + # NOTE: We'd prefer a bytes template but are restricted by Python 3.4. + boundary_sep = _MULTIPART_SEP + multipart_boundary + content = ( + boundary_sep + + _MULTIPART_BEGIN + + json_bytes + + _CRLF + + boundary_sep + + _CRLF + + b"content-type: " + + content_type + + _CRLF + + _CRLF + + data # Empty line between headers and body. + + _CRLF + + boundary_sep + + _MULTIPART_SEP + ) + + return content, multipart_boundary + + +def get_total_bytes(stream): + """Determine the total number of bytes in a stream. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object). + + Returns: + int: The number of bytes. + """ + current_position = stream.tell() + # NOTE: ``.seek()`` **should** return the same value that ``.tell()`` + # returns, but in Python 2, ``file`` objects do not. + stream.seek(0, os.SEEK_END) + end_position = stream.tell() + # Go back to the initial position. + stream.seek(current_position) + + return end_position + + +def get_next_chunk(stream, chunk_size, total_bytes): + """Get a chunk from an I/O stream. + + The ``stream`` may have fewer bytes remaining than ``chunk_size`` + so it may not always be the case that + ``end_byte == start_byte + chunk_size - 1``. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object). + chunk_size (int): The size of the chunk to be read from the ``stream``. + total_bytes (Optional[int]): The (expected) total number of bytes + in the ``stream``. + + Returns: + Tuple[int, bytes, str]: Triple of: + + * the start byte index + * the content in between the start and end bytes (inclusive) + * content range header for the chunk (slice) that has been read + + Raises: + ValueError: If ``total_bytes == 0`` but ``stream.read()`` yields + non-empty content. + ValueError: If there is no data left to consume. This corresponds + exactly to the case ``end_byte < start_byte``, which can only + occur if ``end_byte == start_byte - 1``. + """ + start_byte = stream.tell() + if total_bytes is not None and start_byte + chunk_size >= total_bytes > 0: + payload = stream.read(total_bytes - start_byte) + else: + payload = stream.read(chunk_size) + end_byte = stream.tell() - 1 + + num_bytes_read = len(payload) + if total_bytes is None: + if num_bytes_read < chunk_size: + # We now **KNOW** the total number of bytes. + total_bytes = end_byte + 1 + elif total_bytes == 0: + # NOTE: We also expect ``start_byte == 0`` here but don't check + # because ``_prepare_initiate_request()`` requires the + # stream to be at the beginning. + if num_bytes_read != 0: + raise ValueError( + "Stream specified as empty, but produced non-empty content." + ) + else: + if num_bytes_read == 0: + raise ValueError( + "Stream is already exhausted. There is no content remaining." + ) + + content_range = get_content_range(start_byte, end_byte, total_bytes) + return start_byte, payload, content_range + + +def get_content_range(start_byte, end_byte, total_bytes): + """Convert start, end and total into content range header. + + If ``total_bytes`` is not known, uses "bytes {start}-{end}/*". + If we are dealing with an empty range (i.e. ``end_byte < start_byte``) + then "bytes */{total}" is used. + + This function **ASSUMES** that if the size is not known, the caller will + not also pass an empty range. + + Args: + start_byte (int): The start (inclusive) of the byte range. + end_byte (int): The end (inclusive) of the byte range. + total_bytes (Optional[int]): The number of bytes in the byte + range (if known). + + Returns: + str: The content range header. + """ + if total_bytes is None: + return _RANGE_UNKNOWN_TEMPLATE.format(start_byte, end_byte) + elif end_byte < start_byte: + return _EMPTY_RANGE_TEMPLATE.format(total_bytes) + else: + return _CONTENT_RANGE_TEMPLATE.format(start_byte, end_byte, total_bytes) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/common.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/common.py new file mode 100644 index 0000000000000000000000000000000000000000..2917ea53dfceff1d6e2ecb327b180e5488de20e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/common.py @@ -0,0 +1,21 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common utilities for Google Media Downloads and Resumable Uploads. + +Includes custom exception types, useful constants and shared helpers. +""" + +UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 +"""int: Chunks in a resumable upload must come in multiples of 256 KB.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..7705b065b00d1990fff0bfa83bc916b3f239a6f2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-resumable_media package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..743887eb9c172d7e46bc165f2747ed8123566470 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__init__.py @@ -0,0 +1,685 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""``requests`` utilities for Google Media Downloads and Resumable Uploads. + +This sub-package assumes callers will use the `requests`_ library +as transport and `google-auth`_ for sending authenticated HTTP traffic +with ``requests``. + +.. _requests: http://docs.python-requests.org/ +.. _google-auth: https://google-auth.readthedocs.io/ + +==================== +Authorized Transport +==================== + +To use ``google-auth`` and ``requests`` to create an authorized transport +that has read-only access to Google Cloud Storage (GCS): + +.. testsetup:: get-credentials + + import google.auth + import google.auth.credentials as creds_mod + import mock + + def mock_default(scopes=None): + credentials = mock.Mock(spec=creds_mod.Credentials) + return credentials, 'mock-project' + + # Patch the ``default`` function on the module. + original_default = google.auth.default + google.auth.default = mock_default + +.. doctest:: get-credentials + + >>> import google.auth + >>> import google.auth.transport.requests as tr_requests + >>> + >>> ro_scope = 'https://www.googleapis.com/auth/devstorage.read_only' + >>> credentials, _ = google.auth.default(scopes=(ro_scope,)) + >>> transport = tr_requests.AuthorizedSession(credentials) + >>> transport + + +.. testcleanup:: get-credentials + + # Put back the correct ``default`` function on the module. + google.auth.default = original_default + +================ +Simple Downloads +================ + +To download an object from Google Cloud Storage, construct the media URL +for the GCS object and download it with an authorized transport that has +access to the resource: + +.. testsetup:: basic-download + + import mock + import requests + import http.client + + bucket = 'bucket-foo' + blob_name = 'file.txt' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response.headers['Content-Length'] = '1364156' + fake_content = mock.MagicMock(spec=['__len__']) + fake_content.__len__.return_value = 1364156 + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: basic-download + + >>> from google.cloud.storage._media.requests import Download + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/download/storage/v1/b/' + ... '{bucket}/o/{blob_name}?alt=media') + >>> media_url = url_template.format( + ... bucket=bucket, blob_name=blob_name) + >>> + >>> download = Download(media_url) + >>> response = download.consume(transport) + >>> download.finished + True + >>> response + + >>> response.headers['Content-Length'] + '1364156' + >>> len(response.content) + 1364156 + +To download only a portion of the bytes in the object, +specify ``start`` and ``end`` byte positions (both optional): + +.. testsetup:: basic-download-with-slice + + import mock + import requests + import http.client + + from google.cloud.storage._media.requests import Download + + media_url = 'http://test.invalid' + start = 4096 + end = 8191 + slice_size = end - start + 1 + + fake_response = requests.Response() + fake_response.status_code = int(http.client.PARTIAL_CONTENT) + fake_response.headers['Content-Length'] = '{:d}'.format(slice_size) + content_range = 'bytes {:d}-{:d}/1364156'.format(start, end) + fake_response.headers['Content-Range'] = content_range + fake_content = mock.MagicMock(spec=['__len__']) + fake_content.__len__.return_value = slice_size + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: basic-download-with-slice + + >>> download = Download(media_url, start=4096, end=8191) + >>> response = download.consume(transport) + >>> download.finished + True + >>> response + + >>> response.headers['Content-Length'] + '4096' + >>> response.headers['Content-Range'] + 'bytes 4096-8191/1364156' + >>> len(response.content) + 4096 + +================= +Chunked Downloads +================= + +For very large objects or objects of unknown size, it may make more sense +to download the object in chunks rather than all at once. This can be done +to avoid dropped connections with a poor internet connection or can allow +multiple chunks to be downloaded in parallel to speed up the total +download. + +A :class:`.ChunkedDownload` uses the same media URL and authorized +transport that a basic :class:`.Download` would use, but also +requires a chunk size and a write-able byte ``stream``. The chunk size is used +to determine how much of the resouce to consume with each request and the +stream is to allow the resource to be written out (e.g. to disk) without +having to fit in memory all at once. + +.. testsetup:: chunked-download + + import io + + import mock + import requests + import http.client + + media_url = 'http://test.invalid' + + fifty_mb = 50 * 1024 * 1024 + one_gb = 1024 * 1024 * 1024 + fake_response = requests.Response() + fake_response.status_code = int(http.client.PARTIAL_CONTENT) + fake_response.headers['Content-Length'] = '{:d}'.format(fifty_mb) + content_range = 'bytes 0-{:d}/{:d}'.format(fifty_mb - 1, one_gb) + fake_response.headers['Content-Range'] = content_range + fake_content_begin = b'The beginning of the chunk...' + fake_content = fake_content_begin + b'1' * (fifty_mb - 29) + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: chunked-download + + >>> from google.cloud.storage._media.requests import ChunkedDownload + >>> + >>> chunk_size = 50 * 1024 * 1024 # 50MB + >>> stream = io.BytesIO() + >>> download = ChunkedDownload( + ... media_url, chunk_size, stream) + >>> # Check the state of the download before starting. + >>> download.bytes_downloaded + 0 + >>> download.total_bytes is None + True + >>> response = download.consume_next_chunk(transport) + >>> # Check the state of the download after consuming one chunk. + >>> download.finished + False + >>> download.bytes_downloaded # chunk_size + 52428800 + >>> download.total_bytes # 1GB + 1073741824 + >>> response + + >>> response.headers['Content-Length'] + '52428800' + >>> response.headers['Content-Range'] + 'bytes 0-52428799/1073741824' + >>> len(response.content) == chunk_size + True + >>> stream.seek(0) + 0 + >>> stream.read(29) + b'The beginning of the chunk...' + +The download will change it's ``finished`` status to :data:`True` +once the final chunk is consumed. In some cases, the final chunk may +not be the same size as the other chunks: + +.. testsetup:: chunked-download-end + + import mock + import requests + import http.client + + from google.cloud.storage._media.requests import ChunkedDownload + + media_url = 'http://test.invalid' + + fifty_mb = 50 * 1024 * 1024 + one_gb = 1024 * 1024 * 1024 + stream = mock.Mock(spec=['write']) + download = ChunkedDownload(media_url, fifty_mb, stream) + download._bytes_downloaded = 20 * fifty_mb + download._total_bytes = one_gb + + fake_response = requests.Response() + fake_response.status_code = int(http.client.PARTIAL_CONTENT) + slice_size = one_gb - 20 * fifty_mb + fake_response.headers['Content-Length'] = '{:d}'.format(slice_size) + content_range = 'bytes {:d}-{:d}/{:d}'.format( + 20 * fifty_mb, one_gb - 1, one_gb) + fake_response.headers['Content-Range'] = content_range + fake_content = mock.MagicMock(spec=['__len__']) + fake_content.__len__.return_value = slice_size + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: chunked-download-end + + >>> # The state of the download in progress. + >>> download.finished + False + >>> download.bytes_downloaded # 20 chunks at 50MB + 1048576000 + >>> download.total_bytes # 1GB + 1073741824 + >>> response = download.consume_next_chunk(transport) + >>> # The state of the download after consuming the final chunk. + >>> download.finished + True + >>> download.bytes_downloaded == download.total_bytes + True + >>> response + + >>> response.headers['Content-Length'] + '25165824' + >>> response.headers['Content-Range'] + 'bytes 1048576000-1073741823/1073741824' + >>> len(response.content) < download.chunk_size + True + +In addition, a :class:`.ChunkedDownload` can also take optional +``start`` and ``end`` byte positions. + +Usually, no checksum is returned with a chunked download. Even if one is returned, +it is not validated. If you need to validate the checksum, you can do so +by buffering the chunks and validating the checksum against the completed download. + +============== +Simple Uploads +============== + +Among the three supported upload classes, the simplest is +:class:`.SimpleUpload`. A simple upload should be used when the resource +being uploaded is small and when there is no metadata (other than the name) +associated with the resource. + +.. testsetup:: simple-upload + + import json + + import mock + import requests + import http.client + + bucket = 'some-bucket' + blob_name = 'file.txt' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + payload = { + 'bucket': bucket, + 'contentType': 'text/plain', + 'md5Hash': 'M0XLEsX9/sMdiI+4pB4CAQ==', + 'name': blob_name, + 'size': '27', + } + fake_response._content = json.dumps(payload).encode('utf-8') + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + +.. doctest:: simple-upload + :options: +NORMALIZE_WHITESPACE + + >>> from google.cloud.storage._media.requests import SimpleUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=media&' + ... 'name={blob_name}') + >>> upload_url = url_template.format( + ... bucket=bucket, blob_name=blob_name) + >>> + >>> upload = SimpleUpload(upload_url) + >>> data = b'Some not too large content.' + >>> content_type = 'text/plain' + >>> response = upload.transmit(transport, data, content_type) + >>> upload.finished + True + >>> response + + >>> json_response = response.json() + >>> json_response['bucket'] == bucket + True + >>> json_response['name'] == blob_name + True + >>> json_response['contentType'] == content_type + True + >>> json_response['md5Hash'] + 'M0XLEsX9/sMdiI+4pB4CAQ==' + >>> int(json_response['size']) == len(data) + True + +In the rare case that an upload fails, an :exc:`.InvalidResponse` +will be raised: + +.. testsetup:: simple-upload-fail + + import time + + import mock + import requests + import http.client + + from google.cloud.storage import _media + from google.cloud.storage._media import _helpers + from google.cloud.storage._media.requests import SimpleUpload as constructor + + upload_url = 'http://test.invalid' + data = b'Some not too large content.' + content_type = 'text/plain' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.SERVICE_UNAVAILABLE) + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + time_sleep = time.sleep + def dont_sleep(seconds): + raise RuntimeError('No sleep', seconds) + + def SimpleUpload(*args, **kwargs): + upload = constructor(*args, **kwargs) + # Mock the cumulative sleep to avoid retries (and `time.sleep()`). + upload._retry_strategy = _media.RetryStrategy( + max_cumulative_retry=-1.0) + return upload + + time.sleep = dont_sleep + +.. doctest:: simple-upload-fail + :options: +NORMALIZE_WHITESPACE + + >>> upload = SimpleUpload(upload_url) + >>> error = None + >>> try: + ... upload.transmit(transport, data, content_type) + ... except _media.InvalidResponse as caught_exc: + ... error = caught_exc + ... + >>> error + InvalidResponse('Request failed with status code', 503, + 'Expected one of', ) + >>> error.response + + >>> + >>> upload.finished + True + +.. testcleanup:: simple-upload-fail + + # Put back the correct ``sleep`` function on the ``time`` module. + time.sleep = time_sleep + +Even in the case of failure, we see that the upload is +:attr:`~.SimpleUpload.finished`, i.e. it cannot be re-used. + +================= +Multipart Uploads +================= + +After the simple upload, the :class:`.MultipartUpload` can be used to +achieve essentially the same task. However, a multipart upload allows some +metadata about the resource to be sent along as well. (This is the "multi": +we send a first part with the metadata and a second part with the actual +bytes in the resource.) + +Usage is similar to the simple upload, but :meth:`~.MultipartUpload.transmit` +accepts an extra required argument: ``metadata``. + +.. testsetup:: multipart-upload + + import json + + import mock + import requests + import http.client + + bucket = 'some-bucket' + blob_name = 'file.txt' + data = b'Some not too large content.' + content_type = 'text/plain' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + payload = { + 'bucket': bucket, + 'name': blob_name, + 'metadata': {'color': 'grurple'}, + } + fake_response._content = json.dumps(payload).encode('utf-8') + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + +.. doctest:: multipart-upload + + >>> from google.cloud.storage._media.requests import MultipartUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=multipart') + >>> upload_url = url_template.format(bucket=bucket) + >>> + >>> upload = MultipartUpload(upload_url) + >>> metadata = { + ... 'name': blob_name, + ... 'metadata': { + ... 'color': 'grurple', + ... }, + ... } + >>> response = upload.transmit(transport, data, metadata, content_type) + >>> upload.finished + True + >>> response + + >>> json_response = response.json() + >>> json_response['bucket'] == bucket + True + >>> json_response['name'] == blob_name + True + >>> json_response['metadata'] == metadata['metadata'] + True + +As with the simple upload, in the case of failure an :exc:`.InvalidResponse` +is raised, enclosing the :attr:`~.InvalidResponse.response` that caused +the failure and the ``upload`` object cannot be re-used after a failure. + +================= +Resumable Uploads +================= + +A :class:`.ResumableUpload` deviates from the other two upload classes: +it transmits a resource over the course of multiple requests. This +is intended to be used in cases where: + +* the size of the resource is not known (i.e. it is generated on the fly) +* requests must be short-lived +* the client has request **size** limitations +* the resource is too large to fit into memory + +In general, a resource should be sent in a **single** request to avoid +latency and reduce QPS. See `GCS best practices`_ for more things to +consider when using a resumable upload. + +.. _GCS best practices: https://cloud.google.com/storage/docs/\ + best-practices#uploading + +After creating a :class:`.ResumableUpload` instance, a +**resumable upload session** must be initiated to let the server know that +a series of chunked upload requests will be coming and to obtain an +``upload_id`` for the session. In contrast to the other two upload classes, +:meth:`~.ResumableUpload.initiate` takes a byte ``stream`` as input rather +than raw bytes as ``data``. This can be a file object, a :class:`~io.BytesIO` +object or any other stream implementing the same interface. + +.. testsetup:: resumable-initiate + + import io + + import mock + import requests + import http.client + + bucket = 'some-bucket' + blob_name = 'file.txt' + data = b'Some resumable bytes.' + content_type = 'text/plain' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + upload_id = 'ABCdef189XY_super_serious' + resumable_url_template = ( + 'https://www.googleapis.com/upload/storage/v1/b/{bucket}' + '/o?uploadType=resumable&upload_id={upload_id}') + resumable_url = resumable_url_template.format( + bucket=bucket, upload_id=upload_id) + fake_response.headers['location'] = resumable_url + fake_response.headers['x-guploader-uploadid'] = upload_id + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + +.. doctest:: resumable-initiate + + >>> from google.cloud.storage._media.requests import ResumableUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=resumable') + >>> upload_url = url_template.format(bucket=bucket) + >>> + >>> chunk_size = 1024 * 1024 # 1MB + >>> upload = ResumableUpload(upload_url, chunk_size) + >>> stream = io.BytesIO(data) + >>> # The upload doesn't know how "big" it is until seeing a stream. + >>> upload.total_bytes is None + True + >>> metadata = {'name': blob_name} + >>> response = upload.initiate(transport, stream, metadata, content_type) + >>> response + + >>> upload.resumable_url == response.headers['Location'] + True + >>> upload.total_bytes == len(data) + True + >>> upload_id = response.headers['X-GUploader-UploadID'] + >>> upload_id + 'ABCdef189XY_super_serious' + >>> upload.resumable_url == upload_url + '&upload_id=' + upload_id + True + +Once a :class:`.ResumableUpload` has been initiated, the resource is +transmitted in chunks until completion: + +.. testsetup:: resumable-transmit + + import io + import json + + import mock + import requests + import http.client + + from google.cloud.storage. import _media + import google.cloud.storage._media.requests.upload as upload_mod + + data = b'01234567891' + stream = io.BytesIO(data) + # Create an "already initiated" upload. + upload_url = 'http://test.invalid' + chunk_size = 256 * 1024 # 256KB + upload = upload_mod.ResumableUpload(upload_url, chunk_size) + upload._resumable_url = 'http://test.invalid?upload_id=mocked' + upload._stream = stream + upload._content_type = 'text/plain' + upload._total_bytes = len(data) + + # After-the-fact update the chunk size so that len(data) + # is split into three. + upload._chunk_size = 4 + # Make three fake responses. + fake_response0 = requests.Response() + fake_response0.status_code = http.client.PERMANENT_REDIRECT + fake_response0.headers['range'] = 'bytes=0-3' + + fake_response1 = requests.Response() + fake_response1.status_code = http.client.PERMANENT_REDIRECT + fake_response1.headers['range'] = 'bytes=0-7' + + fake_response2 = requests.Response() + fake_response2.status_code = int(http.client.OK) + bucket = 'some-bucket' + blob_name = 'file.txt' + payload = { + 'bucket': bucket, + 'name': blob_name, + 'size': '{:d}'.format(len(data)), + } + fake_response2._content = json.dumps(payload).encode('utf-8') + + # Use the fake responses to mock a transport. + responses = [fake_response0, fake_response1, fake_response2] + put_method = mock.Mock(side_effect=responses, spec=[]) + transport = mock.Mock(request=put_method, spec=['request']) + +.. doctest:: resumable-transmit + + >>> response0 = upload.transmit_next_chunk(transport) + >>> response0 + + >>> upload.finished + False + >>> upload.bytes_uploaded == upload.chunk_size + True + >>> + >>> response1 = upload.transmit_next_chunk(transport) + >>> response1 + + >>> upload.finished + False + >>> upload.bytes_uploaded == 2 * upload.chunk_size + True + >>> + >>> response2 = upload.transmit_next_chunk(transport) + >>> response2 + + >>> upload.finished + True + >>> upload.bytes_uploaded == upload.total_bytes + True + >>> json_response = response2.json() + >>> json_response['bucket'] == bucket + True + >>> json_response['name'] == blob_name + True +""" +from google.cloud.storage._media.requests.download import ChunkedDownload +from google.cloud.storage._media.requests.download import Download +from google.cloud.storage._media.requests.upload import MultipartUpload +from google.cloud.storage._media.requests.download import RawChunkedDownload +from google.cloud.storage._media.requests.download import RawDownload +from google.cloud.storage._media.requests.upload import ResumableUpload +from google.cloud.storage._media.requests.upload import SimpleUpload +from google.cloud.storage._media.requests.upload import XMLMPUContainer +from google.cloud.storage._media.requests.upload import XMLMPUPart + +__all__ = [ + "ChunkedDownload", + "Download", + "MultipartUpload", + "RawChunkedDownload", + "RawDownload", + "ResumableUpload", + "SimpleUpload", + "XMLMPUContainer", + "XMLMPUPart", +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30c0926344fadd8b7bcedf1c2ad56b12971766b1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/_request_helpers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/_request_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a707c5ba09315b8e2bd6969d6aae9b90fe57115 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/_request_helpers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/download.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/download.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9ca5dc9e94fc7a1ee1db0d75657425195bed01 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/download.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/upload.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/upload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d2b3efaffba33a90acf7cbd2cda2e2a56b4aa11 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/__pycache__/upload.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/_request_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/_request_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..604ffc31375e2b47a5411a0cc9748cbf09bfea5c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/_request_helpers.py @@ -0,0 +1,107 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared utilities used by both downloads and uploads. + +This utilities are explicitly catered to ``requests``-like transports. +""" + +_SINGLE_GET_CHUNK_SIZE = 8192 +# The number of seconds to wait to establish a connection +# (connect() call on socket). Avoid setting this to a multiple of 3 to not +# Align with TCP Retransmission timing. (typically 2.5-3s) +_DEFAULT_CONNECT_TIMEOUT = 61 +# The number of seconds to wait between bytes sent from the server. +_DEFAULT_READ_TIMEOUT = 60 + + +class RequestsMixin(object): + """Mix-in class implementing ``requests``-specific behavior. + + These are methods that are more general purpose, with implementations + specific to the types defined in ``requests``. + """ + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + int: The status code. + """ + return response.status_code + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + ~requests.structures.CaseInsensitiveDict: The header mapping (keys + are case-insensitive). + """ + return response.headers + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + bytes: The body of the ``response``. + """ + return response.content + + +class RawRequestsMixin(RequestsMixin): + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + bytes: The body of the ``response``. + """ + if response._content is False: + response._content = b"".join( + response.raw.stream(_SINGLE_GET_CHUNK_SIZE, decode_content=False) + ) + response._content_consumed = True + return response._content + + +def wait_and_retry(func, retry_strategy): + """Attempts to retry a call to ``func`` until success. + + Args: + func (Callable): A callable that takes no arguments and produces + an HTTP response which will be checked as retry-able. + retry_strategy (Optional[google.api_core.retry.Retry]): The + strategy to use if the request fails and must be retried. + + Returns: + object: The return value of ``func``. + """ + if retry_strategy: + func = retry_strategy(func) + return func() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/download.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/download.py new file mode 100644 index 0000000000000000000000000000000000000000..c5686fcb77b272453517f5067c0a222e10274210 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/download.py @@ -0,0 +1,778 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Support for downloading media from Google APIs.""" + +import urllib3.response # type: ignore +import http + +from google.cloud.storage._media import _download +from google.cloud.storage._media import _helpers +from google.cloud.storage._media.requests import _request_helpers +from google.cloud.storage.exceptions import DataCorruption + +_CHECKSUM_MISMATCH = """\ +Checksum mismatch while downloading: + + {} + +The X-Goog-Hash header indicated an {checksum_type} checksum of: + + {} + +but the actual {checksum_type} checksum of the downloaded contents was: + + {} +""" + +_STREAM_SEEK_ERROR = """\ +Incomplete download for: +{} +Error writing to stream while handling a gzip-compressed file download. +Please restart the download. +""" + +_RESPONSE_HEADERS_INFO = """\ +The X-Goog-Stored-Content-Length is {}. The X-Goog-Stored-Content-Encoding is {}. +The download request read {} bytes of data. +If the download was incomplete, please check the network connection and restart the download. +""" + + +class Download(_request_helpers.RequestsMixin, _download.Download): + """Helper to manage downloading a resource from a Google API. + + "Slices" of the resource can be retrieved by specifying a range + with ``start`` and / or ``end``. However, in typical usage, neither + ``start`` nor ``end`` is expected to be provided. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. If not + provided, but ``end`` is provided, will download from the + beginning to ``end`` of the media. + end (int): The last byte in a range to be downloaded. If not + provided, but ``start`` is provided, will download from the + ``start`` to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The response headers must contain + a checksum of the requested type. If the headers lack an + appropriate checksum (for instance in the case of transcoded or + ranged downloads where the remote service does not know the + correct checksum) an INFO-level log will be emitted. Supported + values are "md5", "crc32c", "auto" and None. The default is "auto", + which will try to detect if the C extension for crc32c is installed + and fall back to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + """ + + def _write_to_stream(self, response): + """Write response body to a write-able stream. + + .. note: + + This method assumes that the ``_stream`` attribute is set on the + current download. + + Args: + response (~requests.Response): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + """ + + # Retrieve the expected checksum only once for the download request, + # then compute and validate the checksum when the full download completes. + # Retried requests are range requests, and there's no way to detect + # data corruption for that byte range alone. + if self._expected_checksum is None and self._checksum_object is None: + # `_get_expected_checksum()` may return None even if a checksum was + # requested, in which case it will emit an info log _MISSING_CHECKSUM. + # If an invalid checksum type is specified, this will raise ValueError. + expected_checksum, checksum_object = _helpers._get_expected_checksum( + response, self._get_headers, self.media_url, checksum_type=self.checksum + ) + self._expected_checksum = expected_checksum + self._checksum_object = checksum_object + else: + expected_checksum = self._expected_checksum + checksum_object = self._checksum_object + + with response: + # NOTE: In order to handle compressed streams gracefully, we try + # to insert our checksum object into the decompression stream. If + # the stream is indeed compressed, this will delegate the checksum + # object to the decoder and return a _DoNothingHash here. + local_checksum_object = _add_decoder(response.raw, checksum_object) + + # This is useful for smaller files, or when the user wants to + # download the entire file in one go. + if self.single_shot_download: + content = response.raw.read(decode_content=True) + self._stream.write(content) + self._bytes_downloaded += len(content) + local_checksum_object.update(content) + response._content_consumed = True + else: + body_iter = response.iter_content( + chunk_size=_request_helpers._SINGLE_GET_CHUNK_SIZE, + decode_unicode=False, + ) + for chunk in body_iter: + self._stream.write(chunk) + self._bytes_downloaded += len(chunk) + local_checksum_object.update(chunk) + + # Don't validate the checksum for partial responses. + if ( + expected_checksum is not None + and response.status_code != http.client.PARTIAL_CONTENT + ): + actual_checksum = _helpers.prepare_checksum_digest(checksum_object.digest()) + if actual_checksum != expected_checksum: + headers = self._get_headers(response) + x_goog_encoding = headers.get("x-goog-stored-content-encoding") + x_goog_length = headers.get("x-goog-stored-content-length") + content_length_msg = _RESPONSE_HEADERS_INFO.format( + x_goog_length, x_goog_encoding, self._bytes_downloaded + ) + if ( + x_goog_length + and self._bytes_downloaded < int(x_goog_length) + and x_goog_encoding != "gzip" + ): + # The library will attempt to trigger a retry by raising a ConnectionError, if + # (a) bytes_downloaded is less than response header x-goog-stored-content-length, and + # (b) the object is not gzip-compressed when stored in Cloud Storage. + raise ConnectionError(content_length_msg) + else: + msg = _CHECKSUM_MISMATCH.format( + self.media_url, + expected_checksum, + actual_checksum, + checksum_type=self.checksum.upper(), + ) + msg += content_length_msg + raise DataCorruption(response, msg) + + def consume( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the resource to be downloaded. + + If a ``stream`` is attached to this download, then the downloaded + resource will be written to the stream. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + ValueError: If the current :class:`Download` has already + finished. + """ + method, _, payload, headers = self._prepare_request() + # NOTE: We assume "payload is None" but pass it along anyway. + request_kwargs = { + "data": payload, + "headers": headers, + "timeout": timeout, + } + if self._stream is not None: + request_kwargs["stream"] = True + + # Assign object generation if generation is specified in the media url. + if self._object_generation is None: + self._object_generation = _helpers._get_generation_from_url(self.media_url) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + url = self.media_url + + # To restart an interrupted download, read from the offset of last byte + # received using a range request, and set object generation query param. + if self._bytes_downloaded > 0: + _download.add_bytes_range( + (self.start or 0) + self._bytes_downloaded, self.end, self._headers + ) + request_kwargs["headers"] = self._headers + + # Set object generation query param to ensure the same object content is requested. + if ( + self._object_generation is not None + and _helpers._get_generation_from_url(self.media_url) is None + ): + query_param = {"generation": self._object_generation} + url = _helpers.add_query_parameters(self.media_url, query_param) + + result = transport.request(method, url, **request_kwargs) + + # If a generation hasn't been specified, and this is the first response we get, let's record the + # generation. In future requests we'll specify the generation query param to avoid data races. + if self._object_generation is None: + self._object_generation = _helpers._parse_generation_header( + result, self._get_headers + ) + + self._process_response(result) + + # With decompressive transcoding, GCS serves back the whole file regardless of the range request, + # thus we reset the stream position to the start of the stream. + # See: https://cloud.google.com/storage/docs/transcoding#range + if self._stream is not None: + if _helpers._is_decompressive_transcoding(result, self._get_headers): + try: + self._stream.seek(0) + except Exception as exc: + msg = _STREAM_SEEK_ERROR.format(url) + raise Exception(msg) from exc + self._bytes_downloaded = 0 + + self._write_to_stream(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +class RawDownload(_request_helpers.RawRequestsMixin, _download.Download): + """Helper to manage downloading a raw resource from a Google API. + + "Slices" of the resource can be retrieved by specifying a range + with ``start`` and / or ``end``. However, in typical usage, neither + ``start`` nor ``end`` is expected to be provided. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. If not + provided, but ``end`` is provided, will download from the + beginning to ``end`` of the media. + end (int): The last byte in a range to be downloaded. If not + provided, but ``start`` is provided, will download from the + ``start`` to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The response headers must contain + a checksum of the requested type. If the headers lack an + appropriate checksum (for instance in the case of transcoded or + ranged downloads where the remote service does not know the + correct checksum) an INFO-level log will be emitted. Supported + values are "md5", "crc32c", "auto" and None. The default is "auto", + which will try to detect if the C extension for crc32c is installed + and fall back to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + """ + + def _write_to_stream(self, response): + """Write response body to a write-able stream. + + .. note: + + This method assumes that the ``_stream`` attribute is set on the + current download. + + Args: + response (~requests.Response): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + """ + # Retrieve the expected checksum only once for the download request, + # then compute and validate the checksum when the full download completes. + # Retried requests are range requests, and there's no way to detect + # data corruption for that byte range alone. + if self._expected_checksum is None and self._checksum_object is None: + # `_get_expected_checksum()` may return None even if a checksum was + # requested, in which case it will emit an info log _MISSING_CHECKSUM. + # If an invalid checksum type is specified, this will raise ValueError. + expected_checksum, checksum_object = _helpers._get_expected_checksum( + response, self._get_headers, self.media_url, checksum_type=self.checksum + ) + self._expected_checksum = expected_checksum + self._checksum_object = checksum_object + else: + expected_checksum = self._expected_checksum + checksum_object = self._checksum_object + + with response: + # This is useful for smaller files, or when the user wants to + # download the entire file in one go. + if self.single_shot_download: + content = response.raw.read() + self._stream.write(content) + self._bytes_downloaded += len(content) + checksum_object.update(content) + else: + body_iter = response.raw.stream( + _request_helpers._SINGLE_GET_CHUNK_SIZE, decode_content=False + ) + for chunk in body_iter: + self._stream.write(chunk) + self._bytes_downloaded += len(chunk) + checksum_object.update(chunk) + response._content_consumed = True + + # Don't validate the checksum for partial responses. + if ( + expected_checksum is not None + and response.status_code != http.client.PARTIAL_CONTENT + ): + actual_checksum = _helpers.prepare_checksum_digest(checksum_object.digest()) + + if actual_checksum != expected_checksum: + headers = self._get_headers(response) + x_goog_encoding = headers.get("x-goog-stored-content-encoding") + x_goog_length = headers.get("x-goog-stored-content-length") + content_length_msg = _RESPONSE_HEADERS_INFO.format( + x_goog_length, x_goog_encoding, self._bytes_downloaded + ) + if ( + x_goog_length + and self._bytes_downloaded < int(x_goog_length) + and x_goog_encoding != "gzip" + ): + # The library will attempt to trigger a retry by raising a ConnectionError, if + # (a) bytes_downloaded is less than response header x-goog-stored-content-length, and + # (b) the object is not gzip-compressed when stored in Cloud Storage. + raise ConnectionError(content_length_msg) + else: + msg = _CHECKSUM_MISMATCH.format( + self.media_url, + expected_checksum, + actual_checksum, + checksum_type=self.checksum.upper(), + ) + msg += content_length_msg + raise DataCorruption(response, msg) + + def consume( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the resource to be downloaded. + + If a ``stream`` is attached to this download, then the downloaded + resource will be written to the stream. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + ValueError: If the current :class:`Download` has already + finished. + """ + method, _, payload, headers = self._prepare_request() + # NOTE: We assume "payload is None" but pass it along anyway. + request_kwargs = { + "data": payload, + "headers": headers, + "timeout": timeout, + "stream": True, + } + + # Assign object generation if generation is specified in the media url. + if self._object_generation is None: + self._object_generation = _helpers._get_generation_from_url(self.media_url) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + url = self.media_url + + # To restart an interrupted download, read from the offset of last byte + # received using a range request, and set object generation query param. + if self._bytes_downloaded > 0: + _download.add_bytes_range( + (self.start or 0) + self._bytes_downloaded, self.end, self._headers + ) + request_kwargs["headers"] = self._headers + + # Set object generation query param to ensure the same object content is requested. + if ( + self._object_generation is not None + and _helpers._get_generation_from_url(self.media_url) is None + ): + query_param = {"generation": self._object_generation} + url = _helpers.add_query_parameters(self.media_url, query_param) + + result = transport.request(method, url, **request_kwargs) + + # If a generation hasn't been specified, and this is the first response we get, let's record the + # generation. In future requests we'll specify the generation query param to avoid data races. + if self._object_generation is None: + self._object_generation = _helpers._parse_generation_header( + result, self._get_headers + ) + + self._process_response(result) + + # With decompressive transcoding, GCS serves back the whole file regardless of the range request, + # thus we reset the stream position to the start of the stream. + # See: https://cloud.google.com/storage/docs/transcoding#range + if self._stream is not None: + if _helpers._is_decompressive_transcoding(result, self._get_headers): + try: + self._stream.seek(0) + except Exception as exc: + msg = _STREAM_SEEK_ERROR.format(url) + raise Exception(msg) from exc + self._bytes_downloaded = 0 + + self._write_to_stream(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +class ChunkedDownload(_request_helpers.RequestsMixin, _download.ChunkedDownload): + """Download a resource in chunks from a Google API. + + Args: + media_url (str): The URL containing the media to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each + request. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + will be used to concatenate chunks of the resource as they are + downloaded. + start (int): The first byte in a range to be downloaded. If not + provided, defaults to ``0``. + end (int): The last byte in a range to be downloaded. If not + provided, will download to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with each request, e.g. headers for data encryption + key headers. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each request. + + Raises: + ValueError: If ``start`` is negative. + """ + + def consume_next_chunk( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the next chunk of the resource to be downloaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ValueError: If the current download has finished. + """ + method, url, payload, headers = self._prepare_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + # NOTE: We assume "payload is None" but pass it along anyway. + result = transport.request( + method, + url, + data=payload, + headers=headers, + timeout=timeout, + ) + self._process_response(result) + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +class RawChunkedDownload(_request_helpers.RawRequestsMixin, _download.ChunkedDownload): + """Download a raw resource in chunks from a Google API. + + Args: + media_url (str): The URL containing the media to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each + request. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + will be used to concatenate chunks of the resource as they are + downloaded. + start (int): The first byte in a range to be downloaded. If not + provided, defaults to ``0``. + end (int): The last byte in a range to be downloaded. If not + provided, will download to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with each request, e.g. headers for data encryption + key headers. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each request. + + Raises: + ValueError: If ``start`` is negative. + """ + + def consume_next_chunk( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the next chunk of the resource to be downloaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ValueError: If the current download has finished. + """ + method, url, payload, headers = self._prepare_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + # NOTE: We assume "payload is None" but pass it along anyway. + result = transport.request( + method, + url, + data=payload, + headers=headers, + stream=True, + timeout=timeout, + ) + self._process_response(result) + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +def _add_decoder(response_raw, checksum): + """Patch the ``_decoder`` on a ``urllib3`` response. + + This is so that we can intercept the compressed bytes before they are + decoded. + + Only patches if the content encoding is ``gzip`` or ``br``. + + Args: + response_raw (urllib3.response.HTTPResponse): The raw response for + an HTTP request. + checksum (object): + A checksum which will be updated with compressed bytes. + + Returns: + object: Either the original ``checksum`` if ``_decoder`` is not + patched, or a ``_DoNothingHash`` if the decoder is patched, since the + caller will no longer need to hash to decoded bytes. + """ + encoding = response_raw.headers.get("content-encoding", "").lower() + if encoding == "gzip": + response_raw._decoder = _GzipDecoder(checksum) + return _helpers._DoNothingHash() + # Only activate if brotli is installed + elif encoding == "br" and _BrotliDecoder: # type: ignore + response_raw._decoder = _BrotliDecoder(checksum) + return _helpers._DoNothingHash() + else: + return checksum + + +class _GzipDecoder(urllib3.response.GzipDecoder): + """Custom subclass of ``urllib3`` decoder for ``gzip``-ed bytes. + + Allows a checksum function to see the compressed bytes before they are + decoded. This way the checksum of the compressed value can be computed. + + Args: + checksum (object): + A checksum which will be updated with compressed bytes. + """ + + def __init__(self, checksum): + super().__init__() + self._checksum = checksum + + def decompress(self, data, max_length=-1): + """Decompress the bytes. + + Args: + data (bytes): The compressed bytes to be decompressed. + + Returns: + bytes: The decompressed bytes from ``data``. + """ + self._checksum.update(data) + try: + return super().decompress(data, max_length=max_length) + except TypeError: + # Fallback for urllib3 < 2.6.0 which lacks `max_length` support. + return super().decompress(data) + + +# urllib3.response.BrotliDecoder might not exist depending on whether brotli is +# installed. +if hasattr(urllib3.response, "BrotliDecoder"): + + class _BrotliDecoder: + """Handler for ``brotli`` encoded bytes. + + Allows a checksum function to see the compressed bytes before they are + decoded. This way the checksum of the compressed value can be computed. + + Because BrotliDecoder's decompress method is dynamically created in + urllib3, a subclass is not practical. Instead, this class creates a + captive urllib3.requests.BrotliDecoder instance and acts as a proxy. + + Args: + checksum (object): + A checksum which will be updated with compressed bytes. + """ + + def __init__(self, checksum): + self._decoder = urllib3.response.BrotliDecoder() + self._checksum = checksum + + def decompress(self, data, max_length=-1): + """Decompress the bytes. + + Args: + data (bytes): The compressed bytes to be decompressed. + + Returns: + bytes: The decompressed bytes from ``data``. + """ + self._checksum.update(data) + try: + return self._decoder.decompress(data, max_length=max_length) + except TypeError: + # Fallback for urllib3 < 2.6.0 which lacks `max_length` support. + return self._decoder.decompress(data) + + def flush(self): + return self._decoder.flush() + + @property + def has_unconsumed_tail(self) -> bool: + return self._decoder.has_unconsumed_tail + +else: # pragma: NO COVER + _BrotliDecoder = None # type: ignore # pragma: NO COVER diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/upload.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9653fb3e10b4d1f4b4fcb968d76d43928d8be7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_media/requests/upload.py @@ -0,0 +1,780 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Support for resumable uploads. + +Also supported here are simple (media) uploads and multipart +uploads that contain both metadata and a small file as payload. +""" + + +from google.cloud.storage._media import _upload +from google.cloud.storage._media.requests import _request_helpers +from google.cloud.storage._media import _helpers + + +class SimpleUpload(_request_helpers.RequestsMixin, _upload.SimpleUpload): + """Upload a resource to a Google API. + + A **simple** media upload sends no metadata and completes the upload + in a single request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def transmit( + self, + transport, + data, + content_type, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Transmit the resource to be uploaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + data (bytes): The resource content to be uploaded. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_request(data, content_type) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +class MultipartUpload(_request_helpers.RequestsMixin, _upload.MultipartUpload): + """Upload a resource with metadata to a Google API. + + A **multipart** upload sends both metadata and the resource in a single + (multipart) request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The request metadata will be amended + to include the computed value. Using this option will override a + manually-set checksum value. Supported values are "md5", + "crc32c", "auto", and None. The default is "auto", which will try + to detect if the C extension for crc32c is installed and fall back + to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def transmit( + self, + transport, + data, + metadata, + content_type, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Transmit the resource to be uploaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_request( + data, metadata, content_type + ) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +class ResumableUpload(_request_helpers.RequestsMixin, _upload.ResumableUpload): + """Initiate and fulfill a resumable upload to a Google API. + + A **resumable** upload sends an initial request with the resource metadata + and then gets assigned an upload ID / upload URL to send bytes to. + Using the upload URL, the upload is then done in chunks (determined by + the user) until all bytes have been uploaded. + + When constructing a resumable upload, only the resumable upload URL and + the chunk size are required: + + .. testsetup:: resumable-constructor + + bucket = 'bucket-foo' + + .. doctest:: resumable-constructor + + >>> from google.cloud.storage._media.requests import ResumableUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=resumable') + >>> upload_url = url_template.format(bucket=bucket) + >>> + >>> chunk_size = 3 * 1024 * 1024 # 3MB + >>> upload = ResumableUpload(upload_url, chunk_size) + + When initiating an upload (via :meth:`initiate`), the caller is expected + to pass the resource being uploaded as a file-like ``stream``. If the size + of the resource is explicitly known, it can be passed in directly: + + .. testsetup:: resumable-explicit-size + + import os + import tempfile + + import mock + import requests + import http.client + + from google.cloud.storage._media.requests import ResumableUpload + + upload_url = 'http://test.invalid' + chunk_size = 3 * 1024 * 1024 # 3MB + upload = ResumableUpload(upload_url, chunk_size) + + file_desc, filename = tempfile.mkstemp() + os.close(file_desc) + + data = b'some bytes!' + with open(filename, 'wb') as file_obj: + file_obj.write(data) + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + resumable_url = 'http://test.invalid?upload_id=7up' + fake_response.headers['location'] = resumable_url + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + .. doctest:: resumable-explicit-size + + >>> import os + >>> + >>> upload.total_bytes is None + True + >>> + >>> stream = open(filename, 'rb') + >>> total_bytes = os.path.getsize(filename) + >>> metadata = {'name': filename} + >>> response = upload.initiate( + ... transport, stream, metadata, 'text/plain', + ... total_bytes=total_bytes) + >>> response + + >>> + >>> upload.total_bytes == total_bytes + True + + .. testcleanup:: resumable-explicit-size + + os.remove(filename) + + If the stream is in a "final" state (i.e. it won't have any more bytes + written to it), the total number of bytes can be determined implicitly + from the ``stream`` itself: + + .. testsetup:: resumable-implicit-size + + import io + + import mock + import requests + import http.client + + from google.cloud.storage._media.requests import ResumableUpload + + upload_url = 'http://test.invalid' + chunk_size = 3 * 1024 * 1024 # 3MB + upload = ResumableUpload(upload_url, chunk_size) + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + resumable_url = 'http://test.invalid?upload_id=7up' + fake_response.headers['location'] = resumable_url + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + data = b'some MOAR bytes!' + metadata = {'name': 'some-file.jpg'} + content_type = 'image/jpeg' + + .. doctest:: resumable-implicit-size + + >>> stream = io.BytesIO(data) + >>> response = upload.initiate( + ... transport, stream, metadata, content_type) + >>> + >>> upload.total_bytes == len(data) + True + + If the size of the resource is **unknown** when the upload is initiated, + the ``stream_final`` argument can be used. This might occur if the + resource is being dynamically created on the client (e.g. application + logs). To use this argument: + + .. testsetup:: resumable-unknown-size + + import io + + import mock + import requests + import http.client + + from google.cloud.storage._media.requests import ResumableUpload + + upload_url = 'http://test.invalid' + chunk_size = 3 * 1024 * 1024 # 3MB + upload = ResumableUpload(upload_url, chunk_size) + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + resumable_url = 'http://test.invalid?upload_id=7up' + fake_response.headers['location'] = resumable_url + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + metadata = {'name': 'some-file.jpg'} + content_type = 'application/octet-stream' + + stream = io.BytesIO(b'data') + + .. doctest:: resumable-unknown-size + + >>> response = upload.initiate( + ... transport, stream, metadata, content_type, + ... stream_final=False) + >>> + >>> upload.total_bytes is None + True + + Args: + upload_url (str): The URL where the resumable upload will be initiated. + chunk_size (int): The size of each chunk used to upload the resource. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the :meth:`initiate` request, e.g. headers for + encrypted data. These **will not** be sent with + :meth:`transmit_next_chunk` or :meth:`recover` requests. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be checked + and google.cloud.storage.exceptions.DataCorruption will be raised on + a mismatch. The corrupted file will not be deleted from the remote + host automatically. Supported values are "md5", "crc32c", "auto", + and None. The default is "auto", which will try to detect if the C + extension for crc32c is installed and fall back to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + + Raises: + ValueError: If ``chunk_size`` is not a multiple of + :data:`.UPLOAD_CHUNK_SIZE`. + """ + + def initiate( + self, + transport, + stream, + metadata, + content_type, + total_bytes=None, + stream_final=True, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Initiate a resumable upload. + + By default, this method assumes your ``stream`` is in a "final" + state ready to transmit. However, ``stream_final=False`` can be used + to indicate that the size of the resource is not known. This can happen + if bytes are being dynamically fed into ``stream``, e.g. if the stream + is attached to application logs. + + If ``stream_final=False`` is used, :attr:`chunk_size` bytes will be + read from the stream every time :meth:`transmit_next_chunk` is called. + If one of those reads produces strictly fewer bites than the chunk + size, the upload will be concluded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_initiate_request( + stream, + metadata, + content_type, + total_bytes=total_bytes, + stream_final=stream_final, + ) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_initiate_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + def transmit_next_chunk( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Transmit the next chunk of the resource to be uploaded. + + If the current upload was initiated with ``stream_final=False``, + this method will dynamically determine if the upload has completed. + The upload will be considered complete if the stream produces + fewer than :attr:`chunk_size` bytes when a chunk is read from it. + + In the case of failure, an exception is thrown that preserves the + failed response: + + .. testsetup:: bad-response + + import io + + import mock + import requests + import http.client + + from google.cloud.storage import _media + import google.cloud.storage._media.requests.upload as upload_mod + + transport = mock.Mock(spec=['request']) + fake_response = requests.Response() + fake_response.status_code = int(http.client.BAD_REQUEST) + transport.request.return_value = fake_response + + upload_url = 'http://test.invalid' + upload = upload_mod.ResumableUpload( + upload_url, _media.UPLOAD_CHUNK_SIZE) + # Fake that the upload has been initiate()-d + data = b'data is here' + upload._stream = io.BytesIO(data) + upload._total_bytes = len(data) + upload._resumable_url = 'http://test.invalid?upload_id=nope' + + .. doctest:: bad-response + :options: +NORMALIZE_WHITESPACE + + >>> error = None + >>> try: + ... upload.transmit_next_chunk(transport) + ... except _media.InvalidResponse as caught_exc: + ... error = caught_exc + ... + >>> error + InvalidResponse('Request failed with status code', 400, + 'Expected one of', , ) + >>> error.response + + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200 or http.client.PERMANENT_REDIRECT. + ~google.cloud.storage.exceptions.DataCorruption: If this is the final + chunk, a checksum validation was requested, and the checksum + does not match or is not available. + """ + method, url, payload, headers = self._prepare_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_resumable_response(result, len(payload)) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + def recover(self, transport): + """Recover from a failure and check the status of the current upload. + + This will verify the progress with the server and make sure the + current upload is in a valid state before :meth:`transmit_next_chunk` + can be used again. See https://cloud.google.com/storage/docs/performing-resumable-uploads#status-check + for more information. + + This method can be used when a :class:`ResumableUpload` is in an + :attr:`~ResumableUpload.invalid` state due to a request failure. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + timeout = ( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ) + + method, url, payload, headers = self._prepare_recover_request() + # NOTE: We assume "payload is None" but pass it along anyway. + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_recover_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +class XMLMPUContainer(_request_helpers.RequestsMixin, _upload.XMLMPUContainer): + """Initiate and close an upload using the XML MPU API. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with this container object, the + uploading of individual parts is handled separately, by XMLMPUPart objects + spawned from this container class. The XMLMPUPart objects are not + necessarily in the same process as the container, so they do not update the + container automatically. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). The + initiate, PUT, and finalization requests will all use this URL, with + varying query parameters. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the :meth:`initiate` request, e.g. headers for + encrypted data. These headers will be propagated to individual + XMLMPUPart objects spawned from this container as well. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + upload_id (Optional(int)): The ID of the upload from the initialization + response. + """ + + def initiate( + self, + transport, + content_type, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Initiate an MPU and record the upload ID. + + Args: + transport (object): An object which can make authenticated + requests. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + + method, url, payload, headers = self._prepare_initiate_request( + content_type, + ) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_initiate_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + def finalize( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Finalize an MPU request with all the parts. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_finalize_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_finalize_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + def cancel( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Cancel an MPU request and permanently delete any uploaded parts. + + This cannot be undone. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_cancel_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_cancel_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) + + +class XMLMPUPart(_request_helpers.RequestsMixin, _upload.XMLMPUPart): + def upload( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Upload the part. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_upload_request() + if self._checksum_object is not None: + checksum_digest_in_base64 = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + if self._checksum_type == "crc32c": + headers["X-Goog-Hash"] = f"crc32c={checksum_digest_in_base64}" + elif self._checksum_type == "md5": + headers["X-Goog-Hash"] = f"md5={checksum_digest_in_base64}" + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_upload_response(result) + + return result + + return _request_helpers.wait_and_retry(retriable_request, self._retry_strategy) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_opentelemetry_tracing.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_opentelemetry_tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..b654aae2bbc070df99b2acfe84155d71d5273b6a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_opentelemetry_tracing.py @@ -0,0 +1,149 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Manages OpenTelemetry tracing span creation and handling. This is a PREVIEW FEATURE: Coverage and functionality may change.""" + +import logging +import os + +from contextlib import contextmanager +from urllib.parse import urlparse +from google.api_core import exceptions as api_exceptions +from google.api_core import retry as api_retry +from google.cloud.storage import __version__ +from google.cloud.storage.retry import ConditionalRetryPolicy + + +ENABLE_OTEL_TRACES_ENV_VAR = "ENABLE_GCS_PYTHON_CLIENT_OTEL_TRACES" +_DEFAULT_ENABLE_OTEL_TRACES_VALUE = False + + +def _parse_bool_env(name: str, default: bool = False) -> bool: + val = os.environ.get(name, None) + if val is None: + return default + return str(val).strip().lower() in {"1", "true", "yes", "on"} + + +enable_otel_traces = _parse_bool_env( + ENABLE_OTEL_TRACES_ENV_VAR, _DEFAULT_ENABLE_OTEL_TRACES_VALUE +) +logger = logging.getLogger(__name__) + +try: + from opentelemetry import trace + + HAS_OPENTELEMETRY = True + +except ImportError: + logger.debug( + "This service is instrumented using OpenTelemetry. " + "OpenTelemetry or one of its components could not be imported; " + "please add compatible versions of opentelemetry-api and " + "opentelemetry-instrumentation packages in order to get Storage " + "Tracing data." + ) + HAS_OPENTELEMETRY = False + +_default_attributes = { + "rpc.service": "CloudStorage", + "rpc.system": "http", + "user_agent.original": f"gcloud-python/{__version__}", +} + +_cloud_trace_adoption_attrs = { + "gcp.client.service": "storage", + "gcp.client.version": __version__, + "gcp.client.repo": "googleapis/python-storage", +} + + +@contextmanager +def create_trace_span(name, attributes=None, client=None, api_request=None, retry=None): + """Creates a context manager for a new span and set it as the current span + in the configured tracer. If no configuration exists yields None.""" + if not HAS_OPENTELEMETRY or not enable_otel_traces: + yield None + return + + tracer = trace.get_tracer(__name__) + final_attributes = _get_final_attributes(attributes, client, api_request, retry) + # Yield new span. + with tracer.start_as_current_span( + name=name, kind=trace.SpanKind.CLIENT, attributes=final_attributes + ) as span: + try: + yield span + except api_exceptions.GoogleAPICallError as error: + span.set_status(trace.Status(trace.StatusCode.ERROR)) + span.record_exception(error) + raise + + +def _get_final_attributes(attributes=None, client=None, api_request=None, retry=None): + collected_attr = _default_attributes.copy() + collected_attr.update(_cloud_trace_adoption_attrs) + if api_request: + collected_attr.update(_set_api_request_attr(api_request, client)) + if isinstance(retry, api_retry.Retry): + collected_attr.update(_set_retry_attr(retry)) + if isinstance(retry, ConditionalRetryPolicy): + collected_attr.update( + _set_retry_attr(retry.retry_policy, retry.conditional_predicate) + ) + if attributes: + collected_attr.update(attributes) + final_attributes = {k: v for k, v in collected_attr.items() if v is not None} + return final_attributes + + +def _set_api_request_attr(request, client): + attr = {} + if request.get("method"): + attr["http.request.method"] = request.get("method") + if request.get("path"): + full_url = client._connection.build_api_url(request.get("path")) + attr.update(_get_opentelemetry_attributes_from_url(full_url, strip_query=True)) + if "timeout" in request: + attr["connect_timeout,read_timeout"] = str(request.get("timeout")) + return attr + + +def _set_retry_attr(retry, conditional_predicate=None): + predicate = conditional_predicate if conditional_predicate else retry._predicate + retry_info = f"multiplier{retry._multiplier}/deadline{retry._deadline}/max{retry._maximum}/initial{retry._initial}/predicate{predicate}" + return {"retry": retry_info} + + +def _get_opentelemetry_attributes_from_url(url, strip_query=True): + """Helper to assemble OpenTelemetry span attributes from a URL.""" + u = urlparse(url) + netloc = u.netloc + # u.hostname is always lowercase. We parse netloc to preserve casing. + # netloc format: [userinfo@]host[:port] + if "@" in netloc: + netloc = netloc.split("@", 1)[1] + if ":" in netloc and not netloc.endswith("]"): # Handle IPv6 literal + netloc = netloc.split(":", 1)[0] + + attributes = { + "server.address": netloc, + "server.port": u.port, + "url.scheme": u.scheme, + "url.path": u.path, + } + if not strip_query: + attributes["url.query"] = u.query + + return attributes diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_signing.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_signing.py new file mode 100644 index 0000000000000000000000000000000000000000..9f47e1a6ed0c8e7882e4e0e687237caba82578df --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/_signing.py @@ -0,0 +1,739 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import base64 +import binascii +import collections +import datetime +import hashlib +import json + +import http +import urllib + +import google.auth.credentials + +from google.auth import exceptions +from google.auth.transport import requests +from google.cloud import _helpers +from google.cloud.storage._helpers import _DEFAULT_UNIVERSE_DOMAIN +from google.cloud.storage._helpers import _NOW +from google.cloud.storage._helpers import _UTC +from google.cloud.storage.retry import DEFAULT_RETRY + + +# `google.cloud.storage._signing.NOW` is deprecated. +# Use `_NOW(_UTC)` instead. +NOW = datetime.datetime.utcnow + +SERVICE_ACCOUNT_URL = ( + "https://googleapis.dev/python/google-api-core/latest/" + "auth.html#setting-up-a-service-account" +) + + +def ensure_signed_credentials(credentials): + """Raise AttributeError if the credentials are unsigned. + + :type credentials: :class:`google.auth.credentials.Signing` + :param credentials: The credentials used to create a private key + for signing text. + + :raises: :exc:`AttributeError` if credentials is not an instance + of :class:`google.auth.credentials.Signing`. + """ + if not isinstance(credentials, google.auth.credentials.Signing): + raise AttributeError( + "you need a private key to sign credentials." + "the credentials you are currently using {} " + "just contains a token. see {} for more " + "details.".format(type(credentials), SERVICE_ACCOUNT_URL) + ) + + +def get_signed_query_params_v2(credentials, expiration, string_to_sign): + """Gets query parameters for creating a signed URL. + + :type credentials: :class:`google.auth.credentials.Signing` + :param credentials: The credentials used to create a private key + for signing text. + + :type expiration: int or long + :param expiration: When the signed URL should expire. + + :type string_to_sign: str + :param string_to_sign: The string to be signed by the credentials. + + :raises: :exc:`AttributeError` if credentials is not an instance + of :class:`google.auth.credentials.Signing`. + + :rtype: dict + :returns: Query parameters matching the signing credentials with a + signed payload. + """ + ensure_signed_credentials(credentials) + signature_bytes = credentials.sign_bytes(string_to_sign.encode("ascii")) + signature = base64.b64encode(signature_bytes) + service_account_name = credentials.signer_email + return { + "GoogleAccessId": service_account_name, + "Expires": expiration, + "Signature": signature, + } + + +def get_expiration_seconds_v2(expiration): + """Convert 'expiration' to a number of seconds in the future. + + :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] + :param expiration: Point in time when the signed URL should expire. If + a ``datetime`` instance is passed without an explicit + ``tzinfo`` set, it will be assumed to be ``UTC``. + + :raises: :exc:`TypeError` when expiration is not a valid type. + + :rtype: int + :returns: a timestamp as an absolute number of seconds since epoch. + """ + # If it's a timedelta, add it to `now` in UTC. + if isinstance(expiration, datetime.timedelta): + now = _NOW(_UTC) + expiration = now + expiration + + # If it's a datetime, convert to a timestamp. + if isinstance(expiration, datetime.datetime): + micros = _helpers._microseconds_from_datetime(expiration) + expiration = micros // 10**6 + + if not isinstance(expiration, int): + raise TypeError( + "Expected an integer timestamp, datetime, or " + "timedelta. Got %s" % type(expiration) + ) + return expiration + + +_EXPIRATION_TYPES = (int, datetime.datetime, datetime.timedelta) + + +def get_expiration_seconds_v4(expiration): + """Convert 'expiration' to a number of seconds offset from the current time. + + :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] + :param expiration: Point in time when the signed URL should expire. If + a ``datetime`` instance is passed without an explicit + ``tzinfo`` set, it will be assumed to be ``UTC``. + + :raises: :exc:`TypeError` when expiration is not a valid type. + :raises: :exc:`ValueError` when expiration is too large. + :rtype: Integer + :returns: seconds in the future when the signed URL will expire + """ + if not isinstance(expiration, _EXPIRATION_TYPES): + raise TypeError( + "Expected an integer timestamp, datetime, or " + "timedelta. Got %s" % type(expiration) + ) + + now = _NOW(_UTC) + + if isinstance(expiration, int): + seconds = expiration + + if isinstance(expiration, datetime.datetime): + if expiration.tzinfo is None: + expiration = expiration.replace(tzinfo=_helpers.UTC) + expiration = expiration - now + + if isinstance(expiration, datetime.timedelta): + seconds = int(expiration.total_seconds()) + + if seconds > SEVEN_DAYS: + raise ValueError(f"Max allowed expiration interval is seven days {SEVEN_DAYS}") + + return seconds + + +def get_canonical_headers(headers): + """Canonicalize headers for signing. + + See: + https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers + + :type headers: Union[dict|List(Tuple(str,str))] + :param headers: + (Optional) Additional HTTP headers to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers + Requests using the signed URL *must* pass the specified header + (name and value) with each request for the URL. + + :rtype: str + :returns: List of headers, normalized / sortted per the URL refernced above. + """ + if headers is None: + headers = [] + elif isinstance(headers, dict): + headers = list(headers.items()) + + if not headers: + return [], [] + + normalized = collections.defaultdict(list) + for key, val in headers: + key = key.lower().strip() + val = " ".join(val.split()) + normalized[key].append(val) + + ordered_headers = sorted((key, ",".join(val)) for key, val in normalized.items()) + + canonical_headers = ["{}:{}".format(*item) for item in ordered_headers] + return canonical_headers, ordered_headers + + +_Canonical = collections.namedtuple( + "_Canonical", ["method", "resource", "query_parameters", "headers"] +) + + +def canonicalize_v2(method, resource, query_parameters, headers): + """Canonicalize method, resource per the V2 spec. + + :type method: str + :param method: The HTTP verb that will be used when requesting the URL. + Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the + signature will additionally contain the `x-goog-resumable` + header, and the method changed to POST. See the signed URL + docs regarding this flow: + https://cloud.google.com/storage/docs/access-control/signed-urls + + :type resource: str + :param resource: A pointer to a specific resource + (typically, ``/bucket-name/path/to/blob.txt``). + + :type query_parameters: dict + :param query_parameters: + (Optional) Additional query parameters to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers#query + + :type headers: Union[dict|List(Tuple(str,str))] + :param headers: + (Optional) Additional HTTP headers to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers + Requests using the signed URL *must* pass the specified header + (name and value) with each request for the URL. + + :rtype: :class:_Canonical + :returns: Canonical method, resource, query_parameters, and headers. + """ + headers, _ = get_canonical_headers(headers) + + if method == "RESUMABLE": + method = "POST" + headers.append("x-goog-resumable:start") + + if query_parameters is None: + return _Canonical(method, resource, [], headers) + + normalized_qp = sorted( + (key.lower(), value and value.strip() or "") + for key, value in query_parameters.items() + ) + encoded_qp = urllib.parse.urlencode(normalized_qp) + canonical_resource = f"{resource}?{encoded_qp}" + return _Canonical(method, canonical_resource, normalized_qp, headers) + + +def generate_signed_url_v2( + credentials, + resource, + expiration, + api_access_endpoint="", + method="GET", + content_md5=None, + content_type=None, + response_type=None, + response_disposition=None, + generation=None, + headers=None, + query_parameters=None, + service_account_email=None, + access_token=None, + universe_domain=None, +): + """Generate a V2 signed URL to provide query-string auth'n to a resource. + + .. note:: + + Assumes ``credentials`` implements the + :class:`google.auth.credentials.Signing` interface. Also assumes + ``credentials`` has a ``signer_email`` property which + identifies the credentials. + + .. note:: + + If you are on Google Compute Engine, you can't generate a signed URL. + If you'd like to be able to generate a signed URL from GCE, you can use a + standard service account from a JSON file rather than a GCE service account. + + See headers [reference](https://cloud.google.com/storage/docs/reference-headers) + for more details on optional arguments. + + :type credentials: :class:`google.auth.credentials.Signing` + :param credentials: Credentials object with an associated private key to + sign text. + + :type resource: str + :param resource: A pointer to a specific resource + (typically, ``/bucket-name/path/to/blob.txt``). + Caller should have already URL-encoded the value. + + :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] + :param expiration: Point in time when the signed URL should expire. If + a ``datetime`` instance is passed without an explicit + ``tzinfo`` set, it will be assumed to be ``UTC``. + + :type api_access_endpoint: str + :param api_access_endpoint: (Optional) URI base. Defaults to empty string. + + :type method: str + :param method: The HTTP verb that will be used when requesting the URL. + Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the + signature will additionally contain the `x-goog-resumable` + header, and the method changed to POST. See the signed URL + docs regarding this flow: + https://cloud.google.com/storage/docs/access-control/signed-urls + + + :type content_md5: str + :param content_md5: (Optional) The MD5 hash of the object referenced by + ``resource``. + + :type content_type: str + :param content_type: (Optional) The content type of the object referenced + by ``resource``. + + :type response_type: str + :param response_type: (Optional) Content type of responses to requests for + the signed URL. Ignored if content_type is set on + object/blob metadata. + + :type response_disposition: str + :param response_disposition: (Optional) Content disposition of responses to + requests for the signed URL. + + :type generation: str + :param generation: (Optional) A value that indicates which generation of + the resource to fetch. + + :type headers: Union[dict|List(Tuple(str,str))] + :param headers: + (Optional) Additional HTTP headers to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers + Requests using the signed URL *must* pass the specified header + (name and value) with each request for the URL. + + :type service_account_email: str + :param service_account_email: (Optional) E-mail address of the service account. + + :type access_token: str + :param access_token: (Optional) Access token for a service account. + + :type query_parameters: dict + :param query_parameters: + (Optional) Additional query parameters to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers#query + + :raises: :exc:`TypeError` when expiration is not a valid type. + :raises: :exc:`AttributeError` if credentials is not an instance + of :class:`google.auth.credentials.Signing`. + + :rtype: str + :returns: A signed URL you can use to access the resource + until expiration. + """ + expiration_stamp = get_expiration_seconds_v2(expiration) + + canonical = canonicalize_v2(method, resource, query_parameters, headers) + + # Generate the string to sign. + elements_to_sign = [ + canonical.method, + content_md5 or "", + content_type or "", + str(expiration_stamp), + ] + elements_to_sign.extend(canonical.headers) + elements_to_sign.append(canonical.resource) + string_to_sign = "\n".join(elements_to_sign) + + # If you are on Google Compute Engine, you can't generate a signed URL. + # See https://github.com/googleapis/google-cloud-python/issues/922 + # Set the right query parameters. + if access_token and service_account_email: + signature = _sign_message( + string_to_sign, access_token, service_account_email, universe_domain + ) + signed_query_params = { + "GoogleAccessId": service_account_email, + "Expires": expiration_stamp, + "Signature": signature, + } + else: + signed_query_params = get_signed_query_params_v2( + credentials, expiration_stamp, string_to_sign + ) + + if response_type is not None: + signed_query_params["response-content-type"] = response_type + if response_disposition is not None: + signed_query_params["response-content-disposition"] = response_disposition + if generation is not None: + signed_query_params["generation"] = generation + + signed_query_params.update(canonical.query_parameters) + sorted_signed_query_params = sorted(signed_query_params.items()) + + # Return the built URL. + return "{endpoint}{resource}?{querystring}".format( + endpoint=api_access_endpoint, + resource=resource, + querystring=urllib.parse.urlencode(sorted_signed_query_params), + ) + + +SEVEN_DAYS = 7 * 24 * 60 * 60 # max age for V4 signed URLs. +DEFAULT_ENDPOINT = "https://storage.googleapis.com" + + +def generate_signed_url_v4( + credentials, + resource, + expiration, + api_access_endpoint=DEFAULT_ENDPOINT, + method="GET", + content_md5=None, + content_type=None, + response_type=None, + response_disposition=None, + generation=None, + headers=None, + query_parameters=None, + service_account_email=None, + access_token=None, + universe_domain=None, + _request_timestamp=None, # for testing only +): + """Generate a V4 signed URL to provide query-string auth'n to a resource. + + .. note:: + + Assumes ``credentials`` implements the + :class:`google.auth.credentials.Signing` interface. Also assumes + ``credentials`` has a ``signer_email`` property which + identifies the credentials. + + .. note:: + + If you are on Google Compute Engine, you can't generate a signed URL. + If you'd like to be able to generate a signed URL from GCE,you can use a + standard service account from a JSON file rather than a GCE service account. + + See headers [reference](https://cloud.google.com/storage/docs/reference-headers) + for more details on optional arguments. + + :type credentials: :class:`google.auth.credentials.Signing` + :param credentials: Credentials object with an associated private key to + sign text. That credentials must provide signer_email + only if service_account_email and access_token are not + passed. + + :type resource: str + :param resource: A pointer to a specific resource + (typically, ``/bucket-name/path/to/blob.txt``). + Caller should have already URL-encoded the value. + + :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] + :param expiration: Point in time when the signed URL should expire. If + a ``datetime`` instance is passed without an explicit + ``tzinfo`` set, it will be assumed to be ``UTC``. + + :type api_access_endpoint: str + :param api_access_endpoint: URI base. Defaults to + "https://storage.googleapis.com/" + + :type method: str + :param method: The HTTP verb that will be used when requesting the URL. + Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the + signature will additionally contain the `x-goog-resumable` + header, and the method changed to POST. See the signed URL + docs regarding this flow: + https://cloud.google.com/storage/docs/access-control/signed-urls + + + :type content_md5: str + :param content_md5: (Optional) The MD5 hash of the object referenced by + ``resource``. + + :type content_type: str + :param content_type: (Optional) The content type of the object referenced + by ``resource``. + + :type response_type: str + :param response_type: (Optional) Content type of responses to requests for + the signed URL. Ignored if content_type is set on + object/blob metadata. + + :type response_disposition: str + :param response_disposition: (Optional) Content disposition of responses to + requests for the signed URL. + + :type generation: str + :param generation: (Optional) A value that indicates which generation of + the resource to fetch. + + :type headers: dict + :param headers: + (Optional) Additional HTTP headers to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers + Requests using the signed URL *must* pass the specified header + (name and value) with each request for the URL. + + :type query_parameters: dict + :param query_parameters: + (Optional) Additional query parameters to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers#query + + :type service_account_email: str + :param service_account_email: (Optional) E-mail address of the service account. + + :type access_token: str + :param access_token: (Optional) Access token for a service account. + + :raises: :exc:`TypeError` when expiration is not a valid type. + :raises: :exc:`AttributeError` if credentials is not an instance + of :class:`google.auth.credentials.Signing`. + + :rtype: str + :returns: A signed URL you can use to access the resource + until expiration. + """ + expiration_seconds = get_expiration_seconds_v4(expiration) + + if _request_timestamp is None: + request_timestamp, datestamp = get_v4_now_dtstamps() + else: + request_timestamp = _request_timestamp + datestamp = _request_timestamp[:8] + + # If you are on Google Compute Engine, you can't generate a signed URL. + # See https://github.com/googleapis/google-cloud-python/issues/922 + client_email = service_account_email + if not access_token or not service_account_email: + ensure_signed_credentials(credentials) + client_email = credentials.signer_email + + credential_scope = f"{datestamp}/auto/storage/goog4_request" + credential = f"{client_email}/{credential_scope}" + + if headers is None: + headers = {} + + if content_type is not None: + headers["Content-Type"] = content_type + + if content_md5 is not None: + headers["Content-MD5"] = content_md5 + + header_names = [key.lower() for key in headers] + if "host" not in header_names: + headers["Host"] = urllib.parse.urlparse(api_access_endpoint).netloc + + if method.upper() == "RESUMABLE": + method = "POST" + headers["x-goog-resumable"] = "start" + + canonical_headers, ordered_headers = get_canonical_headers(headers) + canonical_header_string = ( + "\n".join(canonical_headers) + "\n" + ) # Yes, Virginia, the extra newline is part of the spec. + signed_headers = ";".join([key for key, _ in ordered_headers]) + + if query_parameters is None: + query_parameters = {} + else: + query_parameters = {key: value or "" for key, value in query_parameters.items()} + + query_parameters["X-Goog-Algorithm"] = "GOOG4-RSA-SHA256" + query_parameters["X-Goog-Credential"] = credential + query_parameters["X-Goog-Date"] = request_timestamp + query_parameters["X-Goog-Expires"] = expiration_seconds + query_parameters["X-Goog-SignedHeaders"] = signed_headers + + if response_type is not None: + query_parameters["response-content-type"] = response_type + + if response_disposition is not None: + query_parameters["response-content-disposition"] = response_disposition + + if generation is not None: + query_parameters["generation"] = generation + + canonical_query_string = _url_encode(query_parameters) + + lowercased_headers = dict(ordered_headers) + + if "x-goog-content-sha256" in lowercased_headers: + payload = lowercased_headers["x-goog-content-sha256"] + else: + payload = "UNSIGNED-PAYLOAD" + + canonical_elements = [ + method, + resource, + canonical_query_string, + canonical_header_string, + signed_headers, + payload, + ] + canonical_request = "\n".join(canonical_elements) + + canonical_request_hash = hashlib.sha256( + canonical_request.encode("ascii") + ).hexdigest() + + string_elements = [ + "GOOG4-RSA-SHA256", + request_timestamp, + credential_scope, + canonical_request_hash, + ] + string_to_sign = "\n".join(string_elements) + + if access_token and service_account_email: + signature = _sign_message( + string_to_sign, access_token, service_account_email, universe_domain + ) + signature_bytes = base64.b64decode(signature) + signature = binascii.hexlify(signature_bytes).decode("ascii") + else: + signature_bytes = credentials.sign_bytes(string_to_sign.encode("ascii")) + signature = binascii.hexlify(signature_bytes).decode("ascii") + + return "{}{}?{}&X-Goog-Signature={}".format( + api_access_endpoint, resource, canonical_query_string, signature + ) + + +def get_v4_now_dtstamps(): + """Get current timestamp and datestamp in V4 valid format. + + :rtype: str, str + :returns: Current timestamp, datestamp. + """ + now = _NOW(_UTC).replace(tzinfo=None) + timestamp = now.strftime("%Y%m%dT%H%M%SZ") + datestamp = now.date().strftime("%Y%m%d") + return timestamp, datestamp + + +def _sign_message( + message, + access_token, + service_account_email, + universe_domain=_DEFAULT_UNIVERSE_DOMAIN, +): + """Signs a message. + + :type message: str + :param message: The message to be signed. + + :type access_token: str + :param access_token: Access token for a service account. + + + :type service_account_email: str + :param service_account_email: E-mail address of the service account. + + :raises: :exc:`TransportError` if an `access_token` is unauthorized. + + :rtype: str + :returns: The signature of the message. + + """ + message = _helpers._to_bytes(message) + + method = "POST" + url = f"https://iamcredentials.{universe_domain}/v1/projects/-/serviceAccounts/{service_account_email}:signBlob?alt=json" + headers = { + "Authorization": "Bearer " + access_token, + "Content-type": "application/json", + } + body = json.dumps({"payload": base64.b64encode(message).decode("utf-8")}) + request = requests.Request() + + def retriable_request(): + response = request(url=url, method=method, body=body, headers=headers) + return response + + # Apply the default retry object to the signBlob call. + retry = DEFAULT_RETRY + call = retry(retriable_request) + response = call() + + if response.status != http.client.OK: + raise exceptions.TransportError( + f"Error calling the IAM signBytes API: {response.data}" + ) + + data = json.loads(response.data.decode("utf-8")) + return data["signedBlob"] + + +def _url_encode(query_params): + """Encode query params into URL. + + :type query_params: dict + :param query_params: Query params to be encoded. + + :rtype: str + :returns: URL encoded query params. + """ + params = [ + f"{_quote_param(name)}={_quote_param(value)}" + for name, value in query_params.items() + ] + + return "&".join(sorted(params)) + + +def _quote_param(param): + """Quote query param. + + :type param: Any + :param param: Query param to be encoded. + + :rtype: str + :returns: URL encoded query param. + """ + if not isinstance(param, bytes): + param = str(param) + return urllib.parse.quote(param, safe="~") diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/acl.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/acl.py new file mode 100644 index 0000000000000000000000000000000000000000..d70839e1b12bd056506c7b3fdb14759e88e7e740 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/acl.py @@ -0,0 +1,936 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Manage access to objects and buckets.""" + +from google.cloud.storage._helpers import _add_generation_match_parameters +from google.cloud.storage._opentelemetry_tracing import create_trace_span +from google.cloud.storage.constants import _DEFAULT_TIMEOUT +from google.cloud.storage.retry import DEFAULT_RETRY +from google.cloud.storage.retry import DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED + + +class _ACLEntity(object): + """Class representing a set of roles for an entity. + + This is a helper class that you likely won't ever construct + outside of using the factor methods on the :class:`ACL` object. + + :type entity_type: str + :param entity_type: The type of entity (ie, 'group' or 'user'). + + :type identifier: str + :param identifier: (Optional) The ID or e-mail of the entity. For the special + entity types (like 'allUsers'). + """ + + READER_ROLE = "READER" + WRITER_ROLE = "WRITER" + OWNER_ROLE = "OWNER" + + def __init__(self, entity_type, identifier=None): + self.identifier = identifier + self.roles = set([]) + self.type = entity_type + + def __str__(self): + if not self.identifier: + return str(self.type) + else: + return "{acl.type}-{acl.identifier}".format(acl=self) + + def __repr__(self): + return f"" + + def get_roles(self): + """Get the list of roles permitted by this entity. + + :rtype: list of strings + :returns: The list of roles associated with this entity. + """ + return self.roles + + def grant(self, role): + """Add a role to the entity. + + :type role: str + :param role: The role to add to the entity. + """ + self.roles.add(role) + + def revoke(self, role): + """Remove a role from the entity. + + :type role: str + :param role: The role to remove from the entity. + """ + if role in self.roles: + self.roles.remove(role) + + def grant_read(self): + """Grant read access to the current entity.""" + self.grant(_ACLEntity.READER_ROLE) + + def grant_write(self): + """Grant write access to the current entity.""" + self.grant(_ACLEntity.WRITER_ROLE) + + def grant_owner(self): + """Grant owner access to the current entity.""" + self.grant(_ACLEntity.OWNER_ROLE) + + def revoke_read(self): + """Revoke read access from the current entity.""" + self.revoke(_ACLEntity.READER_ROLE) + + def revoke_write(self): + """Revoke write access from the current entity.""" + self.revoke(_ACLEntity.WRITER_ROLE) + + def revoke_owner(self): + """Revoke owner access from the current entity.""" + self.revoke(_ACLEntity.OWNER_ROLE) + + +class ACL(object): + """Container class representing a list of access controls.""" + + _URL_PATH_ELEM = "acl" + _PREDEFINED_QUERY_PARAM = "predefinedAcl" + + PREDEFINED_XML_ACLS = { + # XML API name -> JSON API name + "project-private": "projectPrivate", + "public-read": "publicRead", + "public-read-write": "publicReadWrite", + "authenticated-read": "authenticatedRead", + "bucket-owner-read": "bucketOwnerRead", + "bucket-owner-full-control": "bucketOwnerFullControl", + } + + PREDEFINED_JSON_ACLS = frozenset( + [ + "private", + "projectPrivate", + "publicRead", + "publicReadWrite", + "authenticatedRead", + "bucketOwnerRead", + "bucketOwnerFullControl", + ] + ) + """See + https://cloud.google.com/storage/docs/access-control/lists#predefined-acl + """ + + loaded = False + + # Subclasses must override to provide these attributes (typically, + # as properties). + reload_path = None + save_path = None + user_project = None + + def __init__(self): + self.entities = {} + + def _ensure_loaded(self, timeout=_DEFAULT_TIMEOUT): + """Load if not already loaded. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + """ + if not self.loaded: + self.reload(timeout=timeout) + + @classmethod + def validate_predefined(cls, predefined): + """Ensures predefined is in list of predefined json values + + :type predefined: str + :param predefined: name of a predefined acl + + :type predefined: str + :param predefined: validated JSON name of predefined acl + + :raises: :exc: `ValueError`: If predefined is not a valid acl + """ + predefined = cls.PREDEFINED_XML_ACLS.get(predefined, predefined) + if predefined and predefined not in cls.PREDEFINED_JSON_ACLS: + raise ValueError(f"Invalid predefined ACL: {predefined}") + return predefined + + def reset(self): + """Remove all entities from the ACL, and clear the ``loaded`` flag.""" + self.entities.clear() + self.loaded = False + + def __iter__(self): + self._ensure_loaded() + + for entity in self.entities.values(): + for role in entity.get_roles(): + if role: + yield {"entity": str(entity), "role": role} + + def entity_from_dict(self, entity_dict): + """Build an _ACLEntity object from a dictionary of data. + + An entity is a mutable object that represents a list of roles + belonging to either a user or group or the special types for all + users and all authenticated users. + + :type entity_dict: dict + :param entity_dict: Dictionary full of data from an ACL lookup. + + :rtype: :class:`_ACLEntity` + :returns: An Entity constructed from the dictionary. + """ + entity = entity_dict["entity"] + role = entity_dict["role"] + + if entity == "allUsers": + entity = self.all() + + elif entity == "allAuthenticatedUsers": + entity = self.all_authenticated() + + elif "-" in entity: + entity_type, identifier = entity.split("-", 1) + entity = self.entity(entity_type=entity_type, identifier=identifier) + + if not isinstance(entity, _ACLEntity): + raise ValueError(f"Invalid dictionary: {entity_dict}") + + entity.grant(role) + return entity + + def has_entity(self, entity): + """Returns whether or not this ACL has any entries for an entity. + + :type entity: :class:`_ACLEntity` + :param entity: The entity to check for existence in this ACL. + + :rtype: bool + :returns: True of the entity exists in the ACL. + """ + self._ensure_loaded() + return str(entity) in self.entities + + def get_entity(self, entity, default=None): + """Gets an entity object from the ACL. + + :type entity: :class:`_ACLEntity` or string + :param entity: The entity to get lookup in the ACL. + + :type default: anything + :param default: This value will be returned if the entity + doesn't exist. + + :rtype: :class:`_ACLEntity` + :returns: The corresponding entity or the value provided + to ``default``. + """ + self._ensure_loaded() + return self.entities.get(str(entity), default) + + def add_entity(self, entity): + """Add an entity to the ACL. + + :type entity: :class:`_ACLEntity` + :param entity: The entity to add to this ACL. + """ + self._ensure_loaded() + self.entities[str(entity)] = entity + + def entity(self, entity_type, identifier=None): + """Factory method for creating an Entity. + + If an entity with the same type and identifier already exists, + this will return a reference to that entity. If not, it will + create a new one and add it to the list of known entities for + this ACL. + + :type entity_type: str + :param entity_type: The type of entity to create + (ie, ``user``, ``group``, etc) + + :type identifier: str + :param identifier: The ID of the entity (if applicable). + This can be either an ID or an e-mail address. + + :rtype: :class:`_ACLEntity` + :returns: A new Entity or a reference to an existing identical entity. + """ + entity = _ACLEntity(entity_type=entity_type, identifier=identifier) + if self.has_entity(entity): + entity = self.get_entity(entity) + else: + self.add_entity(entity) + return entity + + def user(self, identifier): + """Factory method for a user Entity. + + :type identifier: str + :param identifier: An id or e-mail for this particular user. + + :rtype: :class:`_ACLEntity` + :returns: An Entity corresponding to this user. + """ + return self.entity("user", identifier=identifier) + + def group(self, identifier): + """Factory method for a group Entity. + + :type identifier: str + :param identifier: An id or e-mail for this particular group. + + :rtype: :class:`_ACLEntity` + :returns: An Entity corresponding to this group. + """ + return self.entity("group", identifier=identifier) + + def domain(self, domain): + """Factory method for a domain Entity. + + :type domain: str + :param domain: The domain for this entity. + + :rtype: :class:`_ACLEntity` + :returns: An entity corresponding to this domain. + """ + return self.entity("domain", identifier=domain) + + def all(self): + """Factory method for an Entity representing all users. + + :rtype: :class:`_ACLEntity` + :returns: An entity representing all users. + """ + return self.entity("allUsers") + + def all_authenticated(self): + """Factory method for an Entity representing all authenticated users. + + :rtype: :class:`_ACLEntity` + :returns: An entity representing all authenticated users. + """ + return self.entity("allAuthenticatedUsers") + + def get_entities(self): + """Get a list of all Entity objects. + + :rtype: list of :class:`_ACLEntity` objects + :returns: A list of all Entity objects. + """ + self._ensure_loaded() + return list(self.entities.values()) + + @property + def client(self): + """Abstract getter for the object client.""" + raise NotImplementedError + + def _require_client(self, client): + """Check client or verify over-ride. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current ACL. + + :rtype: :class:`google.cloud.storage.client.Client` + :returns: The client passed in or the currently bound client. + """ + if client is None: + client = self.client + return client + + def reload(self, client=None, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY): + """Reload the ACL data from Cloud Storage. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: :class:`~google.api_core.retry.Retry` + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.ACL.reload"): + path = self.reload_path + client = self._require_client(client) + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + self.entities.clear() + + found = client._get_resource( + path, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + self.loaded = True + + for entry in found.get("items", ()): + self.add_entity(self.entity_from_dict(entry)) + + def _save( + self, + acl, + predefined, + client, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Helper for :meth:`save` and :meth:`save_predefined`. + + :type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list. + :param acl: The ACL object to save. If left blank, this will save + current entries. + + :type predefined: str + :param predefined: An identifier for a predefined ACL. Must be one of the + keys in :attr:`PREDEFINED_JSON_ACLS` If passed, `acl` must be None. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + client = self._require_client(client) + query_params = {"projection": "full"} + + if predefined is not None: + acl = [] + query_params[self._PREDEFINED_QUERY_PARAM] = predefined + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + + path = self.save_path + + result = client._patch_resource( + path, + {self._URL_PATH_ELEM: list(acl)}, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + + self.entities.clear() + + for entry in result.get(self._URL_PATH_ELEM, ()): + self.add_entity(self.entity_from_dict(entry)) + + self.loaded = True + + def save( + self, + acl=None, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Save this ACL for the current bucket. + + If :attr:`user_project` is set, bills the API request to that project. + + :type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list. + :param acl: The ACL object to save. If left blank, this will save + current entries. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.ACL.save"): + if acl is None: + acl = self + save_to_backend = acl.loaded + else: + save_to_backend = True + + if save_to_backend: + self._save( + acl, + None, + client, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + + def save_predefined( + self, + predefined, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Save this ACL for the current bucket using a predefined ACL. + + If :attr:`user_project` is set, bills the API request to that project. + + :type predefined: str + :param predefined: An identifier for a predefined ACL. Must be one + of the keys in :attr:`PREDEFINED_JSON_ACLS` + or :attr:`PREDEFINED_XML_ACLS` (which will be + aliased to the corresponding JSON name). + If passed, `acl` must be None. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.ACL.savePredefined"): + predefined = self.validate_predefined(predefined) + self._save( + None, + predefined, + client, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + + def clear( + self, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Remove all ACL entries. + + If :attr:`user_project` is set, bills the API request to that project. + + Note that this won't actually remove *ALL* the rules, but it + will remove all the non-default rules. In short, you'll still + have access to a bucket that you created even after you clear + ACL rules with this method. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.ACL.clear"): + self.save( + [], + client=client, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + + +class BucketACL(ACL): + """An ACL specifically for a bucket. + + :type bucket: :class:`google.cloud.storage.bucket.Bucket` + :param bucket: The bucket to which this ACL relates. + """ + + def __init__(self, bucket): + super(BucketACL, self).__init__() + self.bucket = bucket + + @property + def client(self): + """The client bound to this ACL's bucket.""" + return self.bucket.client + + @property + def reload_path(self): + """Compute the path for GET API requests for this ACL.""" + return f"{self.bucket.path}/{self._URL_PATH_ELEM}" + + @property + def save_path(self): + """Compute the path for PATCH API requests for this ACL.""" + return self.bucket.path + + @property + def user_project(self): + """Compute the user project charged for API requests for this ACL.""" + return self.bucket.user_project + + +class DefaultObjectACL(BucketACL): + """A class representing the default object ACL for a bucket.""" + + _URL_PATH_ELEM = "defaultObjectAcl" + _PREDEFINED_QUERY_PARAM = "predefinedDefaultObjectAcl" + + +class ObjectACL(ACL): + """An ACL specifically for a Cloud Storage object / blob. + + :type blob: :class:`google.cloud.storage.blob.Blob` + :param blob: The blob that this ACL corresponds to. + """ + + def __init__(self, blob): + super(ObjectACL, self).__init__() + self.blob = blob + + @property + def client(self): + """The client bound to this ACL's blob.""" + return self.blob.client + + @property + def reload_path(self): + """Compute the path for GET API requests for this ACL.""" + return f"{self.blob.path}/acl" + + @property + def save_path(self): + """Compute the path for PATCH API requests for this ACL.""" + return self.blob.path + + @property + def user_project(self): + """Compute the user project charged for API requests for this ACL.""" + return self.blob.user_project + + def save( + self, + acl=None, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Save this ACL for the current object. + + If :attr:`user_project` is set, bills the API request to that project. + + :type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list. + :param acl: The ACL object to save. If left blank, this will save + current entries. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + super().save( + acl=acl, + client=client, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + + def save_predefined( + self, + predefined, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Save this ACL for the current object using a predefined ACL. + + If :attr:`user_project` is set, bills the API request to that project. + + :type predefined: str + :param predefined: An identifier for a predefined ACL. Must be one + of the keys in :attr:`PREDEFINED_JSON_ACLS` + or :attr:`PREDEFINED_XML_ACLS` (which will be + aliased to the corresponding JSON name). + If passed, `acl` must be None. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + super().save_predefined( + predefined=predefined, + client=client, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + + def clear( + self, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Remove all ACL entries. + + If :attr:`user_project` is set, bills the API request to that project. + + Note that this won't actually remove *ALL* the rules, but it + will remove all the non-default rules. In short, you'll still + have access to a bucket that you created even after you clear + ACL rules with this method. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the ACL's parent. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + super().clear( + client=client, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/_utils.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..170a0cfae929e56691528e551eaf79a7922151d7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/_utils.py @@ -0,0 +1,41 @@ +# 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import google_crc32c + +from google.api_core import exceptions + + +def raise_if_no_fast_crc32c(): + """Check if the C-accelerated version of google-crc32c is available. + + If not, raise an error to prevent silent performance degradation. + + raises google.api_core.exceptions.FailedPrecondition: If the C extension is not available. + returns: True if the C extension is available. + rtype: bool + + """ + if google_crc32c.implementation != "c": + raise exceptions.FailedPrecondition( + "The google-crc32c package is not installed with C support. " + "C extension is required for faster data integrity checks." + "For more information, see https://github.com/googleapis/python-crc32c." + ) + + +def update_write_handle_if_exists(obj, response): + """Update the write_handle attribute of an object if it exists in the response.""" + if hasattr(response, "write_handle") and response.write_handle is not None: + obj.write_handle = response.write_handle diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_abstract_object_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_abstract_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..26cbab7a0956601828f3fd862a3f4f50576d31be --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_abstract_object_stream.py @@ -0,0 +1,67 @@ +# 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 Any, Optional + + +class _AsyncAbstractObjectStream(abc.ABC): + """Abstract base class to represent gRPC bidi-stream for GCS ``Object``. + + Concrete implementation of this class could be ``_AsyncReadObjectStream`` + or ``_AsyncWriteObjectStream``. + + :type bucket_name: str + :param bucket_name: (Optional) The name of the bucket containing the object. + + :type object_name: str + :param object_name: (Optional) The name of the object. + + :type generation_number: int + :param generation_number: (Optional) If present, selects a specific revision of + this object. + + :type handle: Any + :param handle: (Optional) The handle for the object, could be read_handle or + write_handle, based on how the stream is used. + """ + + def __init__( + self, + bucket_name: str, + object_name: str, + generation_number: Optional[int] = None, + handle: Optional[Any] = None, + ) -> None: + super().__init__() + self.bucket_name: str = bucket_name + self.object_name: str = object_name + self.generation_number: Optional[int] = generation_number + self.handle: Optional[Any] = handle + + @abc.abstractmethod + async def open(self) -> None: + pass + + @abc.abstractmethod + async def close(self) -> None: + pass + + @abc.abstractmethod + async def send(self, protobuf: Any) -> None: + pass + + @abc.abstractmethod + async def recv(self) -> Any: + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_appendable_object_writer.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_appendable_object_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..c65209680c694d12a6d259f46e964d7c474169d8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_appendable_object_writer.py @@ -0,0 +1,585 @@ +# 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 io import BufferedReader +import io +import logging +from typing import List, Optional, Tuple, Union + +from google.api_core import exceptions +from google.api_core.retry_async import AsyncRetry +from google.rpc import status_pb2 +from google.cloud._storage_v2.types import BidiWriteObjectRedirectedError +from google.cloud._storage_v2.types.storage import BidiWriteObjectRequest + + +from . import _utils +from google.cloud import _storage_v2 +from google.cloud.storage.asyncio.async_grpc_client import ( + AsyncGrpcClient, +) +from google.cloud.storage.asyncio.async_write_object_stream import ( + _AsyncWriteObjectStream, +) +from google.cloud.storage.asyncio.retry.bidi_stream_retry_manager import ( + _BidiStreamRetryManager, +) +from google.cloud.storage.asyncio.retry.writes_resumption_strategy import ( + _WriteResumptionStrategy, + _WriteState, +) +from google.cloud.storage.asyncio.retry._helpers import ( + _extract_bidi_writes_redirect_proto, +) + +_MAX_CHUNK_SIZE_BYTES = 2 * 1024 * 1024 # 2 MiB +_DEFAULT_FLUSH_INTERVAL_BYTES = 16 * 1024 * 1024 # 16 MiB +_BIDI_WRITE_REDIRECTED_TYPE_URL = ( + "type.googleapis.com/google.storage.v2.BidiWriteObjectRedirectedError" +) +logger = logging.getLogger(__name__) + + +def _is_write_retryable(exc): + """Predicate to determine if a write operation should be retried.""" + + if isinstance( + exc, + ( + exceptions.InternalServerError, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + exceptions.TooManyRequests, + BidiWriteObjectRedirectedError, + ), + ): + logger.warning(f"Retryable write exception encountered: {exc}") + return True + + grpc_error = None + if isinstance(exc, exceptions.Aborted) and exc.errors: + grpc_error = exc.errors[0] + if isinstance(grpc_error, BidiWriteObjectRedirectedError): + return True + + trailers = grpc_error.trailing_metadata() + if not trailers: + return False + + status_details_bin = None + for key, value in trailers: + if key == "grpc-status-details-bin": + status_details_bin = value + break + + if status_details_bin: + status_proto = status_pb2.Status() + try: + status_proto.ParseFromString(status_details_bin) + for detail in status_proto.details: + if detail.type_url == _BIDI_WRITE_REDIRECTED_TYPE_URL: + return True + except Exception: + logger.error( + "Error unpacking redirect details from gRPC error. Exception: ", + {exc}, + ) + return False + return False + + +class AsyncAppendableObjectWriter: + """Class for appending data to a GCS Appendable Object asynchronously.""" + + def __init__( + self, + client: AsyncGrpcClient, + bucket_name: str, + object_name: str, + generation: Optional[int] = None, + write_handle: Optional[_storage_v2.BidiWriteHandle] = None, + writer_options: Optional[dict] = None, + ): + """ + Class for appending data to a GCS Appendable Object. + + Example usage: + + ``` + + from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient + from google.cloud.storage.asyncio.async_appendable_object_writer import AsyncAppendableObjectWriter + import asyncio + + client = AsyncGrpcClient() + bucket_name = "my-bucket" + object_name = "my-appendable-object" + + # instantiate the writer + writer = AsyncAppendableObjectWriter(client, bucket_name, object_name) + # open the writer, (underlying gRPC bidi-stream will be opened) + await writer.open() + + # append data, it can be called multiple times. + await writer.append(b"hello world") + await writer.append(b"some more data") + + # optionally flush data to persist. + await writer.flush() + + # close the gRPC stream. + # Please note closing the program will also close the stream, + # however it's recommended to close the stream if no more data to append + # to clean up gRPC connection (which means CPU/memory/network resources) + await writer.close() + ``` + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient` + :param client: async grpc client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the GCS bucket containing the object. + + :type object_name: str + :param object_name: The name of the GCS Appendable Object to be written. + + :type generation: Optional[int] + :param generation: (Optional) If present, creates writer for that + specific revision of that object. Use this to append data to an + existing Appendable Object. + + Setting to ``0`` makes the `writer.open()` succeed only if + object doesn't exist in the bucket (useful for not accidentally + overwriting existing objects). + + Warning: If `None`, a new object is created. If an object with the + same name already exists, it will be overwritten the moment + `writer.open()` is called. + + :type write_handle: _storage_v2.BidiWriteHandle + :param write_handle: (Optional) An handle for writing the object. + If provided, opening the bidi-gRPC connection will be faster. + + :type writer_options: dict + :param writer_options: (Optional) A dictionary of writer options. + Supported options: + - "FLUSH_INTERVAL_BYTES": int + The number of bytes to append before "persisting" data in GCS + servers. Default is `_DEFAULT_FLUSH_INTERVAL_BYTES`. + Must be a multiple of `_MAX_CHUNK_SIZE_BYTES`. + """ + _utils.raise_if_no_fast_crc32c() + self.client = client + self.bucket_name = bucket_name + self.object_name = object_name + self.write_handle = write_handle + self.generation = generation + + self.write_obj_stream: Optional[_AsyncWriteObjectStream] = None + self._is_stream_open: bool = False + # `offset` is the latest size of the object without staleless. + self.offset: Optional[int] = None + # `persisted_size` is the total_bytes persisted in the GCS server. + # Please note: `offset` and `persisted_size` are same when the stream is + # opened. + self.persisted_size: Optional[int] = None + if writer_options is None: + writer_options = {} + self.flush_interval = writer_options.get( + "FLUSH_INTERVAL_BYTES", _DEFAULT_FLUSH_INTERVAL_BYTES + ) + if self.flush_interval < _MAX_CHUNK_SIZE_BYTES: + raise exceptions.OutOfRange( + f"flush_interval must be >= {_MAX_CHUNK_SIZE_BYTES} , but provided {self.flush_interval}" + ) + if self.flush_interval % _MAX_CHUNK_SIZE_BYTES != 0: + raise exceptions.OutOfRange( + f"flush_interval must be a multiple of {_MAX_CHUNK_SIZE_BYTES}, but provided {self.flush_interval}" + ) + self.bytes_appended_since_last_flush = 0 + self._routing_token: Optional[str] = None + self.object_resource: Optional[_storage_v2.Object] = None + self._flush_count = 0 + + async def state_lookup(self) -> int: + """Returns the persisted_size + + :rtype: int + :returns: persisted size. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before state_lookup().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest( + state_lookup=True, + ) + ) + response = await self.write_obj_stream.recv() + self.persisted_size = response.persisted_size + return self.persisted_size + + def _on_open_error(self, exc): + """Extracts routing token and write handle on redirect error during open.""" + redirect_proto = _extract_bidi_writes_redirect_proto(exc) + if redirect_proto: + if redirect_proto.routing_token: + self._routing_token = redirect_proto.routing_token + if redirect_proto.write_handle: + self.write_handle = redirect_proto.write_handle + if redirect_proto.generation: + self.generation = redirect_proto.generation + + async def open( + self, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Opens the underlying bidi-gRPC stream. + + :raises ValueError: If the stream is already open. + + """ + if self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is already open") + + if retry_policy is None: + retry_policy = AsyncRetry( + predicate=_is_write_retryable, on_error=self._on_open_error + ) + else: + original_on_error = retry_policy._on_error + + def combined_on_error(exc): + self._on_open_error(exc) + if original_on_error: + original_on_error(exc) + + retry_policy = AsyncRetry( + predicate=_is_write_retryable, + initial=retry_policy._initial, + maximum=retry_policy._maximum, + multiplier=retry_policy._multiplier, + deadline=retry_policy._deadline, + on_error=combined_on_error, + ) + + async def _do_open(): + current_metadata = list(metadata) if metadata else [] + + # Cleanup stream from previous failed attempt, if any. + if self.write_obj_stream: + if self.write_obj_stream.is_stream_open: + try: + await self.write_obj_stream.close() + except Exception as e: + logger.warning( + f"Error closing previous write stream during open retry. Got exception: {e}" + ) + self.write_obj_stream = None + self._is_stream_open = False + + self.write_obj_stream = _AsyncWriteObjectStream( + client=self.client.grpc_client, + bucket_name=self.bucket_name, + object_name=self.object_name, + generation_number=self.generation, + write_handle=self.write_handle, + routing_token=self._routing_token, + ) + + if self._routing_token: + current_metadata.append( + ("x-goog-request-params", f"routing_token={self._routing_token}") + ) + + await self.write_obj_stream.open( + metadata=current_metadata if current_metadata else None + ) + + if self.write_obj_stream.generation_number: + self.generation = self.write_obj_stream.generation_number + if self.write_obj_stream.write_handle: + self.write_handle = self.write_obj_stream.write_handle + if self.write_obj_stream.persisted_size is not None: + self.persisted_size = self.write_obj_stream.persisted_size + # set offset while opening + self.offset = self.persisted_size + + self._is_stream_open = True + self._routing_token = None + + await retry_policy(_do_open)() + + async def append( + self, + data: bytes, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Appends data to the Appendable object with automatic retries. + + calling `self.append` will append bytes at the end of the current size + ie. `self.offset` bytes relative to the begining of the object. + + This method sends the provided `data` to the GCS server in chunks. + and persists data in GCS at every `_DEFAULT_FLUSH_INTERVAL_BYTES` bytes + or at the last chunk whichever is earlier. Persisting is done by setting + `flush=True` on request. + + :type data: bytes + :param data: The bytes to append to the object. + + :type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry` + :param retry_policy: (Optional) The retry policy to use for the operation. + + :type metadata: List[Tuple[str, str]] + :param metadata: (Optional) The metadata to be sent with the request. + + :raises ValueError: If the stream is not open. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before append().") + if not data: + logger.debug("No data provided to append; returning without action.") + return + + if retry_policy is None: + retry_policy = AsyncRetry(predicate=_is_write_retryable) + + strategy = _WriteResumptionStrategy() + buffer = io.BytesIO(data) + attempt_count = 0 + + def send_and_recv_generator( + requests: List[BidiWriteObjectRequest], + state: dict[str, _WriteState], + metadata: Optional[List[Tuple[str, str]]] = None, + ): + async def generator(): + nonlocal attempt_count + nonlocal requests + attempt_count += 1 + resp = None + write_state = state["write_state"] + # If this is a retry or redirect, we must re-open the stream + if attempt_count > 1 or write_state.routing_token: + logger.info( + f"Re-opening the stream with attempt_count: {attempt_count}" + ) + + current_metadata = list(metadata) if metadata else [] + if write_state.routing_token: + current_metadata.append( + ( + "x-goog-request-params", + f"routing_token={write_state.routing_token}", + ) + ) + self._routing_token = write_state.routing_token + + self._is_stream_open = False + await self.open(metadata=current_metadata) + + write_state.persisted_size = self.persisted_size + write_state.write_handle = self.write_handle + write_state.routing_token = None + + write_state.user_buffer.seek(write_state.persisted_size) + write_state.bytes_sent = write_state.persisted_size + write_state.bytes_since_last_flush = 0 + self.bytes_appended_since_last_flush = 0 + + requests = strategy.generate_requests(state) + + for chunk_req in requests: + await self.write_obj_stream.send(chunk_req) + if chunk_req.flush: + self._flush_count += 1 + + resp = None + if chunk_req.state_lookup: + # TODO: if there's error, it'll raise error + # and will be handled by `recover_state_on_failure` + resp = await self.write_obj_stream.recv() + + if resp: + if resp.persisted_size is not None: + self.persisted_size = resp.persisted_size + state["write_state"].persisted_size = resp.persisted_size + self.offset = self.persisted_size + if resp.write_handle: + self.write_handle = resp.write_handle + state["write_state"].write_handle = resp.write_handle + + yield resp + + return generator() + + # State initialization + write_state = _WriteState(_MAX_CHUNK_SIZE_BYTES, buffer, self.flush_interval) + write_state.write_handle = self.write_handle + write_state.persisted_size = self.persisted_size + # offset is set during `open()` call. + write_state.bytes_sent = self.offset or 0 + write_state.bytes_since_last_flush = self.bytes_appended_since_last_flush + + retry_manager = _BidiStreamRetryManager( + _WriteResumptionStrategy(), + lambda r, s: send_and_recv_generator(r, s, metadata), + ) + await retry_manager.execute({"write_state": write_state}, retry_policy) + + # Sync local markers + self.bytes_appended_since_last_flush = write_state.bytes_since_last_flush + self.offset = write_state.bytes_sent + + async def simple_flush(self) -> None: + """Flushes the data to the server. + Please note: Unlike `flush` it does not do `state_lookup` + + :rtype: None + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before simple_flush().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest( + flush=True, + ) + ) + self.bytes_appended_since_last_flush = 0 + + async def flush(self) -> int: + """Flushes the data to the server. + + :rtype: int + :returns: The persisted size after flush. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before flush().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest( + flush=True, + state_lookup=True, + ) + ) + response = await self.write_obj_stream.recv() + self.persisted_size = response.persisted_size + self.offset = self.persisted_size + self.bytes_appended_since_last_flush = 0 + return self.persisted_size + + async def close(self, finalize_on_close=False) -> Union[int, _storage_v2.Object]: + """Closes the underlying bidi-gRPC stream. + + :type finalize_on_close: bool + :param finalize_on_close: Finalizes the Appendable Object. No more data + can be appended. + + rtype: Union[int, _storage_v2.Object] + returns: Updated `self.persisted_size` by default after closing the + bidi-gRPC stream. However, if `finalize_on_close=True` is passed, + returns the finalized object resource. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before close().") + + if finalize_on_close: + return await self.finalize() + + await self.write_obj_stream.close() + + self._is_stream_open = False + return self.persisted_size + + async def finalize(self) -> _storage_v2.Object: + """Finalizes the Appendable Object. + + Note: Once finalized no more data can be appended. + This method is different from `close`. if `.close()` is called data may + still be appended to object at a later point in time by opening with + generation number. + (i.e. `open(..., generation=)`. + However if `.finalize()` is called no more data can be appended to the + object. + + rtype: google.cloud.storage_v2.types.Object + returns: The finalized object resource. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before finalize().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest(finish_write=True) + ) + response = await self.write_obj_stream.recv() + self.object_resource = response.resource + self.persisted_size = self.object_resource.size + await self.write_obj_stream.close() + + self._is_stream_open = False + self.offset = None + return self.object_resource + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open + + # helper methods. + async def append_from_string(self, data: str): + """ + str data will be encoded to bytes using utf-8 encoding calling + + self.append(data.encode("utf-8")) + """ + raise NotImplementedError("append_from_string is not implemented yet.") + + async def append_from_stream(self, stream_obj): + """ + At a time read a chunk of data (16MiB) from `stream_obj` + and call self.append(chunk) + """ + raise NotImplementedError("append_from_stream is not implemented yet.") + + async def append_from_file( + self, file_obj: BufferedReader, block_size: int = _DEFAULT_FLUSH_INTERVAL_BYTES + ): + """ + Appends data to an Appendable Object using file_handle which is opened + for reading in binary mode. + + :type file_obj: file + :param file_obj: A file handle opened in binary mode for reading. + + """ + while block := file_obj.read(block_size): + await self.append(block) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_grpc_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_grpc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..90ca78bfb969a4e4d409323b1ef3e07f46b105ad --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_grpc_client.py @@ -0,0 +1,250 @@ +# 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. + +"""An async client for interacting with Google Cloud Storage using the gRPC API.""" + +from google.cloud import _storage_v2 as storage_v2 +from google.cloud._storage_v2.services.storage.transports.base import ( + DEFAULT_CLIENT_INFO, +) +from google.cloud.storage import __version__ +import grpc +from google.auth import credentials as auth_credentials + + +class AsyncGrpcClient: + """An asynchronous client for interacting with Google Cloud Storage using the gRPC API. + + :type credentials: :class:`~google.auth.credentials.Credentials` + :param credentials: (Optional) The OAuth2 Credentials to use for this + client. If not passed, falls back to the default + inferred from the environment. + + :type client_info: :class:`~google.api_core.client_info.ClientInfo` + :param client_info: + The client info used to send a user-agent string along with API + requests. If ``None``, then default info will be used. + + :type client_options: :class:`~google.api_core.client_options.ClientOptions` + :param client_options: (Optional) Client options used to set user options + on the client. + + :type attempt_direct_path: bool + :param attempt_direct_path: + (Optional) Whether to attempt to use DirectPath for gRPC connections. + Defaults to ``True``. + """ + + def __init__( + self, + credentials=None, + client_info=None, + client_options=None, + *, + attempt_direct_path=True, + ): + if isinstance(credentials, auth_credentials.AnonymousCredentials): + if client_options is None or client_options.api_endpoint is None: + raise ValueError( + "Either client_options or `client_option.api_endpoint` is None. Please provide api_endpoint when `AnonymousCredentials` is used " + ) + self._grpc_client = self._create_anonymous_client( + client_options, credentials + ) + return + + if client_info is None: + client_info = DEFAULT_CLIENT_INFO + client_info.client_library_version = __version__ + if client_info.user_agent is None: + client_info.user_agent = "" + agent_version = f"gcloud-python/{__version__}" + if agent_version not in client_info.user_agent: + client_info.user_agent += f" {agent_version} " + + self._grpc_client = self._create_async_grpc_client( + credentials=credentials, + client_info=client_info, + client_options=client_options, + attempt_direct_path=attempt_direct_path, + ) + + def _create_anonymous_client(self, client_options, credentials): + channel = grpc.aio.insecure_channel(client_options.api_endpoint) + transport = storage_v2.services.storage.transports.StorageGrpcAsyncIOTransport( + channel=channel, credentials=credentials + ) + return storage_v2.StorageAsyncClient(transport=transport) + + @classmethod + def _create_insecure_grpc_client(cls, client_options): + return cls( + credentials=auth_credentials.AnonymousCredentials(), + client_options=client_options, + attempt_direct_path=False, + ) + + def _create_async_grpc_client( + self, + credentials=None, + client_info=None, + client_options=None, + attempt_direct_path=True, + ): + transport_cls = storage_v2.StorageAsyncClient.get_transport_class( + "grpc_asyncio" + ) + + primary_user_agent = client_info.to_user_agent() + + channel = transport_cls.create_channel( + attempt_direct_path=attempt_direct_path, + credentials=credentials, + options=(("grpc.primary_user_agent", primary_user_agent),), + ) + transport = transport_cls(channel=channel) + + return storage_v2.StorageAsyncClient( + transport=transport, + client_info=client_info, + client_options=client_options, + ) + + @property + def grpc_client(self): + """The underlying gRPC client. + + This property gives users direct access to the `_storage_v2.StorageAsyncClient` + instance. This can be useful for accessing + newly added or experimental RPCs that are not yet exposed through + the high-level GrpcClient. + Returns: + google.cloud._storage_v2.StorageAsyncClient: The configured GAPIC client. + """ + return self._grpc_client + + async def delete_object( + self, + bucket_name, + object_name, + generation=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + **kwargs, + ): + """Deletes an object and its metadata. + + :type bucket_name: str + :param bucket_name: The name of the bucket in which the object resides. + + :type object_name: str + :param object_name: The name of the object to delete. + + :type generation: int + :param generation: + (Optional) If present, permanently deletes a specific generation + of an object. + + :type if_generation_match: int + :param if_generation_match: (Optional) + + :type if_generation_not_match: int + :param if_generation_not_match: (Optional) + + :type if_metageneration_match: int + :param if_metageneration_match: (Optional) + + :type if_metageneration_not_match: int + :param if_metageneration_not_match: (Optional) + + + """ + # The gRPC API requires the bucket name to be in the format "projects/_/buckets/bucket_name" + bucket_path = f"projects/_/buckets/{bucket_name}" + request = storage_v2.DeleteObjectRequest( + bucket=bucket_path, + object=object_name, + generation=generation, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + **kwargs, + ) + await self._grpc_client.delete_object(request=request) + + async def get_object( + self, + bucket_name, + object_name, + generation=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + soft_deleted=None, + **kwargs, + ): + """Retrieves an object's metadata. + + In the gRPC API, this is performed by the GetObject RPC, which + returns the object resource (metadata) without the object's data. + + :type bucket_name: str + :param bucket_name: The name of the bucket in which the object resides. + + :type object_name: str + :param object_name: The name of the object. + + :type generation: int + :param generation: + (Optional) If present, selects a specific generation of an object. + + :type if_generation_match: int + :param if_generation_match: (Optional) Precondition for object generation match. + + :type if_generation_not_match: int + :param if_generation_not_match: (Optional) Precondition for object generation mismatch. + + :type if_metageneration_match: int + :param if_metageneration_match: (Optional) Precondition for metageneration match. + + :type if_metageneration_not_match: int + :param if_metageneration_not_match: (Optional) Precondition for metageneration mismatch. + + :type soft_deleted: bool + :param soft_deleted: + (Optional) If True, return the soft-deleted version of this object. + + :rtype: :class:`google.cloud._storage_v2.types.Object` + :returns: The object metadata resource. + """ + bucket_path = f"projects/_/buckets/{bucket_name}" + + request = storage_v2.GetObjectRequest( + bucket=bucket_path, + object=object_name, + generation=generation, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + soft_deleted=soft_deleted or False, + **kwargs, + ) + + # Calls the underlying GAPIC StorageAsyncClient.get_object method + return await self._grpc_client.get_object(request=request) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_multi_range_downloader.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_multi_range_downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..51afd255bda1006591100d0086b7224e60eef7d6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_multi_range_downloader.py @@ -0,0 +1,528 @@ +# 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 +import asyncio +import logging +from google.api_core import exceptions +from google.api_core.retry_async import AsyncRetry +from google.cloud.storage.asyncio.retry._helpers import _handle_redirect +from google.rpc import status_pb2 + +from typing import List, Optional, Tuple, Any, Dict + +from ._utils import raise_if_no_fast_crc32c +from google.cloud.storage.asyncio.async_read_object_stream import ( + _AsyncReadObjectStream, +) +from google.cloud.storage.asyncio.async_grpc_client import ( + AsyncGrpcClient, +) +from google.cloud.storage.asyncio.retry.bidi_stream_retry_manager import ( + _BidiStreamRetryManager, +) +from google.cloud.storage.asyncio.retry.reads_resumption_strategy import ( + _ReadResumptionStrategy, + _DownloadState, +) + +from io import BytesIO +from google.cloud import _storage_v2 +from google.cloud.storage._helpers import generate_random_56_bit_integer + +_MAX_READ_RANGES_PER_BIDI_READ_REQUEST = 100 +_BIDI_READ_REDIRECTED_TYPE_URL = ( + "type.googleapis.com/google.storage.v2.BidiReadObjectRedirectedError" +) + +logger = logging.getLogger(__name__) + + +def _is_read_retryable(exc): + """Predicate to determine if a read operation should be retried.""" + if isinstance( + exc, + ( + exceptions.InternalServerError, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + exceptions.TooManyRequests, + ), + ): + return True + + if not isinstance(exc, exceptions.Aborted) or not exc.errors: + return False + + try: + grpc_error = exc.errors[0] + trailers = grpc_error.trailing_metadata() + if not trailers: + return False + + status_details_bin = next( + (v for k, v in trailers if k == "grpc-status-details-bin"), None + ) + + if not status_details_bin: + return False + + status_proto = status_pb2.Status() + status_proto.ParseFromString(status_details_bin) + return any( + detail.type_url == _BIDI_READ_REDIRECTED_TYPE_URL + for detail in status_proto.details + ) + except Exception as e: + logger.error(f"Error parsing status_details_bin: {e}") + return False + + +class AsyncMultiRangeDownloader: + """Provides an interface for downloading multiple ranges of a GCS ``Object`` + concurrently. + + Example usage: + + .. code-block:: python + + client = AsyncGrpcClient() + mrd = await AsyncMultiRangeDownloader.create_mrd( + client, bucket_name="chandrasiri-rs", object_name="test_open9" + ) + my_buff1 = open('my_fav_file.txt', 'wb') + my_buff2 = BytesIO() + my_buff3 = BytesIO() + my_buff4 = any_object_which_provides_BytesIO_like_interface() + await mrd.download_ranges( + [ + # (start_byte, bytes_to_read, writeable_buffer) + (0, 100, my_buff1), + (100, 20, my_buff2), + (200, 123, my_buff3), + (300, 789, my_buff4), + ] + ) + + # verify data in buffers... + assert my_buff2.getbuffer().nbytes == 20 + + + """ + + @classmethod + async def create_mrd( + cls, + client: AsyncGrpcClient, + bucket_name: str, + object_name: str, + generation: Optional[int] = None, + read_handle: Optional[_storage_v2.BidiReadHandle] = None, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + **kwargs, + ) -> AsyncMultiRangeDownloader: + """Initializes a MultiRangeDownloader and opens the underlying bidi-gRPC + object for reading. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient` + :param client: The asynchronous client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the bucket containing the object. + + :type object_name: str + :param object_name: The name of the object to be read. + + :type generation: int + :param generation: (Optional) If present, selects a specific + revision of this object. + + :type read_handle: _storage_v2.BidiReadHandle + :param read_handle: (Optional) An existing handle for reading the object. + If provided, opening the bidi-gRPC connection will be faster. + + :type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry` + :param retry_policy: (Optional) The retry policy to use for the ``open`` operation. + + :type metadata: List[Tuple[str, str]] + :param metadata: (Optional) The metadata to be sent with the ``open`` request. + + :rtype: :class:`~google.cloud.storage.asyncio.async_multi_range_downloader.AsyncMultiRangeDownloader` + :returns: An initialized AsyncMultiRangeDownloader instance for reading. + """ + mrd = cls( + client, + bucket_name, + object_name, + generation=generation, + read_handle=read_handle, + **kwargs, + ) + await mrd.open(retry_policy=retry_policy, metadata=metadata) + return mrd + + def __init__( + self, + client: AsyncGrpcClient, + bucket_name: str, + object_name: str, + generation: Optional[int] = None, + read_handle: Optional[_storage_v2.BidiReadHandle] = None, + **kwargs, + ) -> None: + """Constructor for AsyncMultiRangeDownloader, clients are not adviced to + use it directly. Instead it's adviced to use the classmethod `create_mrd`. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient` + :param client: The asynchronous client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the bucket containing the object. + + :type object_name: str + :param object_name: The name of the object to be read. + + :type generation: int + :param generation: (Optional) If present, selects a specific revision of + this object. + + :type read_handle: _storage_v2.BidiReadHandle + :param read_handle: (Optional) An existing read handle. + """ + if "generation_number" in kwargs: + if generation is not None: + raise TypeError( + "Cannot set both 'generation' and 'generation_number'. " + "Use 'generation' for new code." + ) + logger.warning( + "'generation_number' is deprecated and will be removed in a future " + "major release. Please use 'generation' instead." + ) + generation = kwargs.pop("generation_number") + + raise_if_no_fast_crc32c() + + self.client = client + self.bucket_name = bucket_name + self.object_name = object_name + self.generation = generation + self.read_handle: Optional[_storage_v2.BidiReadHandle] = read_handle + self.read_obj_str: Optional[_AsyncReadObjectStream] = None + self._is_stream_open: bool = False + self._routing_token: Optional[str] = None + self._read_id_to_writable_buffer_dict = {} + self._read_id_to_download_ranges_id = {} + self._download_ranges_id_to_pending_read_ids = {} + self.persisted_size: Optional[int] = None # updated after opening the stream + self._open_retries: int = 0 + + async def __aenter__(self): + """Opens the underlying bidi-gRPC connection to read from the object.""" + await self.open() + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + """Closes the underlying bidi-gRPC connection.""" + if self.is_stream_open: + await self.close() + + def _on_open_error(self, exc): + """Extracts routing token and read handle on redirect error during open.""" + logger.warning(f"Error occurred while opening MRD: {exc}") + routing_token, read_handle = _handle_redirect(exc) + if routing_token: + self._routing_token = routing_token + if read_handle: + self.read_handle = read_handle + + async def open( + self, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Opens the bidi-gRPC connection to read from the object.""" + if self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is already open") + + if retry_policy is None: + def on_error_wrapper(exc): + self._open_retries += 1 + self._on_open_error(exc) + + retry_policy = AsyncRetry( + predicate=_is_read_retryable, on_error=on_error_wrapper + ) + else: + original_on_error = retry_policy._on_error + + def combined_on_error(exc): + self._open_retries += 1 + self._on_open_error(exc) + if original_on_error: + original_on_error(exc) + + retry_policy = AsyncRetry( + predicate=_is_read_retryable, + initial=retry_policy._initial, + maximum=retry_policy._maximum, + multiplier=retry_policy._multiplier, + deadline=retry_policy._deadline, + on_error=combined_on_error, + ) + + async def _do_open(): + current_metadata = list(metadata) if metadata else [] + + # Cleanup stream from previous failed attempt, if any. + if self.read_obj_str: + if self.read_obj_str.is_stream_open: + try: + await self.read_obj_str.close() + except exceptions.GoogleAPICallError as e: + logger.warning( + f"Failed to close existing stream during resumption: {e}" + ) + self.read_obj_str = None + self._is_stream_open = False + + self.read_obj_str = _AsyncReadObjectStream( + client=self.client.grpc_client, + bucket_name=self.bucket_name, + object_name=self.object_name, + generation_number=self.generation, + read_handle=self.read_handle, + ) + + if self._routing_token: + current_metadata.append( + ("x-goog-request-params", f"routing_token={self._routing_token}") + ) + self._routing_token = None + + await self.read_obj_str.open( + metadata=current_metadata if current_metadata else None + ) + + if self.read_obj_str.generation_number: + self.generation = self.read_obj_str.generation_number + if self.read_obj_str.read_handle: + self.read_handle = self.read_obj_str.read_handle + if self.read_obj_str.persisted_size is not None: + self.persisted_size = self.read_obj_str.persisted_size + + self._is_stream_open = True + + await retry_policy(_do_open)() + + async def download_ranges( + self, + read_ranges: List[Tuple[int, int, BytesIO]], + lock: asyncio.Lock = None, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Downloads multiple byte ranges from the object into the buffers + provided by user with automatic retries. + + :type read_ranges: List[Tuple[int, int, "BytesIO"]] + :param read_ranges: A list of tuples, where each tuple represents a + combination of byte_range and writeable buffer in format - + (`start_byte`, `bytes_to_read`, `writeable_buffer`). Buffer has + to be provided by the user, and user has to make sure appropriate + memory is available in the application to avoid out-of-memory crash. + + Special cases: + if the value of `bytes_to_read` is 0, it'll be interpreted as + download all contents until the end of the file from `start_byte`. + Examples: + * (0, 0, buffer) : downloads 0 to end , i.e. entire object. + * (100, 0, buffer) : downloads from 100 to end. + + + :type lock: asyncio.Lock + :param lock: (Optional) An asyncio lock to synchronize sends and recvs + on the underlying bidi-GRPC stream. This is required when multiple + coroutines are calling this method concurrently. + + i.e. Example usage with multiple coroutines: + + ``` + lock = asyncio.Lock() + task1 = asyncio.create_task(mrd.download_ranges(ranges1, lock)) + task2 = asyncio.create_task(mrd.download_ranges(ranges2, lock)) + await asyncio.gather(task1, task2) + + ``` + + If user want to call this method serially from multiple coroutines, + then providing a lock is not necessary. + + ``` + await mrd.download_ranges(ranges1) + await mrd.download_ranges(ranges2) + + # ... some other code code... + + ``` + + :type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry` + :param retry_policy: (Optional) The retry policy to use for the operation. + + :raises ValueError: if the underlying bidi-GRPC stream is not open. + :raises ValueError: if the length of read_ranges is more than 1000. + :raises DataCorruption: if a checksum mismatch is detected while reading data. + + """ + + if len(read_ranges) > 1000: + raise ValueError( + "Invalid input - length of read_ranges cannot be more than 1000" + ) + + if not self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is not open") + + if lock is None: + lock = asyncio.Lock() + + if retry_policy is None: + retry_policy = AsyncRetry(predicate=_is_read_retryable) + + # Initialize Global State for Retry Strategy + download_states = {} + for read_range in read_ranges: + read_id = generate_random_56_bit_integer() + download_states[read_id] = _DownloadState( + initial_offset=read_range[0], + initial_length=read_range[1], + user_buffer=read_range[2], + ) + + initial_state = { + "download_states": download_states, + "read_handle": self.read_handle, + "routing_token": None, + } + + # Track attempts to manage stream reuse + attempt_count = 0 + + def send_ranges_and_get_bytes( + requests: List[_storage_v2.ReadRange], + state: Dict[str, Any], + metadata: Optional[List[Tuple[str, str]]] = None, + ): + async def generator(): + nonlocal attempt_count + attempt_count += 1 + + if attempt_count > 1: + logger.info( + f"Resuming download (attempt {attempt_count}) for {len(requests)} ranges." + ) + + async with lock: + current_handle = state.get("read_handle") + current_token = state.get("routing_token") + + # We reopen if it's a redirect (token exists) OR if this is a retry + # (not first attempt). This prevents trying to send data on a dead + # stream from a previous failed attempt. + should_reopen = ( + (attempt_count > 1) + or (current_token is not None) + or (metadata is not None) + ) + + if should_reopen: + if current_token: + logger.info( + f"Re-opening stream with routing token: {current_token}" + ) + + self.read_obj_str = _AsyncReadObjectStream( + client=self.client.grpc_client, + bucket_name=self.bucket_name, + object_name=self.object_name, + generation_number=self.generation, + read_handle=current_handle, + ) + + # Inject routing_token into metadata if present + current_metadata = list(metadata) if metadata else [] + if current_token: + current_metadata.append( + ( + "x-goog-request-params", + f"routing_token={current_token}", + ) + ) + + await self.read_obj_str.open( + metadata=current_metadata if current_metadata else None + ) + self._is_stream_open = True + + pending_read_ids = {r.read_id for r in requests} + + # Send Requests + for i in range( + 0, len(requests), _MAX_READ_RANGES_PER_BIDI_READ_REQUEST + ): + batch = requests[i : i + _MAX_READ_RANGES_PER_BIDI_READ_REQUEST] + await self.read_obj_str.send( + _storage_v2.BidiReadObjectRequest(read_ranges=batch) + ) + + while pending_read_ids: + response = await self.read_obj_str.recv() + if response is None: + break + if response.object_data_ranges: + for data_range in response.object_data_ranges: + if data_range.range_end: + pending_read_ids.discard( + data_range.read_range.read_id + ) + yield response + + return generator() + + strategy = _ReadResumptionStrategy() + retry_manager = _BidiStreamRetryManager( + strategy, lambda r, s: send_ranges_and_get_bytes(r, s, metadata=metadata) + ) + + await retry_manager.execute(initial_state, retry_policy) + + if initial_state.get("read_handle"): + self.read_handle = initial_state["read_handle"] + + async def close(self): + """ + Closes the underlying bidi-gRPC connection. + """ + if not self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is not open") + + if self.read_obj_str: + await self.read_obj_str.close() + self.read_obj_str = None + self._is_stream_open = False + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_read_object_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_read_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..bde6c16518c11e88893f109ba2f8967c8e55664e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_read_object_stream.py @@ -0,0 +1,188 @@ +# 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 List, Optional, Tuple +from google.cloud import _storage_v2 +from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient +from google.cloud.storage.asyncio.async_abstract_object_stream import ( + _AsyncAbstractObjectStream, +) + +from google.api_core.bidi_async import AsyncBidiRpc + + +class _AsyncReadObjectStream(_AsyncAbstractObjectStream): + """Class representing a gRPC bidi-stream for reading data from a GCS ``Object``. + + This class provides a unix socket-like interface to a GCS ``Object``, with + methods like ``open``, ``close``, ``send``, and ``recv``. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient.grpc_client` + :param client: async grpc client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the GCS ``bucket`` containing the object. + + :type object_name: str + :param object_name: The name of the GCS ``object`` to be read. + + :type generation_number: int + :param generation_number: (Optional) If present, selects a specific revision of + this object. + + :type read_handle: _storage_v2.BidiReadHandle + :param read_handle: (Optional) An existing handle for reading the object. + If provided, opening the bidi-gRPC connection will be faster. + """ + + def __init__( + self, + client: AsyncGrpcClient.grpc_client, + bucket_name: str, + object_name: str, + generation_number: Optional[int] = None, + read_handle: Optional[_storage_v2.BidiReadHandle] = None, + ) -> None: + if client is None: + raise ValueError("client must be provided") + if bucket_name is None: + raise ValueError("bucket_name must be provided") + if object_name is None: + raise ValueError("object_name must be provided") + + super().__init__( + bucket_name=bucket_name, + object_name=object_name, + generation_number=generation_number, + ) + self.client: AsyncGrpcClient.grpc_client = client + self.read_handle: Optional[_storage_v2.BidiReadHandle] = read_handle + + self._full_bucket_name = f"projects/_/buckets/{self.bucket_name}" + + self.rpc = self.client._client._transport._wrapped_methods[ + self.client._client._transport.bidi_read_object + ] + self.metadata = (("x-goog-request-params", f"bucket={self._full_bucket_name}"),) + self.socket_like_rpc: Optional[AsyncBidiRpc] = None + self._is_stream_open: bool = False + self.persisted_size: Optional[int] = None + + async def open(self, metadata: Optional[List[Tuple[str, str]]] = None) -> None: + """Opens the bidi-gRPC connection to read from the object. + + This method sends an initial request to start the stream and receives + the first response containing metadata and a read handle. + + Args: + metadata (Optional[List[Tuple[str, str]]]): Additional metadata + to send with the initial stream request, e.g., for routing tokens. + """ + if self._is_stream_open: + raise ValueError("Stream is already open") + + read_handle = self.read_handle if self.read_handle else None + + read_object_spec = _storage_v2.BidiReadObjectSpec( + bucket=self._full_bucket_name, + object=self.object_name, + generation=self.generation_number if self.generation_number else None, + read_handle=read_handle, + ) + self.first_bidi_read_req = _storage_v2.BidiReadObjectRequest( + read_object_spec=read_object_spec + ) + + # Build the x-goog-request-params header + request_params = [f"bucket={self._full_bucket_name}"] + other_metadata = [] + if metadata: + for key, value in metadata: + if key == "x-goog-request-params": + request_params.append(value) + else: + other_metadata.append((key, value)) + + current_metadata = other_metadata + current_metadata.append(("x-goog-request-params", "&".join(request_params))) + + self.socket_like_rpc = AsyncBidiRpc( + self.rpc, + initial_request=self.first_bidi_read_req, + metadata=current_metadata, + ) + await self.socket_like_rpc.open() # this is actually 1 send + response = await self.socket_like_rpc.recv() + # populated only in the first response of bidi-stream and when opened + # without using `read_handle` + if hasattr(response, "metadata") and response.metadata: + if self.generation_number is None: + self.generation_number = response.metadata.generation + # update persisted size + self.persisted_size = response.metadata.size + + if response and response.read_handle: + self.read_handle = response.read_handle + + self._is_stream_open = True + + async def close(self) -> None: + """Closes the bidi-gRPC connection.""" + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.requests_done() + await self.socket_like_rpc.close() + self._is_stream_open = False + + async def requests_done(self): + """Signals that all requests have been sent.""" + + await self.socket_like_rpc.send(None) + await self.socket_like_rpc.recv() + + async def send( + self, bidi_read_object_request: _storage_v2.BidiReadObjectRequest + ) -> None: + """Sends a request message on the stream. + + Args: + bidi_read_object_request (:class:`~google.cloud._storage_v2.types.BidiReadObjectRequest`): + The request message to send. This is typically used to specify + the read offset and limit. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.socket_like_rpc.send(bidi_read_object_request) + + async def recv(self) -> _storage_v2.BidiReadObjectResponse: + """Receives a response from the stream. + + This method waits for the next message from the server, which could + contain object data or metadata. + + Returns: + :class:`~google.cloud._storage_v2.types.BidiReadObjectResponse`: + The response message from the server. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + response = await self.socket_like_rpc.recv() + # Update read_handle if present in response + if response and response.read_handle: + self.read_handle = response.read_handle + return response + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_write_object_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_write_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..4729cfd2020ee0c8f71788248808ba8726693e69 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/async_write_object_stream.py @@ -0,0 +1,239 @@ +# 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 List, Optional, Tuple +import grpc +from google.cloud import _storage_v2 +from google.cloud.storage.asyncio import _utils +from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient +from google.cloud.storage.asyncio.async_abstract_object_stream import ( + _AsyncAbstractObjectStream, +) +from google.api_core.bidi_async import AsyncBidiRpc + + +class _AsyncWriteObjectStream(_AsyncAbstractObjectStream): + """Class representing a gRPC bidi-stream for writing data from a GCS + ``Appendable Object``. + + This class provides a unix socket-like interface to a GCS ``Object``, with + methods like ``open``, ``close``, ``send``, and ``recv``. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient.grpc_client` + :param client: async grpc client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the GCS ``bucket`` containing the object. + + :type object_name: str + :param object_name: The name of the GCS ``Appendable Object`` to be write. + + :type generation_number: int + :param generation_number: (Optional) If present, creates writer for that + specific revision of that object. Use this to append data to an + existing Appendable Object. + + Setting to ``0`` makes the `writer.open()` succeed only if + object doesn't exist in the bucket (useful for not accidentally + overwriting existing objects). + + Warning: If `None`, a new object is created. If an object with the + same name already exists, it will be overwritten the moment + `writer.open()` is called. + + :type write_handle: _storage_v2.BidiWriteHandle + :param write_handle: (Optional) An existing handle for writing the object. + If provided, opening the bidi-gRPC connection will be faster. + """ + + def __init__( + self, + client: AsyncGrpcClient.grpc_client, + bucket_name: str, + object_name: str, + generation_number: Optional[int] = None, # None means new object + write_handle: Optional[_storage_v2.BidiWriteHandle] = None, + routing_token: Optional[str] = None, + ) -> None: + if client is None: + raise ValueError("client must be provided") + if bucket_name is None: + raise ValueError("bucket_name must be provided") + if object_name is None: + raise ValueError("object_name must be provided") + + super().__init__( + bucket_name=bucket_name, + object_name=object_name, + generation_number=generation_number, + ) + self.client: AsyncGrpcClient.grpc_client = client + self.write_handle: Optional[_storage_v2.BidiWriteHandle] = write_handle + self.routing_token: Optional[str] = routing_token + + self._full_bucket_name = f"projects/_/buckets/{self.bucket_name}" + + self.rpc = self.client._client._transport._wrapped_methods[ + self.client._client._transport.bidi_write_object + ] + + self.metadata = (("x-goog-request-params", f"bucket={self._full_bucket_name}"),) + self.socket_like_rpc: Optional[AsyncBidiRpc] = None + self._is_stream_open: bool = False + self.first_bidi_write_req = None + self.persisted_size = 0 + self.object_resource: Optional[_storage_v2.Object] = None + + async def open(self, metadata: Optional[List[Tuple[str, str]]] = None) -> None: + """ + Opens the bidi-gRPC connection to write to the object. + + This method sends an initial request to start the stream and receives + the first response containing metadata and a write handle. + + :rtype: None + :raises ValueError: If the stream is already open. + :raises google.api_core.exceptions.FailedPrecondition: + if `generation_number` is 0 and object already exists. + """ + if self._is_stream_open: + raise ValueError("Stream is already open") + + # Create a new object or overwrite existing one if generation_number + # is None. This makes it consistent with GCS JSON API behavior. + # Created object type would be Appendable Object. + # if `generation_number` == 0 new object will be created only if there + # isn't any existing object. + if self.generation_number is None or self.generation_number == 0: + self.first_bidi_write_req = _storage_v2.BidiWriteObjectRequest( + write_object_spec=_storage_v2.WriteObjectSpec( + resource=_storage_v2.Object( + name=self.object_name, bucket=self._full_bucket_name + ), + appendable=True, + if_generation_match=self.generation_number, + ), + ) + else: + self.first_bidi_write_req = _storage_v2.BidiWriteObjectRequest( + append_object_spec=_storage_v2.AppendObjectSpec( + bucket=self._full_bucket_name, + object=self.object_name, + generation=self.generation_number, + write_handle=self.write_handle if self.write_handle else None, + routing_token=self.routing_token if self.routing_token else None, + ), + ) + + request_param_values = [f"bucket={self._full_bucket_name}"] + final_metadata = [] + if metadata: + for key, value in metadata: + if key == "x-goog-request-params": + request_param_values.append(value) + else: + final_metadata.append((key, value)) + + final_metadata.append(("x-goog-request-params", "&".join(request_param_values))) + + self.socket_like_rpc = AsyncBidiRpc( + self.rpc, + initial_request=self.first_bidi_write_req, + metadata=final_metadata, + ) + + await self.socket_like_rpc.open() # this is actually 1 send + response = await self.socket_like_rpc.recv() + self._is_stream_open = True + + if response.persisted_size: + self.persisted_size = response.persisted_size + + if response.resource: + if not response.resource.size: + # Appending to a 0 byte appendable object. + self.persisted_size = 0 + else: + self.persisted_size = response.resource.size + + self.generation_number = response.resource.generation + + if response.write_handle: + self.write_handle = response.write_handle + + async def close(self) -> None: + """Closes the bidi-gRPC connection.""" + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.requests_done() + await self.socket_like_rpc.close() + self._is_stream_open = False + + async def requests_done(self): + """Signals that all requests have been sent.""" + await self.socket_like_rpc.send(None) + + # The server may send a final "EOF" response immediately, or it may + # first send an intermediate response followed by the EOF response depending on whether the object was finalized or not. + first_resp = await self.socket_like_rpc.recv() + _utils.update_write_handle_if_exists(self, first_resp) + + if first_resp != grpc.aio.EOF: + # this persisted_size will not be upto date., also what if response + # doesn't have persisted_size? , it'll throw error. + if hasattr(first_resp, "persisted_size"): + self.persisted_size = first_resp.persisted_size + second_resp = await self.socket_like_rpc.recv() + assert second_resp == grpc.aio.EOF + + async def send( + self, bidi_write_object_request: _storage_v2.BidiWriteObjectRequest + ) -> None: + """Sends a request message on the stream. + + Args: + bidi_write_object_request (:class:`~google.cloud._storage_v2.types.BidiReadObjectRequest`): + The request message to send. This is typically used to specify + the read offset and limit. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.socket_like_rpc.send(bidi_write_object_request) + + async def recv(self) -> _storage_v2.BidiWriteObjectResponse: + """Receives a response from the stream. + + This method waits for the next message from the server, which could + contain object data or metadata. + + Returns: + :class:`~google.cloud._storage_v2.types.BidiWriteObjectResponse`: + The response message from the server. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + response = await self.socket_like_rpc.recv() + # Update write_handle if present in response + if response: + if response.write_handle: + self.write_handle = response.write_handle + if response.persisted_size is not None: + self.persisted_size = response.persisted_size + if response.resource and response.resource.size: + self.persisted_size = response.resource.size + return response + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ad2462ecbc0300ed476f0dbaa319e07ecb25c4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/_helpers.py @@ -0,0 +1,125 @@ +# 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 + +import logging +from typing import Tuple, Optional + +from google.api_core import exceptions +from google.cloud._storage_v2.types import ( + BidiReadObjectRedirectedError, + BidiWriteObjectRedirectedError, +) +from google.rpc import status_pb2 + +_BIDI_READ_REDIRECTED_TYPE_URL = ( + "type.googleapis.com/google.storage.v2.BidiReadObjectRedirectedError" +) +_BIDI_WRITE_REDIRECTED_TYPE_URL = ( + "type.googleapis.com/google.storage.v2.BidiWriteObjectRedirectedError" +) +logger = logging.getLogger(__name__) + + +def _handle_redirect( + exc: Exception, +) -> Tuple[Optional[str], Optional[bytes]]: + """ + Extracts routing token and read handle from a gRPC error. + + :type exc: Exception + :param exc: The exception to parse. + + :rtype: Tuple[Optional[str], Optional[bytes]] + :returns: A tuple of (routing_token, read_handle). + """ + routing_token = None + read_handle = None + + grpc_error = None + if isinstance(exc, exceptions.Aborted) and exc.errors: + grpc_error = exc.errors[0] + + if grpc_error: + if isinstance(grpc_error, BidiReadObjectRedirectedError): + routing_token = grpc_error.routing_token + if grpc_error.read_handle: + read_handle = grpc_error.read_handle + return routing_token, read_handle + + if hasattr(grpc_error, "trailing_metadata"): + trailers = grpc_error.trailing_metadata() + if not trailers: + return None, None + + status_details_bin = None + for key, value in trailers: + if key == "grpc-status-details-bin": + status_details_bin = value + break + + if status_details_bin: + status_proto = status_pb2.Status() + try: + status_proto.ParseFromString(status_details_bin) + for detail in status_proto.details: + if detail.type_url == _BIDI_READ_REDIRECTED_TYPE_URL: + redirect_proto = BidiReadObjectRedirectedError.deserialize( + detail.value + ) + if redirect_proto.routing_token: + routing_token = redirect_proto.routing_token + if redirect_proto.read_handle: + read_handle = redirect_proto.read_handle + break + except Exception as e: + logger.error(f"Error unpacking redirect: {e}") + + return routing_token, read_handle + + +def _extract_bidi_writes_redirect_proto(exc: Exception): + grpc_error = None + if isinstance(exc, exceptions.Aborted) and exc.errors: + grpc_error = exc.errors[0] + + if grpc_error: + if isinstance(grpc_error, BidiWriteObjectRedirectedError): + return grpc_error + + if hasattr(grpc_error, "trailing_metadata"): + trailers = grpc_error.trailing_metadata() + if not trailers: + return + + status_details_bin = None + for key, value in trailers: + if key == "grpc-status-details-bin": + status_details_bin = value + break + + if status_details_bin: + status_proto = status_pb2.Status() + try: + status_proto.ParseFromString(status_details_bin) + for detail in status_proto.details: + if detail.type_url == _BIDI_WRITE_REDIRECTED_TYPE_URL: + redirect_proto = BidiWriteObjectRedirectedError.deserialize( + detail.value + ) + return redirect_proto + except Exception: + logger.error("Error unpacking redirect details from gRPC error.") + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/base_strategy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/base_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..ff193f109a0c83ae8ffc97068d6c687e7a0b4cde --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/base_strategy.py @@ -0,0 +1,83 @@ +# 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 Any, Iterable + + +class _BaseResumptionStrategy(abc.ABC): + """Abstract base class defining the interface for a bidi stream resumption strategy. + + This class defines the skeleton for a pluggable strategy that contains + all the service-specific logic for a given bidi operation (e.g., reads + or writes). This allows a generic retry manager to handle the common + retry loop while sending the state management and request generation + to a concrete implementation of this class. + """ + + @abc.abstractmethod + def generate_requests(self, state: Any) -> Iterable[Any]: + """Generates the next batch of requests based on the current state. + + This method is called at the beginning of each retry attempt. It should + inspect the provided state object and generate the appropriate list of + request protos to send to the server. For example, a read strategy + would use this to implement "Smarter Resumption" by creating smaller + `ReadRange` requests for partially downloaded ranges. For bidi-writes, + it will set the `write_offset` field to the persisted size received + from the server in the next request. + + :type state: Any + :param state: An object containing all the state needed for the + operation (e.g., requested ranges, user buffers, + bytes written). + """ + pass + + @abc.abstractmethod + def update_state_from_response(self, response: Any, state: Any) -> None: + """Updates the state based on a successful server response. + + This method is called for every message received from the server. It is + responsible for processing the response and updating the shared state + object. + + :type response: Any + :param response: The response message received from the server. + + :type state: Any + :param state: The shared state object for the operation, which will be + mutated by this method. + """ + pass + + @abc.abstractmethod + async def recover_state_on_failure(self, error: Exception, state: Any) -> None: + """Prepares the state for the next retry attempt after a failure. + + This method is called when a retriable gRPC error occurs. It is + responsible for performing any necessary actions to ensure the next + retry attempt can succeed. For bidi reads, its primary role is to + handle the `BidiReadObjectRedirectError` by extracting the + `routing_token` and updating the state. For bidi writes, it will update + the state to reflect any bytes that were successfully persisted before + the failure. + + :type error: :class:`Exception` + :param error: The exception that was caught by the retry engine. + + :type state: Any + :param state: The shared state object for the operation. + """ + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/bidi_stream_retry_manager.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/bidi_stream_retry_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..947ee74c118363ca970f90a661c38e81b68e7acb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/bidi_stream_retry_manager.py @@ -0,0 +1,69 @@ +# 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 logging +from typing import Any, AsyncIterator, Callable + +from google.cloud.storage.asyncio.retry.base_strategy import ( + _BaseResumptionStrategy, +) + +logger = logging.getLogger(__name__) + + +class _BidiStreamRetryManager: + """Manages the generic retry loop for a bidi streaming operation.""" + + def __init__( + self, + strategy: _BaseResumptionStrategy, + send_and_recv: Callable[..., AsyncIterator[Any]], + ): + """Initializes the retry manager. + Args: + strategy: The strategy for managing the state of a specific + bidi operation (e.g., reads or writes). + send_and_recv: An async callable that opens a new gRPC stream. + """ + self._strategy = strategy + self._send_and_recv = send_and_recv + + async def execute(self, initial_state: Any, retry_policy): + """ + Executes the bidi operation with the configured retry policy. + Args: + initial_state: An object containing all state for the operation. + retry_policy: The `google.api_core.retry.AsyncRetry` object to + govern the retry behavior for this specific operation. + """ + state = initial_state + + async def attempt(): + requests = self._strategy.generate_requests(state) + stream = self._send_and_recv(requests, state) + try: + async for response in stream: + self._strategy.update_state_from_response(response, state) + return + except Exception as e: + if retry_policy._predicate(e): + logger.warning( + f"Bidi stream operation failed: {e}. Attempting state recovery and retry." + ) + await self._strategy.recover_state_on_failure(e, state) + raise e + + wrapped_attempt = retry_policy(attempt) + + await wrapped_attempt() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/reads_resumption_strategy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/reads_resumption_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..e7003c105a63bdd9c6ed4cd6ceebbcadbb22350a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/reads_resumption_strategy.py @@ -0,0 +1,163 @@ +# 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, Dict, List, IO +import logging + +from google_crc32c import Checksum +from google.cloud import _storage_v2 as storage_v2 +from google.cloud.storage.exceptions import DataCorruption +from google.cloud.storage.asyncio.retry._helpers import ( + _handle_redirect, +) +from google.cloud.storage.asyncio.retry.base_strategy import ( + _BaseResumptionStrategy, +) + + +_BIDI_READ_REDIRECTED_TYPE_URL = ( + "type.googleapis.com/google.storage.v2.BidiReadObjectRedirectedError" +) +logger = logging.getLogger(__name__) + + +class _DownloadState: + """A helper class to track the state of a single range download.""" + + def __init__( + self, initial_offset: int, initial_length: int, user_buffer: IO[bytes] + ): + self.initial_offset = initial_offset + self.initial_length = initial_length + self.user_buffer = user_buffer + self.bytes_written = 0 + self.next_expected_offset = initial_offset + self.is_complete = False + + +class _ReadResumptionStrategy(_BaseResumptionStrategy): + """The concrete resumption strategy for bidi reads.""" + + def generate_requests(self, state: Dict[str, Any]) -> List[storage_v2.ReadRange]: + """Generates new ReadRange requests for all incomplete downloads. + + :type state: dict + :param state: A dictionary mapping a read_id to its corresponding + _DownloadState object. + """ + pending_requests = [] + download_states: Dict[int, _DownloadState] = state["download_states"] + + for read_id, read_state in download_states.items(): + if not read_state.is_complete: + new_offset = read_state.initial_offset + read_state.bytes_written + + # Calculate remaining length. If initial_length is 0 (read to end), + # it stays 0. Otherwise, subtract bytes_written. + new_length = 0 + if read_state.initial_length > 0: + new_length = read_state.initial_length - read_state.bytes_written + + new_request = storage_v2.ReadRange( + read_offset=new_offset, + read_length=new_length, + read_id=read_id, + ) + pending_requests.append(new_request) + return pending_requests + + def update_state_from_response( + self, response: storage_v2.BidiReadObjectResponse, state: Dict[str, Any] + ) -> None: + """Processes a server response, performs integrity checks, and updates state.""" + proto = getattr(response, "_pb", response) + + # Capture read_handle if provided. + if proto.HasField("read_handle"): + state["read_handle"] = storage_v2.BidiReadHandle( + handle=proto.read_handle.handle + ) + + download_states = state["download_states"] + + for object_data_range in proto.object_data_ranges: + # Ignore empty ranges or ranges for IDs not in our state + # (e.g., from a previously cancelled request on the same stream). + if not object_data_range.HasField("read_range"): + logger.warning( + "Received response with missing read_range field; ignoring." + ) + continue + + read_range_pb = object_data_range.read_range + read_id = read_range_pb.read_id + + if read_id not in download_states: + logger.warning( + f"Received data for unknown or stale read_id {read_id}; ignoring." + ) + continue + + read_state = download_states[read_id] + + # Offset Verification + # We must validate data before updating state or writing to buffer. + chunk_offset = read_range_pb.read_offset + if chunk_offset != read_state.next_expected_offset: + raise DataCorruption( + response, + f"Offset mismatch for read_id {read_id}. " + f"Expected {read_state.next_expected_offset}, got {chunk_offset}", + ) + + # Checksum Verification + checksummed_data = object_data_range.checksummed_data + data = checksummed_data.content + + if checksummed_data.HasField("crc32c"): + server_checksum = checksummed_data.crc32c + client_checksum = int.from_bytes(Checksum(data).digest(), "big") + if server_checksum != client_checksum: + raise DataCorruption( + response, + f"Checksum mismatch for read_id {read_id}. " + f"Server sent {server_checksum}, client calculated {client_checksum}.", + ) + + # Update State & Write Data + chunk_size = len(data) + read_state.user_buffer.write(data) + read_state.bytes_written += chunk_size + read_state.next_expected_offset += chunk_size + + # Final Byte Count Verification + if object_data_range.range_end: + read_state.is_complete = True + if ( + read_state.initial_length != 0 + and read_state.bytes_written > read_state.initial_length + ): + raise DataCorruption( + response, + f"Byte count mismatch for read_id {read_id}. " + f"Expected {read_state.initial_length}, got {read_state.bytes_written}", + ) + + async def recover_state_on_failure(self, error: Exception, state: Any) -> None: + """Handles BidiReadObjectRedirectedError for reads.""" + routing_token, read_handle = _handle_redirect(error) + if routing_token: + state["routing_token"] = routing_token + if read_handle: + state["read_handle"] = read_handle diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/writes_resumption_strategy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/writes_resumption_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dcd1e17e2d556d55245cb9297baa8b0bd83c44 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/asyncio/retry/writes_resumption_strategy.py @@ -0,0 +1,152 @@ +# 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, Dict, IO, List, Optional, Union + +import google_crc32c +from google.cloud._storage_v2.types import storage as storage_type +from google.cloud._storage_v2.types.storage import BidiWriteObjectRedirectedError +from google.cloud.storage.asyncio.retry.base_strategy import ( + _BaseResumptionStrategy, +) +from google.cloud.storage.asyncio.retry._helpers import ( + _extract_bidi_writes_redirect_proto, +) + + +class _WriteState: + """A helper class to track the state of a single upload operation. + + :type chunk_size: int + :param chunk_size: The size of chunks to write to the server. + + :type user_buffer: IO[bytes] + :param user_buffer: The data source. + + :type flush_interval: int + :param flush_interval: The flush interval at which the data is flushed. + """ + + def __init__( + self, + chunk_size: int, + user_buffer: IO[bytes], + flush_interval: int, + ): + self.chunk_size = chunk_size + self.user_buffer = user_buffer + self.persisted_size: int = 0 + # Bytes sent to the server (it may be unpersisted), + # i.e. latest object size = persisted_size + some more bytes. + # Please note: these bytes are sent from client to server, server might have also received it. + # but might not have persisted it yet (may be in memory buffer on server side). + # This variable is same as `offset variable` in the instance of `AppendableObjectWriter`. + self.bytes_sent: int = 0 + self.bytes_since_last_flush: int = 0 + self.flush_interval: int = flush_interval + self.write_handle: Union[bytes, storage_type.BidiWriteHandle, None] = None + self.routing_token: Optional[str] = None + self.is_finalized: bool = False + + +class _WriteResumptionStrategy(_BaseResumptionStrategy): + """The concrete resumption strategy for bidi writes.""" + + def generate_requests( + self, state: Dict[str, Any] + ) -> List[storage_type.BidiWriteObjectRequest]: + """Generates BidiWriteObjectRequests to resume or continue the upload. + + This method is not applicable for `open` methods. + """ + write_state: _WriteState = state["write_state"] + + requests = [] + # The buffer should already be seeked to the correct position (persisted_size) + # by the `recover_state_on_failure` method before this is called. + while not write_state.is_finalized: + chunk = write_state.user_buffer.read(write_state.chunk_size) + + # End of File detection + if not chunk: + break + + checksummed_data = storage_type.ChecksummedData(content=chunk) + checksum = google_crc32c.Checksum(chunk) + checksummed_data.crc32c = int.from_bytes(checksum.digest(), "big") + + request = storage_type.BidiWriteObjectRequest( + write_offset=write_state.bytes_sent, + checksummed_data=checksummed_data, + ) + chunk_len = len(chunk) + write_state.bytes_sent += chunk_len + write_state.bytes_since_last_flush += chunk_len + + if write_state.bytes_since_last_flush >= write_state.flush_interval: + request.flush = True + request.state_lookup = True + write_state.bytes_since_last_flush = 0 + + requests.append(request) + return requests + + def update_state_from_response( + self, response: storage_type.BidiWriteObjectResponse, state: Dict[str, Any] + ) -> None: + """Processes a server response and updates the write state.""" + write_state: _WriteState = state["write_state"] + if response is None: + return + if response.persisted_size: + write_state.persisted_size = response.persisted_size + + if response.write_handle: + write_state.write_handle = response.write_handle + + if response.resource: + write_state.persisted_size = response.resource.size + if response.resource.finalize_time: + write_state.is_finalized = True + + async def recover_state_on_failure( + self, error: Exception, state: Dict[str, Any] + ) -> None: + """ + Handles errors, specifically BidiWriteObjectRedirectedError, and rewinds state. + + This method rewinds the user buffer and internal byte tracking to the + last confirmed 'persisted_size' from the server. + """ + write_state: _WriteState = state["write_state"] + + redirect_proto = None + + if isinstance(error, BidiWriteObjectRedirectedError): + redirect_proto = error + else: + redirect_proto = _extract_bidi_writes_redirect_proto(error) + + # Extract routing token and potentially a new write handle for redirection. + if redirect_proto: + if redirect_proto.routing_token: + write_state.routing_token = redirect_proto.routing_token + if redirect_proto.write_handle: + write_state.write_handle = redirect_proto.write_handle + + # We must assume any data sent beyond 'persisted_size' was lost. + # Reset the user buffer to the last known good byte confirmed by the server. + write_state.user_buffer.seek(write_state.persisted_size) + write_state.bytes_sent = write_state.persisted_size + write_state.bytes_since_last_flush = 0 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/batch.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..03a27fc23e11b83ca94697145cf4e98abf9c8e96 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/batch.py @@ -0,0 +1,386 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Batch updates / deletes of storage buckets / blobs. + +A batch request is a single standard HTTP request containing multiple Cloud Storage JSON API calls. +Within this main HTTP request, there are multiple parts which each contain a nested HTTP request. +The body of each part is itself a complete HTTP request, with its own verb, URL, headers, and body. + +Note that Cloud Storage does not support batch operations for uploading or downloading. +Additionally, the current batch design does not support library methods whose return values +depend on the response payload. See more details in the [Sending Batch Requests official guide](https://cloud.google.com/storage/docs/batch). + +Examples of situations when you might want to use the Batch module: +``blob.patch()`` +``blob.update()`` +``blob.delete()`` +``bucket.delete_blob()`` +``bucket.patch()`` +``bucket.update()`` +""" +from email.encoders import encode_noop +from email.generator import Generator +from email.mime.application import MIMEApplication +from email.mime.multipart import MIMEMultipart +from email.parser import Parser +import io +import json + +import requests + +from google.cloud import _helpers +from google.cloud import exceptions +from google.cloud.storage._http import Connection +from google.cloud.storage.constants import _DEFAULT_TIMEOUT + + +class MIMEApplicationHTTP(MIMEApplication): + """MIME type for ``application/http``. + + Constructs payload from headers and body + + :type method: str + :param method: HTTP method + + :type uri: str + :param uri: URI for HTTP request + + :type headers: dict + :param headers: HTTP headers + + :type body: str + :param body: (Optional) HTTP payload + + """ + + def __init__(self, method, uri, headers, body): + if isinstance(body, dict): + body = json.dumps(body) + headers["Content-Type"] = "application/json" + headers["Content-Length"] = len(body) + if body is None: + body = "" + lines = [f"{method} {uri} HTTP/1.1"] + lines.extend([f"{key}: {value}" for key, value in sorted(headers.items())]) + lines.append("") + lines.append(body) + payload = "\r\n".join(lines) + super().__init__(payload, "http", encode_noop) + + +class _FutureDict(object): + """Class to hold a future value for a deferred request. + + Used by for requests that get sent in a :class:`Batch`. + """ + + @staticmethod + def get(key, default=None): + """Stand-in for dict.get. + + :type key: object + :param key: Hashable dictionary key. + + :type default: object + :param default: Fallback value to dict.get. + + :raises: :class:`KeyError` always since the future is intended to fail + as a dictionary. + """ + raise KeyError(f"Cannot get({key!r}, default={default!r}) on a future") + + def __getitem__(self, key): + """Stand-in for dict[key]. + + :type key: object + :param key: Hashable dictionary key. + + :raises: :class:`KeyError` always since the future is intended to fail + as a dictionary. + """ + raise KeyError(f"Cannot get item {key!r} from a future") + + def __setitem__(self, key, value): + """Stand-in for dict[key] = value. + + :type key: object + :param key: Hashable dictionary key. + + :type value: object + :param value: Dictionary value. + + :raises: :class:`KeyError` always since the future is intended to fail + as a dictionary. + """ + raise KeyError(f"Cannot set {key!r} -> {value!r} on a future") + + +class _FutureResponse(requests.Response): + """Reponse that returns a placeholder dictionary for a batched requests.""" + + def __init__(self, future_dict): + super(_FutureResponse, self).__init__() + self._future_dict = future_dict + self.status_code = 204 + + def json(self): + return self._future_dict + + @property + def content(self): + return self._future_dict + + +class Batch(Connection): + """Proxy an underlying connection, batching up change operations. + + .. warning:: + + Cloud Storage does not support batch operations for uploading or downloading. + Additionally, the current batch design does not support library methods whose + return values depend on the response payload. + + :type client: :class:`google.cloud.storage.client.Client` + :param client: The client to use for making connections. + + :type raise_exception: bool + :param raise_exception: + (Optional) Defaults to True. If True, instead of adding exceptions + to the list of return responses, the final exception will be raised. + Note that exceptions are unwrapped after all operations are complete + in success or failure, and only the last exception is raised. + """ + + _MAX_BATCH_SIZE = 1000 + + def __init__(self, client, raise_exception=True): + api_endpoint = client._connection.API_BASE_URL + client_info = client._connection._client_info + super(Batch, self).__init__( + client, client_info=client_info, api_endpoint=api_endpoint + ) + self._requests = [] + self._target_objects = [] + self._responses = [] + self._raise_exception = raise_exception + + def _do_request( + self, method, url, headers, data, target_object, timeout=_DEFAULT_TIMEOUT + ): + """Override Connection: defer actual HTTP request. + + Only allow up to ``_MAX_BATCH_SIZE`` requests to be deferred. + + :type method: str + :param method: The HTTP method to use in the request. + + :type url: str + :param url: The URL to send the request to. + + :type headers: dict + :param headers: A dictionary of HTTP headers to send with the request. + + :type data: str + :param data: The data to send as the body of the request. + + :type target_object: object + :param target_object: + (Optional) This allows us to enable custom behavior in our batch + connection. Here we defer an HTTP request and complete + initialization of the object at a later time. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :rtype: tuple of ``response`` (a dictionary of sorts) + and ``content`` (a string). + :returns: The HTTP response object and the content of the response. + """ + if len(self._requests) >= self._MAX_BATCH_SIZE: + raise ValueError( + "Too many deferred requests (max %d)" % self._MAX_BATCH_SIZE + ) + self._requests.append((method, url, headers, data, timeout)) + result = _FutureDict() + self._target_objects.append(target_object) + if target_object is not None: + target_object._properties = result + return _FutureResponse(result) + + def _prepare_batch_request(self): + """Prepares headers and body for a batch request. + + :rtype: tuple (dict, str) + :returns: The pair of headers and body of the batch request to be sent. + :raises: :class:`ValueError` if no requests have been deferred. + """ + if len(self._requests) == 0: + raise ValueError("No deferred requests") + + multi = MIMEMultipart() + + # Use timeout of last request, default to _DEFAULT_TIMEOUT + timeout = _DEFAULT_TIMEOUT + for method, uri, headers, body, _timeout in self._requests: + subrequest = MIMEApplicationHTTP(method, uri, headers, body) + multi.attach(subrequest) + timeout = _timeout + + buf = io.StringIO() + generator = Generator(buf, False, 0) + generator.flatten(multi) + payload = buf.getvalue() + + # Strip off redundant header text + _, body = payload.split("\n\n", 1) + return dict(multi._headers), body, timeout + + def _finish_futures(self, responses, raise_exception=True): + """Apply all the batch responses to the futures created. + + :type responses: list of (headers, payload) tuples. + :param responses: List of headers and payloads from each response in + the batch. + + :type raise_exception: bool + :param raise_exception: + (Optional) Defaults to True. If True, instead of adding exceptions + to the list of return responses, the final exception will be raised. + Note that exceptions are unwrapped after all operations are complete + in success or failure, and only the last exception is raised. + + :raises: :class:`ValueError` if no requests have been deferred. + """ + # If a bad status occurs, we track it, but don't raise an exception + # until all futures have been populated. + # If raise_exception=False, we add exceptions to the list of responses. + exception_args = None + + if len(self._target_objects) != len(responses): # pragma: NO COVER + raise ValueError("Expected a response for every request.") + + for target_object, subresponse in zip(self._target_objects, responses): + # For backwards compatibility, only the final exception will be raised. + # Set raise_exception=False to include all exceptions to the list of return responses. + if not 200 <= subresponse.status_code < 300 and raise_exception: + exception_args = exception_args or subresponse + elif target_object is not None: + try: + target_object._properties = subresponse.json() + except ValueError: + target_object._properties = subresponse.content + + if exception_args is not None: + raise exceptions.from_http_response(exception_args) + + def finish(self, raise_exception=True): + """Submit a single `multipart/mixed` request with deferred requests. + + :type raise_exception: bool + :param raise_exception: + (Optional) Defaults to True. If True, instead of adding exceptions + to the list of return responses, the final exception will be raised. + Note that exceptions are unwrapped after all operations are complete + in success or failure, and only the last exception is raised. + + :rtype: list of tuples + :returns: one ``(headers, payload)`` tuple per deferred request. + """ + headers, body, timeout = self._prepare_batch_request() + + url = f"{self.API_BASE_URL}/batch/storage/v1" + + # Use the private ``_base_connection`` rather than the property + # ``_connection``, since the property may be this + # current batch. + response = self._client._base_connection._make_request( + "POST", url, data=body, headers=headers, timeout=timeout + ) + + # Raise exception if the top-level batch request fails + if not 200 <= response.status_code < 300: + raise exceptions.from_http_response(response) + + responses = list(_unpack_batch_response(response)) + self._finish_futures(responses, raise_exception=raise_exception) + self._responses = responses + return responses + + def current(self): + """Return the topmost batch, or None.""" + return self._client.current_batch + + def __enter__(self): + self._client._push_batch(self) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + try: + if exc_type is None: + self.finish(raise_exception=self._raise_exception) + finally: + self._client._pop_batch() + + +def _generate_faux_mime_message(parser, response): + """Convert response, content -> (multipart) email.message. + + Helper for _unpack_batch_response. + """ + # We coerce to bytes to get consistent concat across + # Py2 and Py3. Percent formatting is insufficient since + # it includes the b in Py3. + content_type = _helpers._to_bytes(response.headers.get("content-type", "")) + + faux_message = b"".join( + [b"Content-Type: ", content_type, b"\nMIME-Version: 1.0\n\n", response.content] + ) + + return parser.parsestr(faux_message.decode("utf-8")) + + +def _unpack_batch_response(response): + """Convert requests.Response -> [(headers, payload)]. + + Creates a generator of tuples of emulating the responses to + :meth:`requests.Session.request`. + + :type response: :class:`requests.Response` + :param response: HTTP response / headers from a request. + """ + parser = Parser() + message = _generate_faux_mime_message(parser, response) + + if not isinstance(message._payload, list): # pragma: NO COVER + raise ValueError("Bad response: not multi-part") + + for subrequest in message._payload: + status_line, rest = subrequest._payload.split("\n", 1) + _, status, _ = status_line.split(" ", 2) + sub_message = parser.parsestr(rest) + payload = sub_message._payload + msg_headers = dict(sub_message._headers) + content_id = msg_headers.get("Content-ID") + + subresponse = requests.Response() + subresponse.request = requests.Request( + method="BATCH", url=f"contentid://{content_id}" + ).prepare() + subresponse.status_code = int(status) + subresponse.headers.update(msg_headers) + subresponse._content = payload.encode("utf-8") + + yield subresponse diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/blob.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/blob.py new file mode 100644 index 0000000000000000000000000000000000000000..0b022985fc321a9e385e1c06475fa4d3d8c37cd1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/blob.py @@ -0,0 +1,5302 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pylint: disable=too-many-lines + +"""Create / interact with Google Cloud Storage blobs.""" + +import base64 +import copy +import hashlib +from io import BytesIO +from io import TextIOWrapper +import logging +import mimetypes +import os +import re +from email.parser import HeaderParser +from urllib.parse import parse_qsl +from urllib.parse import quote +from urllib.parse import urlencode +from urllib.parse import urlsplit +from urllib.parse import urlunsplit +import warnings + +from google.cloud.storage._media.requests import ChunkedDownload +from google.cloud.storage._media.requests import Download +from google.cloud.storage._media.requests import RawDownload +from google.cloud.storage._media.requests import RawChunkedDownload +from google.cloud.storage._media.requests import MultipartUpload +from google.cloud.storage._media.requests import ResumableUpload + +from google.api_core.iam import Policy +from google.cloud import exceptions +from google.cloud._helpers import _bytes_to_unicode +from google.cloud._helpers import _datetime_to_rfc3339 +from google.cloud._helpers import _rfc3339_nanos_to_datetime +from google.cloud._helpers import _to_bytes +from google.cloud.exceptions import NotFound +from google.cloud.storage._opentelemetry_tracing import ( + _get_opentelemetry_attributes_from_url, +) +from google.cloud.storage._helpers import _add_etag_match_headers +from google.cloud.storage._helpers import _add_generation_match_parameters +from google.cloud.storage._helpers import _PropertyMixin +from google.cloud.storage._helpers import _scalar_property +from google.cloud.storage._helpers import _bucket_bound_hostname_url +from google.cloud.storage._helpers import _raise_if_more_than_one_set +from google.cloud.storage._helpers import _get_default_headers +from google.cloud.storage._helpers import _get_default_storage_base_url +from google.cloud.storage._signing import generate_signed_url_v2 +from google.cloud.storage._signing import generate_signed_url_v4 +from google.cloud.storage._helpers import _API_VERSION +from google.cloud.storage._helpers import _virtual_hosted_style_base_url +from google.cloud.storage._opentelemetry_tracing import create_trace_span +from google.cloud.storage.acl import ACL +from google.cloud.storage.acl import ObjectACL +from google.cloud.storage.constants import _DEFAULT_TIMEOUT +from google.cloud.storage.constants import ARCHIVE_STORAGE_CLASS +from google.cloud.storage.constants import COLDLINE_STORAGE_CLASS +from google.cloud.storage.constants import MULTI_REGIONAL_LEGACY_STORAGE_CLASS +from google.cloud.storage.constants import NEARLINE_STORAGE_CLASS +from google.cloud.storage.constants import REGIONAL_LEGACY_STORAGE_CLASS +from google.cloud.storage.constants import STANDARD_STORAGE_CLASS +from google.cloud.storage.exceptions import DataCorruption +from google.cloud.storage.exceptions import InvalidResponse +from google.cloud.storage.retry import ConditionalRetryPolicy +from google.cloud.storage.retry import DEFAULT_RETRY +from google.cloud.storage.retry import DEFAULT_RETRY_IF_ETAG_IN_JSON +from google.cloud.storage.retry import DEFAULT_RETRY_IF_GENERATION_SPECIFIED +from google.cloud.storage.fileio import BlobReader +from google.cloud.storage.fileio import BlobWriter + + +_DEFAULT_CONTENT_TYPE = "application/octet-stream" +_DOWNLOAD_URL_TEMPLATE = "{hostname}/download/storage/{api_version}{path}?alt=media" +_BASE_UPLOAD_TEMPLATE = ( + "{hostname}/upload/storage/{api_version}{bucket_path}/o?uploadType=" +) +_MULTIPART_URL_TEMPLATE = _BASE_UPLOAD_TEMPLATE + "multipart" +_RESUMABLE_URL_TEMPLATE = _BASE_UPLOAD_TEMPLATE + "resumable" +# NOTE: "acl" is also writeable but we defer ACL management to +# the classes in the google.cloud.storage.acl module. +_CONTENT_TYPE_FIELD = "contentType" +_WRITABLE_FIELDS = ( + "cacheControl", + "contentDisposition", + "contentEncoding", + "contentLanguage", + _CONTENT_TYPE_FIELD, + "crc32c", + "customTime", + "md5Hash", + "metadata", + "name", + "retention", + "storageClass", +) +_READ_LESS_THAN_SIZE = ( + "Size {:d} was specified but the file-like object only had " "{:d} bytes remaining." +) +_CHUNKED_DOWNLOAD_CHECKSUM_MESSAGE = ( + "A checksum of type `{}` was requested, but checksumming is not available " + "for downloads when chunk_size is set." +) +_COMPOSE_IF_GENERATION_LIST_DEPRECATED = ( + "'if_generation_match: type list' is deprecated and supported for " + "backwards-compatability reasons only. Use 'if_source_generation_match' " + "instead' to match source objects' generations." +) +_COMPOSE_IF_GENERATION_LIST_AND_IF_SOURCE_GENERATION_ERROR = ( + "Use 'if_generation_match' to match the generation of the destination " + "object by passing in a generation number, instead of a list. " + "Use 'if_source_generation_match' to match source objects generations." +) +_COMPOSE_IF_METAGENERATION_LIST_DEPRECATED = ( + "'if_metageneration_match: type list' is deprecated and supported for " + "backwards-compatability reasons only. Note that the metageneration to " + "be matched is that of the destination blob. Please pass in a single " + "value (type long)." +) +_COMPOSE_IF_SOURCE_GENERATION_MISMATCH_ERROR = ( + "'if_source_generation_match' length must be the same as 'sources' length" +) +_DOWNLOAD_AS_STRING_DEPRECATED = ( + "Blob.download_as_string() is deprecated and will be removed in future. " + "Use Blob.download_as_bytes() instead." +) +_FROM_STRING_DEPRECATED = ( + "Blob.from_string() is deprecated and will be removed in future. " + "Use Blob.from_uri() instead." +) +_GS_URL_REGEX_PATTERN = re.compile( + r"(?Pgs)://(?P[a-z0-9_.-]+)/(?P.+)" +) + +_DEFAULT_CHUNKSIZE = 104857600 # 1024 * 1024 B * 100 = 100 MiB +_MAX_MULTIPART_SIZE = 8388608 # 8 MiB + +_logger = logging.getLogger(__name__) + + +class Blob(_PropertyMixin): + """A wrapper around Cloud Storage's concept of an ``Object``. + + :type name: str + :param name: The name of the blob. This corresponds to the unique path of + the object in the bucket. If bytes, will be converted to a + unicode object. Blob / object names can contain any sequence + of valid unicode characters, of length 1-1024 bytes when + UTF-8 encoded. + + :type bucket: :class:`google.cloud.storage.bucket.Bucket` + :param bucket: The bucket to which this blob belongs. + + :type chunk_size: int + :param chunk_size: + (Optional) The size of a chunk of data whenever iterating (in bytes). + This must be a multiple of 256 KB per the API specification. If not + specified, the chunk_size of the blob itself is used. If that is not + specified, a default value of 40 MB is used. + + :type encryption_key: bytes + :param encryption_key: + (Optional) 32 byte encryption key for customer-supplied encryption. + See https://cloud.google.com/storage/docs/encryption#customer-supplied. + + :type kms_key_name: str + :param kms_key_name: + (Optional) Resource name of Cloud KMS key used to encrypt the blob's + contents. + + :type generation: long + :param generation: + (Optional) If present, selects a specific revision of this object. + """ + + _chunk_size = None # Default value for each instance. + _CHUNK_SIZE_MULTIPLE = 256 * 1024 + """Number (256 KB, in bytes) that must divide the chunk size.""" + + STORAGE_CLASSES = ( + STANDARD_STORAGE_CLASS, + NEARLINE_STORAGE_CLASS, + COLDLINE_STORAGE_CLASS, + ARCHIVE_STORAGE_CLASS, + MULTI_REGIONAL_LEGACY_STORAGE_CLASS, + REGIONAL_LEGACY_STORAGE_CLASS, + ) + """Allowed values for :attr:`storage_class`. + + See + https://cloud.google.com/storage/docs/json_api/v1/objects#storageClass + https://cloud.google.com/storage/docs/per-object-storage-class + + .. note:: + This list does not include 'DURABLE_REDUCED_AVAILABILITY', which + is only documented for buckets (and deprecated). + """ + + def __init__( + self, + name, + bucket, + chunk_size=None, + encryption_key=None, + kms_key_name=None, + generation=None, + ): + """ + property :attr:`name` + Get the blob's name. + """ + name = _bytes_to_unicode(name) + super(Blob, self).__init__(name=name) + + self.chunk_size = chunk_size # Check that setter accepts value. + self._bucket = bucket + self._acl = ObjectACL(self) + _raise_if_more_than_one_set( + encryption_key=encryption_key, kms_key_name=kms_key_name + ) + + self._encryption_key = encryption_key + + if kms_key_name is not None: + self._properties["kmsKeyName"] = kms_key_name + + if generation is not None: + self._properties["generation"] = generation + + @property + def bucket(self): + """Bucket which contains the object. + + :rtype: :class:`~google.cloud.storage.bucket.Bucket` + :returns: The object's bucket. + """ + return self._bucket + + @property + def chunk_size(self): + """Get the blob's default chunk size. + + :rtype: int or ``NoneType`` + :returns: The current blob's chunk size, if it is set. + """ + return self._chunk_size + + @chunk_size.setter + def chunk_size(self, value): + """Set the blob's default chunk size. + + :type value: int + :param value: (Optional) The current blob's chunk size, if it is set. + + :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a + multiple of 256 KB. + """ + if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0: + raise ValueError( + "Chunk size must be a multiple of %d." % (self._CHUNK_SIZE_MULTIPLE,) + ) + self._chunk_size = value + + @property + def encryption_key(self): + """Retrieve the customer-supplied encryption key for the object. + + :rtype: bytes or ``NoneType`` + :returns: + The encryption key or ``None`` if no customer-supplied encryption key was used, + or the blob's resource has not been loaded from the server. + """ + return self._encryption_key + + @encryption_key.setter + def encryption_key(self, value): + """Set the blob's encryption key. + + See https://cloud.google.com/storage/docs/encryption#customer-supplied + + To perform a key rotation for an encrypted blob, use :meth:`rewrite`. + See https://cloud.google.com/storage/docs/encryption/using-customer-supplied-keys?hl=ca#rotating + + :type value: bytes + :param value: 32 byte encryption key for customer-supplied encryption. + """ + self._encryption_key = value + + @staticmethod + def path_helper(bucket_path, blob_name): + """Relative URL path for a blob. + + :type bucket_path: str + :param bucket_path: The URL path for a bucket. + + :type blob_name: str + :param blob_name: The name of the blob. + + :rtype: str + :returns: The relative URL path for ``blob_name``. + """ + return bucket_path + "/o/" + _quote(blob_name) + + @property + def acl(self): + """Create our ACL on demand.""" + return self._acl + + def __repr__(self): + if self.bucket: + bucket_name = self.bucket.name + else: + bucket_name = None + + return f"" + + @property + def path(self): + """Getter property for the URL path to this Blob. + + :rtype: str + :returns: The URL path to this Blob. + """ + if not self.name: + raise ValueError("Cannot determine path without a blob name.") + + return self.path_helper(self.bucket.path, self.name) + + @property + def client(self): + """The client bound to this blob.""" + return self.bucket.client + + @property + def user_project(self): + """Project ID billed for API requests made via this blob. + + Derived from bucket's value. + + :rtype: str + """ + return self.bucket.user_project + + def _encryption_headers(self): + """Return any encryption headers needed to fetch the object. + + :rtype: List(Tuple(str, str)) + :returns: a list of tuples to be passed as headers. + """ + return _get_encryption_headers(self._encryption_key) + + @property + def _query_params(self): + """Default query parameters.""" + params = {} + if self.generation is not None: + params["generation"] = self.generation + if self.user_project is not None: + params["userProject"] = self.user_project + return params + + @property + def public_url(self): + """The public URL for this blob. + + Use :meth:`make_public` to enable anonymous access via the returned + URL. + + :rtype: `string` + :returns: The public URL for this blob. + """ + if self.client: + endpoint = self.client.api_endpoint + else: + endpoint = _get_default_storage_base_url() + return "{storage_base_url}/{bucket_name}/{quoted_name}".format( + storage_base_url=endpoint, + bucket_name=self.bucket.name, + quoted_name=_quote(self.name, safe=b"/~"), + ) + + @classmethod + def from_uri(cls, uri, client=None): + """Get a constructor for blob object by URI. + + .. code-block:: python + + from google.cloud import storage + from google.cloud.storage.blob import Blob + client = storage.Client() + blob = Blob.from_uri("gs://bucket/object", client=client) + + :type uri: str + :param uri: The blob uri following a gs://bucket/object pattern. + Both a bucket and object name is required to construct a blob object. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. Application code should + *always* pass ``client``. + + :rtype: :class:`google.cloud.storage.blob.Blob` + :returns: The blob object created. + """ + from google.cloud.storage.bucket import Bucket + + match = _GS_URL_REGEX_PATTERN.match(uri) + if not match: + raise ValueError("URI pattern must be gs://bucket/object") + bucket = Bucket(client, name=match.group("bucket_name")) + return cls(match.group("object_name"), bucket) + + @classmethod + def from_string(cls, uri, client=None): + """(Deprecated) Get a constructor for blob object by URI. + + .. note:: + Deprecated alias for :meth:`from_uri`. + + .. code-block:: python + + from google.cloud import storage + from google.cloud.storage.blob import Blob + client = storage.Client() + blob = Blob.from_string("gs://bucket/object", client=client) + + :type uri: str + :param uri: The blob uri following a gs://bucket/object pattern. + Both a bucket and object name is required to construct a blob object. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. Application code should + *always* pass ``client``. + + :rtype: :class:`google.cloud.storage.blob.Blob` + :returns: The blob object created. + """ + warnings.warn(_FROM_STRING_DEPRECATED, PendingDeprecationWarning, stacklevel=2) + return Blob.from_uri(uri=uri, client=client) + + def generate_signed_url( + self, + expiration=None, + api_access_endpoint=None, + method="GET", + content_md5=None, + content_type=None, + response_disposition=None, + response_type=None, + generation=None, + headers=None, + query_parameters=None, + client=None, + credentials=None, + version=None, + service_account_email=None, + access_token=None, + virtual_hosted_style=False, + bucket_bound_hostname=None, + scheme="http", + ): + """Generates a signed URL for this blob. + + .. note:: + + If you are on Google Compute Engine, you can't generate a signed + URL using GCE service account. + If you'd like to be able to generate a signed URL from GCE, + you can use a standard service account from a JSON file rather + than a GCE service account. + + If you have a blob that you want to allow access to for a set + amount of time, you can use this method to generate a URL that + is only valid within a certain time period. + + See a [code sample](https://cloud.google.com/storage/docs/samples/storage-generate-signed-url-v4#storage_generate_signed_url_v4-python). + + This is particularly useful if you don't want publicly + accessible blobs, but don't want to require users to explicitly + log in. + + If ``bucket_bound_hostname`` is set as an argument of :attr:`api_access_endpoint`, + ``https`` works only if using a ``CDN``. + + :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] + :param expiration: + Point in time when the signed URL should expire. If a ``datetime`` + instance is passed without an explicit ``tzinfo`` set, it will be + assumed to be ``UTC``. + + :type api_access_endpoint: str + :param api_access_endpoint: (Optional) URI base, for instance + "https://storage.googleapis.com". If not specified, the client's + api_endpoint will be used. Incompatible with bucket_bound_hostname. + + :type method: str + :param method: The HTTP verb that will be used when requesting the URL. + + :type content_md5: str + :param content_md5: + (Optional) The MD5 hash of the object referenced by ``resource``. + + :type content_type: str + :param content_type: + (Optional) The content type of the object referenced by + ``resource``. + + :type response_disposition: str + :param response_disposition: + (Optional) Content disposition of responses to requests for the + signed URL. For example, to enable the signed URL to initiate a + file of ``blog.png``, use the value ``'attachment; + filename=blob.png'``. + + :type response_type: str + :param response_type: + (Optional) Content type of responses to requests for the signed + URL. Ignored if content_type is set on object/blob metadata. + + :type generation: str + :param generation: + (Optional) A value that indicates which generation of the resource + to fetch. + + :type headers: dict + :param headers: + (Optional) Additional HTTP headers to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers + Requests using the signed URL *must* pass the specified header + (name and value) with each request for the URL. + + :type query_parameters: dict + :param query_parameters: + (Optional) Additional query parameters to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers#query + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type credentials: :class:`google.auth.credentials.Credentials` + :param credentials: + (Optional) 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. + + :type version: str + :param version: + (Optional) The version of signed credential to create. Must be one + of 'v2' | 'v4'. + + :type service_account_email: str + :param service_account_email: + (Optional) E-mail address of the service account. + + :type access_token: str + :param access_token: (Optional) Access token for a service account. + + :type virtual_hosted_style: bool + :param virtual_hosted_style: + (Optional) If true, then construct the URL relative the bucket's + virtual hostname, e.g., '.storage.googleapis.com'. + Incompatible with bucket_bound_hostname. + + :type bucket_bound_hostname: str + :param bucket_bound_hostname: + (Optional) If passed, then construct the URL relative to the bucket-bound hostname. + Value can be a bare or with scheme, e.g., 'example.com' or 'http://example.com'. + Incompatible with api_access_endpoint and virtual_hosted_style. + See: https://cloud.google.com/storage/docs/request-endpoints#cname + + :type scheme: str + :param scheme: + (Optional) If ``bucket_bound_hostname`` is passed as a bare + hostname, use this value as the scheme. ``https`` will work only + when using a CDN. Defaults to ``"http"``. + + :raises: :exc:`ValueError` when version is invalid or mutually exclusive arguments are used. + :raises: :exc:`TypeError` when expiration is not a valid type. + :raises: :exc:`AttributeError` if credentials is not an instance + of :class:`google.auth.credentials.Signing`. + + :rtype: str + :returns: A signed URL you can use to access the resource + until expiration. + """ + if version is None: + version = "v2" + elif version not in ("v2", "v4"): + raise ValueError("'version' must be either 'v2' or 'v4'") + + if ( + api_access_endpoint is not None or virtual_hosted_style + ) and bucket_bound_hostname: + raise ValueError( + "The bucket_bound_hostname argument is not compatible with " + "either api_access_endpoint or virtual_hosted_style." + ) + + if api_access_endpoint is None: + client = self._require_client(client) + api_access_endpoint = client.api_endpoint + + quoted_name = _quote(self.name, safe=b"/~") + + # If you are on Google Compute Engine, you can't generate a signed URL + # using GCE service account. + # See https://github.com/googleapis/google-auth-library-python/issues/50 + if virtual_hosted_style: + api_access_endpoint = _virtual_hosted_style_base_url( + api_access_endpoint, self.bucket.name + ) + resource = f"/{quoted_name}" + elif bucket_bound_hostname: + api_access_endpoint = _bucket_bound_hostname_url( + bucket_bound_hostname, scheme + ) + resource = f"/{quoted_name}" + else: + resource = f"/{self.bucket.name}/{quoted_name}" + + if credentials is None: + client = self._require_client(client) # May be redundant, but that's ok. + credentials = client._credentials + + client = self._require_client(client) + universe_domain = client.universe_domain + + if version == "v2": + helper = generate_signed_url_v2 + else: + helper = generate_signed_url_v4 + + if self._encryption_key is not None: + encryption_headers = _get_encryption_headers(self._encryption_key) + if headers is None: + headers = {} + if version == "v2": + # See: https://cloud.google.com/storage/docs/access-control/signed-urls-v2#about-canonical-extension-headers + v2_copy_only = "X-Goog-Encryption-Algorithm" + headers[v2_copy_only] = encryption_headers[v2_copy_only] + else: + headers.update(encryption_headers) + + return helper( + credentials, + resource=resource, + expiration=expiration, + api_access_endpoint=api_access_endpoint, + method=method.upper(), + content_md5=content_md5, + content_type=content_type, + response_type=response_type, + response_disposition=response_disposition, + generation=generation, + headers=headers, + query_parameters=query_parameters, + service_account_email=service_account_email, + access_token=access_token, + universe_domain=universe_domain, + ) + + def exists( + self, + client=None, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + soft_deleted=None, + ): + """Determines whether or not this blob exists. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type soft_deleted: bool + :param soft_deleted: + (Optional) If True, looks for a soft-deleted object. Will only return True + if the object exists and is in a soft-deleted state. + :attr:`generation` is required to be set on the blob if ``soft_deleted`` is set to True. + See: https://cloud.google.com/storage/docs/soft-delete + + :rtype: bool + :returns: True if the blob exists in Cloud Storage. + """ + with create_trace_span(name="Storage.Blob.exists"): + client = self._require_client(client) + # We only need the status code (200 or not) so we seek to + # minimize the returned payload. + query_params = self._query_params + query_params["fields"] = "name" + if soft_deleted is not None: + query_params["softDeleted"] = soft_deleted + + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + + headers = {} + _add_etag_match_headers( + headers, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + ) + + try: + # We intentionally pass `_target_object=None` since fields=name + # would limit the local properties. + client._get_resource( + self.path, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=None, + ) + except NotFound: + # NOTE: This will not fail immediately in a batch. However, when + # Batch.finish() is called, the resulting `NotFound` will be + # raised. + return False + return True + + def delete( + self, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Deletes a blob from Cloud Storage. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :raises: :class:`google.cloud.exceptions.NotFound` + (propagated from + :meth:`google.cloud.storage.bucket.Bucket.delete_blob`). + """ + with create_trace_span(name="Storage.Blob.delete"): + self.bucket.delete_blob( + self.name, + client=client, + generation=self.generation, + timeout=timeout, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + def _get_transport(self, client): + """Return the client's transport. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :rtype transport: + :class:`~google.auth.transport.requests.AuthorizedSession` + :returns: The transport (with credentials) that will + make authenticated requests. + """ + client = self._require_client(client) + return client._http + + def _get_download_url( + self, + client, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + ): + """Get the download URL for the current blob. + + If the ``media_link`` has been loaded, it will be used, otherwise + the URL will be constructed from the current blob's path (and possibly + generation) to avoid a round trip. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: The client to use. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :rtype: str + :returns: The download URL for the current blob. + """ + name_value_pairs = [] + if self.media_link is None: + hostname = _get_host_name(client._connection) + base_url = _DOWNLOAD_URL_TEMPLATE.format( + hostname=hostname, path=self.path, api_version=_API_VERSION + ) + if self.generation is not None: + name_value_pairs.append(("generation", f"{self.generation:d}")) + else: + base_url = self.media_link + + if self.user_project is not None: + name_value_pairs.append(("userProject", self.user_project)) + + _add_generation_match_parameters( + name_value_pairs, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + return _add_query_parameters(base_url, name_value_pairs) + + def _extract_headers_from_download(self, response): + """Extract headers from a non-chunked request's http object. + + This avoids the need to make a second request for commonly used + headers. + + :type response: + :class requests.models.Response + :param response: The server response from downloading a non-chunked file + """ + self._properties["contentEncoding"] = response.headers.get( + "Content-Encoding", None + ) + self._properties[_CONTENT_TYPE_FIELD] = response.headers.get( + "Content-Type", None + ) + self._properties["cacheControl"] = response.headers.get("Cache-Control", None) + self._properties["storageClass"] = response.headers.get( + "X-Goog-Storage-Class", None + ) + self._properties["contentLanguage"] = response.headers.get( + "Content-Language", None + ) + self._properties["etag"] = response.headers.get("ETag", None) + self._properties["generation"] = response.headers.get("X-goog-generation", None) + self._properties["metageneration"] = response.headers.get( + "X-goog-metageneration", None + ) + # 'X-Goog-Hash': 'crc32c=4gcgLQ==,md5=CS9tHYTtyFntzj7B9nkkJQ==', + x_goog_hash = response.headers.get("X-Goog-Hash", "") + + if x_goog_hash: + digests = {} + for encoded_digest in x_goog_hash.split(","): + match = re.match(r"(crc32c|md5)=([\w\d/\+/]+={0,3})", encoded_digest) + if match: + method, digest = match.groups() + digests[method] = digest + + self._properties["crc32c"] = digests.get("crc32c", None) + self._properties["md5Hash"] = digests.get("md5", None) + + def _do_download( + self, + transport, + file_obj, + download_url, + headers, + start=None, + end=None, + raw_download=False, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + """Perform a download without any error handling. + + This is intended to be called by :meth:`_prep_and_do_download` so it can + be wrapped with error handling / remapping. + + :type transport: + :class:`~google.auth.transport.requests.AuthorizedSession` + :param transport: + The transport (with credentials) that will make authenticated + requests. + + :type file_obj: file + :param file_obj: A file handle to which to write the blob's data. + + :type download_url: str + :param download_url: The URL where the media can be accessed. + + :type headers: dict + :param headers: Headers to be sent with the request(s). + + :type start: int + :param start: (Optional) The first byte in a range to be downloaded. + + :type end: int + :param end: (Optional) The last byte in a range to be downloaded. + + :type raw_download: bool + :param raw_download: + (Optional) If true, download the object without any expansion. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify the integrity + of the object. The response headers must contain a checksum of the + requested type. If the headers lack an appropriate checksum (for + instance in the case of transcoded or ranged downloads where the + remote service does not know the correct checksum, including + downloads where chunk_size is set) an INFO-level log will be + emitted. Supported values are "md5", "crc32c", "auto" and None. The + default is "auto", which will try to detect if the C extension for + crc32c is installed and fall back to md5 otherwise. + + :type retry: google.api_core.retry.Retry + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will configure backoff and timeout options. + + This private method does not accept ConditionalRetryPolicy values + because the information necessary to evaluate the policy is instead + evaluated in blob._prep_and_do_download(). + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type single_shot_download: bool + :param single_shot_download: + (Optional) If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + """ + + extra_attributes = _get_opentelemetry_attributes_from_url(download_url) + extra_attributes["download.chunk_size"] = f"{self.chunk_size}" + extra_attributes["download.raw_download"] = raw_download + extra_attributes["upload.checksum"] = f"{checksum}" + extra_attributes["download.single_shot_download"] = single_shot_download + args = {"timeout": timeout} + + if self.chunk_size is None: + if raw_download: + klass = RawDownload + download_class = "RawDownload" + else: + klass = Download + download_class = "Download" + + download = klass( + download_url, + stream=file_obj, + headers=headers, + start=start, + end=end, + checksum=checksum, + retry=retry, + # NOTE: single_shot_download is only supported in Download and RawDownload + # classes, i.e., when chunk_size is set to None (the default value). It is + # not supported for chunked downloads. + single_shot_download=single_shot_download, + ) + with create_trace_span( + name=f"Storage.{download_class}/consume", + attributes=extra_attributes, + api_request=args, + ): + response = download.consume(transport, timeout=timeout) + self._extract_headers_from_download(response) + else: + if checksum: + msg = _CHUNKED_DOWNLOAD_CHECKSUM_MESSAGE.format(checksum) + _logger.info(msg) + + if raw_download: + klass = RawChunkedDownload + download_class = "RawChunkedDownload" + else: + klass = ChunkedDownload + download_class = "ChunkedDownload" + + download = klass( + download_url, + self.chunk_size, + file_obj, + headers=headers, + start=start if start else 0, + end=end, + retry=retry, + ) + + with create_trace_span( + name=f"Storage.{download_class}/consumeNextChunk", + attributes=extra_attributes, + api_request=args, + ): + while not download.finished: + download.consume_next_chunk(transport, timeout=timeout) + + def download_to_file( + self, + file_obj, + client=None, + start=None, + end=None, + raw_download=False, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + """Download the contents of this blob into a file-like object. + + .. note:: + + If the server-set property, :attr:`media_link`, is not yet + initialized, makes an additional API request to load it. + + If the :attr:`chunk_size` of a current blob is `None`, will download data + in single download request otherwise it will download the :attr:`chunk_size` + of data in each request. + + For more fine-grained control over the download process, check out + [`google-resumable-media`](https://googleapis.dev/python/google-resumable-media/latest/index.html). + For example, this library allows downloading **parts** of a blob rather than the whole thing. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type file_obj: file + :param file_obj: A file handle to which to write the blob's data. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type start: int + :param start: (Optional) The first byte in a range to be downloaded. + + :type end: int + :param end: (Optional) The last byte in a range to be downloaded. + + :type raw_download: bool + :param raw_download: + (Optional) If true, download the object without any expansion. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify the integrity + of the object. The response headers must contain a checksum of the + requested type. If the headers lack an appropriate checksum (for + instance in the case of transcoded or ranged downloads where the + remote service does not know the correct checksum, including + downloads where chunk_size is set) an INFO-level log will be + emitted. Supported values are "md5", "crc32c", "auto" and None. The + default is "auto", which will try to detect if the C extension for + crc32c is installed and fall back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type single_shot_download: bool + :param single_shot_download: + (Optional) If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + :raises: :class:`google.cloud.exceptions.NotFound` + """ + with create_trace_span(name="Storage.Blob.downloadToFile"): + self._prep_and_do_download( + file_obj, + client=client, + start=start, + end=end, + raw_download=raw_download, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + single_shot_download=single_shot_download, + ) + + def _handle_filename_and_download(self, filename, *args, **kwargs): + """Download the contents of this blob into a named file. + + :type filename: str + :param filename: A filename to be passed to ``open``. + + For *args and **kwargs, refer to the documentation for download_to_filename() for more information. + """ + + try: + with open(filename, "wb") as file_obj: + self._prep_and_do_download( + file_obj, + *args, + **kwargs, + ) + + except (DataCorruption, NotFound): + # Delete the corrupt or empty downloaded file. + os.remove(filename) + raise + + updated = self.updated + if updated is not None: + mtime = updated.timestamp() + os.utime(file_obj.name, (mtime, mtime)) + + def download_to_filename( + self, + filename, + client=None, + start=None, + end=None, + raw_download=False, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + """Download the contents of this blob into a named file. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + See a [code sample](https://cloud.google.com/storage/docs/samples/storage-download-encrypted-file#storage_download_encrypted_file-python) + to download a file with a [`customer-supplied encryption key`](https://cloud.google.com/storage/docs/encryption#customer-supplied). + + :type filename: str + :param filename: A filename to be passed to ``open``. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type start: int + :param start: (Optional) The first byte in a range to be downloaded. + + :type end: int + :param end: (Optional) The last byte in a range to be downloaded. + + :type raw_download: bool + :param raw_download: + (Optional) If true, download the object without any expansion. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify the integrity + of the object. The response headers must contain a checksum of the + requested type. If the headers lack an appropriate checksum (for + instance in the case of transcoded or ranged downloads where the + remote service does not know the correct checksum, including + downloads where chunk_size is set) an INFO-level log will be + emitted. Supported values are "md5", "crc32c", "auto" and None. The + default is "auto", which will try to detect if the C extension for + crc32c is installed and fall back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type single_shot_download: bool + :param single_shot_download: + (Optional) If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + :raises: :class:`google.cloud.exceptions.NotFound` + """ + with create_trace_span(name="Storage.Blob.downloadToFilename"): + self._handle_filename_and_download( + filename, + client=client, + start=start, + end=end, + raw_download=raw_download, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + single_shot_download=single_shot_download, + ) + + def download_as_bytes( + self, + client=None, + start=None, + end=None, + raw_download=False, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + """Download the contents of this blob as a bytes object. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type start: int + :param start: (Optional) The first byte in a range to be downloaded. + + :type end: int + :param end: (Optional) The last byte in a range to be downloaded. + + :type raw_download: bool + :param raw_download: + (Optional) If true, download the object without any expansion. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify the integrity + of the object. The response headers must contain a checksum of the + requested type. If the headers lack an appropriate checksum (for + instance in the case of transcoded or ranged downloads where the + remote service does not know the correct checksum, including + downloads where chunk_size is set) an INFO-level log will be + emitted. Supported values are "md5", "crc32c", "auto" and None. The + default is "auto", which will try to detect if the C extension for + crc32c is installed and fall back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type single_shot_download: bool + :param single_shot_download: + (Optional) If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + :rtype: bytes + :returns: The data stored in this blob. + + :raises: :class:`google.cloud.exceptions.NotFound` + """ + with create_trace_span(name="Storage.Blob.downloadAsBytes"): + string_buffer = BytesIO() + + self._prep_and_do_download( + string_buffer, + client=client, + start=start, + end=end, + raw_download=raw_download, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + single_shot_download=single_shot_download, + ) + return string_buffer.getvalue() + + def download_as_string( + self, + client=None, + start=None, + end=None, + raw_download=False, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + """(Deprecated) Download the contents of this blob as a bytes object. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + .. note:: + Deprecated alias for :meth:`download_as_bytes`. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type start: int + :param start: (Optional) The first byte in a range to be downloaded. + + :type end: int + :param end: (Optional) The last byte in a range to be downloaded. + + :type raw_download: bool + :param raw_download: + (Optional) If true, download the object without any expansion. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type single_shot_download: bool + :param single_shot_download: + (Optional) If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + :rtype: bytes + :returns: The data stored in this blob. + + :raises: :class:`google.cloud.exceptions.NotFound` + """ + warnings.warn( + _DOWNLOAD_AS_STRING_DEPRECATED, + PendingDeprecationWarning, + stacklevel=2, + ) + with create_trace_span(name="Storage.Blob.downloadAsString"): + return self.download_as_bytes( + client=client, + start=start, + end=end, + raw_download=raw_download, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + single_shot_download=single_shot_download, + ) + + def download_as_text( + self, + client=None, + start=None, + end=None, + raw_download=False, + encoding=None, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + """Download the contents of this blob as text (*not* bytes). + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type start: int + :param start: (Optional) The first byte in a range to be downloaded. + + :type end: int + :param end: (Optional) The last byte in a range to be downloaded. + + :type raw_download: bool + :param raw_download: + (Optional) If true, download the object without any expansion. + + :type encoding: str + :param encoding: (Optional) encoding to be used to decode the + downloaded bytes. Defaults to the ``charset`` param of + attr:`content_type`, or else to "utf-8". + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type single_shot_download: bool + :param single_shot_download: + (Optional) If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + :rtype: text + :returns: The data stored in this blob, decoded to text. + """ + with create_trace_span(name="Storage.Blob.downloadAsText"): + data = self.download_as_bytes( + client=client, + start=start, + end=end, + raw_download=raw_download, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + single_shot_download=single_shot_download, + ) + + if encoding is not None: + return data.decode(encoding) + + if self.content_type is not None: + msg = HeaderParser().parsestr("Content-Type: " + self.content_type) + params = dict(msg.get_params()[1:]) + if "charset" in params: + return data.decode(params["charset"]) + + return data.decode("utf-8") + + def _get_content_type(self, content_type, filename=None): + """Determine the content type from the current object. + + The return value will be determined in order of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + :type content_type: str + :param content_type: (Optional) Type of content. + + :type filename: str + :param filename: + (Optional) The name of the file where the content is stored. + + :rtype: str + :returns: Type of content gathered from the object. + """ + if content_type is None: + content_type = self.content_type + + if content_type is None and filename is not None: + content_type, _ = mimetypes.guess_type(filename) + + if content_type is None: + content_type = _DEFAULT_CONTENT_TYPE + + return content_type + + def _get_writable_metadata(self): + """Get the object / blob metadata which is writable. + + This is intended to be used when creating a new object / blob. + + See the [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects) + for more information, the fields marked as writable are: + + * ``acl`` + * ``cacheControl`` + * ``contentDisposition`` + * ``contentEncoding`` + * ``contentLanguage`` + * ``contentType`` + * ``crc32c`` + * ``customTime`` + * ``md5Hash`` + * ``metadata`` + * ``name`` + * ``retention`` + * ``storageClass`` + + For now, we don't support ``acl``, access control lists should be + managed directly through :class:`ObjectACL` methods. + """ + # NOTE: This assumes `self.name` is unicode. + object_metadata = {"name": self.name} + for key in self._changes: + if key in _WRITABLE_FIELDS: + object_metadata[key] = self._properties[key] + + return object_metadata + + def _get_upload_arguments(self, client, content_type, filename=None, command=None): + """Get required arguments for performing an upload. + + The content type returned will be determined in order of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + :type content_type: str + :param content_type: Type of content being uploaded (or :data:`None`). + + :type command: str + :param command: + (Optional) Information about which interface for upload was used, + to be included in the X-Goog-API-Client header. Please leave as None + unless otherwise directed. + + :rtype: tuple + :returns: A triple of + + * A header dictionary + * An object metadata dictionary + * The ``content_type`` as a string (according to precedence) + """ + content_type = self._get_content_type(content_type, filename=filename) + # Add any client attached custom headers to the upload headers. + headers = { + **_get_default_headers( + client._connection.user_agent, content_type, command=command + ), + **_get_encryption_headers(self._encryption_key), + **client._extra_headers, + } + object_metadata = self._get_writable_metadata() + return headers, object_metadata, content_type + + def _do_multipart_upload( + self, + client, + stream, + content_type, + size, + predefined_acl, + if_generation_match, + if_generation_not_match, + if_metageneration_match, + if_metageneration_not_match, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=None, + command=None, + ): + """Perform a multipart upload. + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type stream: IO[bytes] + :param stream: A bytes IO object open for reading. + + :type content_type: str + :param content_type: Type of content being uploaded (or :data:`None`). + + :type size: int + :param size: + The number of bytes to be uploaded (which will be read from + ``stream``). If not provided, the upload will be concluded once + ``stream`` is exhausted (or :data:`None`). + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. The request metadata will be amended + to include the computed value. Using this option will override a + manually-set checksum value. Supported values are "md5", "crc32c", + "auto" and None. The default is "auto", which will try to detect if + the C extension for crc32c is installed and fall back to md5 + otherwise. + :type retry: google.api_core.retry.Retry + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will configure backoff and timeout options. + + This private method does not accept ConditionalRetryPolicy values + because the information necessary to evaluate the policy is instead + evaluated in blob._do_upload(). + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type command: str + :param command: + (Optional) Information about which interface for upload was used, + to be included in the X-Goog-API-Client header. Please leave as None + unless otherwise directed. + + :rtype: :class:`~requests.Response` + :returns: The "200 OK" response object returned after the multipart + upload request. + :raises: :exc:`ValueError` if ``size`` is not :data:`None` but the + ``stream`` has fewer than ``size`` bytes remaining. + """ + if size is None: + data = stream.read() + else: + data = stream.read(size) + if len(data) < size: + msg = _READ_LESS_THAN_SIZE.format(size, len(data)) + raise ValueError(msg) + + client = self._require_client(client) + transport = self._get_transport(client) + if "metadata" in self._properties and "metadata" not in self._changes: + self._changes.add("metadata") + + info = self._get_upload_arguments(client, content_type, command=command) + headers, object_metadata, content_type = info + + hostname = _get_host_name(client._connection) + base_url = _MULTIPART_URL_TEMPLATE.format( + hostname=hostname, + bucket_path=self.bucket.path, + api_version=_API_VERSION, + ) + name_value_pairs = [] + + if self.user_project is not None: + name_value_pairs.append(("userProject", self.user_project)) + + # When a Customer Managed Encryption Key is used to encrypt Cloud Storage object + # at rest, object resource metadata will store the version of the Key Management + # Service cryptographic material. If a Blob instance with KMS Key metadata set is + # used to upload a new version of the object then the existing kmsKeyName version + # value can't be used in the upload request and the client instead ignores it. + if ( + self.kms_key_name is not None + and "cryptoKeyVersions" not in self.kms_key_name + ): + name_value_pairs.append(("kmsKeyName", self.kms_key_name)) + + if predefined_acl is not None: + name_value_pairs.append(("predefinedAcl", predefined_acl)) + + if if_generation_match is not None: + name_value_pairs.append(("ifGenerationMatch", if_generation_match)) + + if if_generation_not_match is not None: + name_value_pairs.append(("ifGenerationNotMatch", if_generation_not_match)) + + if if_metageneration_match is not None: + name_value_pairs.append(("ifMetagenerationMatch", if_metageneration_match)) + + if if_metageneration_not_match is not None: + name_value_pairs.append( + ("ifMetaGenerationNotMatch", if_metageneration_not_match) + ) + + upload_url = _add_query_parameters(base_url, name_value_pairs) + upload = MultipartUpload( + upload_url, headers=headers, checksum=checksum, retry=retry + ) + + extra_attributes = _get_opentelemetry_attributes_from_url(upload_url) + extra_attributes["upload.checksum"] = f"{checksum}" + args = {"timeout": timeout} + with create_trace_span( + name="Storage.MultipartUpload/transmit", + attributes=extra_attributes, + client=client, + api_request=args, + ): + response = upload.transmit( + transport, data, object_metadata, content_type, timeout=timeout + ) + + return response + + def _initiate_resumable_upload( + self, + client, + stream, + content_type, + size, + predefined_acl=None, + extra_headers=None, + chunk_size=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=None, + command=None, + crc32c_checksum_value=None, + ): + """Initiate a resumable upload. + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type stream: IO[bytes] + :param stream: A bytes IO object open for reading. + + :type content_type: str + :param content_type: Type of content being uploaded (or :data:`None`). + + :type size: int + :param size: + The number of bytes to be uploaded (which will be read from + ``stream``). If not provided, the upload will be concluded once + ``stream`` is exhausted (or :data:`None`). + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type extra_headers: dict + :param extra_headers: + (Optional) Extra headers to add to standard headers. + + :type chunk_size: int + :param chunk_size: + (Optional) Chunk size to use when creating a + :class:`~google.cloud.storage._media.requests.ResumableUpload`. + If not passed, will fall back to the chunk size on the + current blob, if the chunk size of a current blob is also + `None`, will set the default value. + The default value of ``chunk_size`` is 100 MB. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be checked + and google.cloud.storage.exceptions.DataCorruption will be raised on + a mismatch. On a validation failure, the client will attempt to + delete the uploaded object automatically. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type retry: google.api_core.retry.Retry + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will configure backoff and timeout options. + + This private method does not accept ConditionalRetryPolicy values + because the information necessary to evaluate the policy is instead + evaluated in blob._do_upload(). + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type command: str + :param command: + (Optional) Information about which interface for upload was used, + to be included in the X-Goog-API-Client header. Please leave as None + unless otherwise directed. + + :type crc32c_checksum_value: str + :param crc32c_checksum_value: (Optional) This should be the checksum of + the entire contents of `file`. Applicable while uploading object + greater than `_MAX_MULTIPART_SIZE` bytes. + + It can be obtained by running + + `gcloud storage hash /path/to/your/file` + + or + + .. code-block:: python + + import google_crc32c + import base64 + + data = b"Hello, world!" + crc32c_int = google_crc32c.value(data) + crc32c_hex = f"{crc32c_int:08x}" + crc32c_bytes = crc32c_int.to_bytes(4, "big") + base64_encoded = base64.b64encode(crc32c_bytes) + crc32c_base64 = base64_encoded.decode("utf-8") + + print(crc32c_base64) + + Above code block prints 8 char string of base64 encoded big-endian + bytes of 32 bit CRC32c integer. + + More details on CRC32c can be found in Appendix B: + https://datatracker.ietf.org/doc/html/rfc4960#appendix-B and + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + + :rtype: tuple + :returns: + Pair of + + * The :class:`~google.cloud.storage._media.requests.ResumableUpload` + that was created + * The ``transport`` used to initiate the upload. + """ + client = self._require_client(client) + if chunk_size is None: + chunk_size = self.chunk_size + if chunk_size is None: + chunk_size = _DEFAULT_CHUNKSIZE + + transport = self._get_transport(client) + if "metadata" in self._properties and "metadata" not in self._changes: + self._changes.add("metadata") + info = self._get_upload_arguments(client, content_type, command=command) + headers, object_metadata, content_type = info + if extra_headers is not None: + headers.update(extra_headers) + + if crc32c_checksum_value is not None: + object_metadata["crc32c"] = crc32c_checksum_value + + hostname = _get_host_name(client._connection) + base_url = _RESUMABLE_URL_TEMPLATE.format( + hostname=hostname, + bucket_path=self.bucket.path, + api_version=_API_VERSION, + ) + name_value_pairs = [] + + if self.user_project is not None: + name_value_pairs.append(("userProject", self.user_project)) + + # When a Customer Managed Encryption Key is used to encrypt Cloud Storage object + # at rest, object resource metadata will store the version of the Key Management + # Service cryptographic material. If a Blob instance with KMS Key metadata set is + # used to upload a new version of the object then the existing kmsKeyName version + # value can't be used in the upload request and the client instead ignores it. + if ( + self.kms_key_name is not None + and "cryptoKeyVersions" not in self.kms_key_name + ): + name_value_pairs.append(("kmsKeyName", self.kms_key_name)) + + if predefined_acl is not None: + name_value_pairs.append(("predefinedAcl", predefined_acl)) + + if if_generation_match is not None: + name_value_pairs.append(("ifGenerationMatch", if_generation_match)) + + if if_generation_not_match is not None: + name_value_pairs.append(("ifGenerationNotMatch", if_generation_not_match)) + + if if_metageneration_match is not None: + name_value_pairs.append(("ifMetagenerationMatch", if_metageneration_match)) + + if if_metageneration_not_match is not None: + name_value_pairs.append( + ("ifMetaGenerationNotMatch", if_metageneration_not_match) + ) + + upload_url = _add_query_parameters(base_url, name_value_pairs) + upload = ResumableUpload( + upload_url, + chunk_size, + headers=headers, + checksum=checksum, + retry=retry, + ) + + upload.initiate( + transport, + stream, + object_metadata, + content_type, + total_bytes=size, + stream_final=False, + timeout=timeout, + ) + + return upload, transport + + def _do_resumable_upload( + self, + client, + stream, + content_type, + size, + predefined_acl, + if_generation_match, + if_generation_not_match, + if_metageneration_match, + if_metageneration_not_match, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=None, + command=None, + crc32c_checksum_value=None, + ): + """Perform a resumable upload. + + Assumes ``chunk_size`` is not :data:`None` on the current blob. + The default value of ``chunk_size`` is 100 MB. + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type stream: IO[bytes] + :param stream: A bytes IO object open for reading. + + :type content_type: str + :param content_type: Type of content being uploaded (or :data:`None`). + + :type size: int + :param size: + The number of bytes to be uploaded (which will be read from + ``stream``). If not provided, the upload will be concluded once + ``stream`` is exhausted (or :data:`None`). + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be checked + and google.cloud.storage.exceptions.DataCorruption will be raised on + a mismatch. On a validation failure, the client will attempt to + delete the uploaded object automatically. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type retry: google.api_core.retry.Retry + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will configure backoff and timeout options. + + This private method does not accept ConditionalRetryPolicy values + because the information necessary to evaluate the policy is instead + evaluated in blob._do_upload(). + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type command: str + :param command: + (Optional) Information about which interface for upload was used, + to be included in the X-Goog-API-Client header. Please leave as None + unless otherwise directed. + + :type crc32c_checksum_value: str + :param crc32c_checksum_value: (Optional) This should be the checksum of + the entire contents of `stream`. Applicable while uploading object + greater than `_MAX_MULTIPART_SIZE` bytes. + + It can be obtained by running + + `gcloud storage hash /path/to/your/file` + + or + + .. code-block:: python + + import google_crc32c + import base64 + + data = b"Hello, world!" + crc32c_int = google_crc32c.value(data) + crc32c_hex = f"{crc32c_int:08x}" + crc32c_bytes = crc32c_int.to_bytes(4, "big") + base64_encoded = base64.b64encode(crc32c_bytes) + crc32c_base64 = base64_encoded.decode("utf-8") + + print(crc32c_base64) + + Above code block prints 8 char string of base64 encoded big-endian + bytes of 32 bit CRC32c integer. + + More details on CRC32c can be found in Appendix B: + https://datatracker.ietf.org/doc/html/rfc4960#appendix-B and + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + + :rtype: :class:`~requests.Response` + :returns: The "200 OK" response object returned after the final chunk + is uploaded. + """ + upload, transport = self._initiate_resumable_upload( + client, + stream, + content_type, + size, + predefined_acl=predefined_acl, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + command=command, + crc32c_checksum_value=crc32c_checksum_value, + ) + extra_attributes = _get_opentelemetry_attributes_from_url(upload.resumable_url) + extra_attributes["upload.chunk_size"] = upload.chunk_size + extra_attributes["upload.checksum"] = f"{checksum}" + + args = {"timeout": timeout} + with create_trace_span( + name="Storage.ResumableUpload/transmitNextChunk", + attributes=extra_attributes, + client=client, + api_request=args, + ): + while not upload.finished: + try: + response = upload.transmit_next_chunk(transport, timeout=timeout) + except DataCorruption: + # Attempt to delete the corrupted object. + self.delete() + raise + return response + + def _do_upload( + self, + client, + stream, + content_type, + size, + predefined_acl, + if_generation_match, + if_generation_not_match, + if_metageneration_match, + if_metageneration_not_match, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=None, + command=None, + crc32c_checksum_value=None, + ): + """Determine an upload strategy and then perform the upload. + + If the size of the data to be uploaded exceeds 8 MB a resumable media + request will be used, otherwise the content and the metadata will be + uploaded in a single multipart upload request. + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type stream: IO[bytes] + :param stream: A bytes IO object open for reading. + + :type content_type: str + :param content_type: Type of content being uploaded (or :data:`None`). + + :type size: int + :param size: + The number of bytes to be uploaded (which will be read from + ``stream``). If not provided, the upload will be concluded once + ``stream`` is exhausted (or :data:`None`). + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. If the upload is completed in a single + request, the checksum will be entirely precomputed and the remote + server will handle verification and error handling. If the upload + is too large and must be transmitted in multiple requests, the + checksum will be incrementally computed and the client will handle + verification and error handling, raising + google.cloud.storage.exceptions.DataCorruption on a mismatch and + attempting to delete the corrupted file. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type command: str + :param command: + (Optional) Information about which interface for upload was used, + to be included in the X-Goog-API-Client header. Please leave as None + unless otherwise directed. + + :type crc32c_checksum_value: str + :param crc32c_checksum_value: (Optional) This should be the checksum of + the entire contents of `file_obj`. Applicable while uploading object + greater than `_MAX_MULTIPART_SIZE` bytes. + + It can be obtained by running + + `gcloud storage hash /path/to/your/file` + + or + + .. code-block:: python + + import google_crc32c + import base64 + + data = b"Hello, world!" + crc32c_int = google_crc32c.value(data) + crc32c_hex = f"{crc32c_int:08x}" + crc32c_bytes = crc32c_int.to_bytes(4, "big") + base64_encoded = base64.b64encode(crc32c_bytes) + crc32c_base64 = base64_encoded.decode("utf-8") + + print(crc32c_base64) + + Above code block prints 8 char string of base64 encoded big-endian + bytes of 32 bit CRC32c integer. + + More details on CRC32c can be found in Appendix B: + https://datatracker.ietf.org/doc/html/rfc4960#appendix-B and + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + + :rtype: dict + :returns: The parsed JSON from the "200 OK" response. This will be the + **only** response in the multipart case and it will be the + **final** response in the resumable case. + """ + + # Handle ConditionalRetryPolicy. + if isinstance(retry, ConditionalRetryPolicy): + # Conditional retries are designed for non-media calls, which change + # arguments into query_params dictionaries. Media operations work + # differently, so here we make a "fake" query_params to feed to the + # ConditionalRetryPolicy. + query_params = { + "ifGenerationMatch": if_generation_match, + "ifMetagenerationMatch": if_metageneration_match, + } + retry = retry.get_retry_policy_if_conditions_met(query_params=query_params) + + if size is not None and size <= _MAX_MULTIPART_SIZE: + response = self._do_multipart_upload( + client, + stream, + content_type, + size, + predefined_acl, + if_generation_match, + if_generation_not_match, + if_metageneration_match, + if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + command=command, + ) + else: + response = self._do_resumable_upload( + client, + stream, + content_type, + size, + predefined_acl, + if_generation_match, + if_generation_not_match, + if_metageneration_match, + if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + command=command, + crc32c_checksum_value=crc32c_checksum_value, + ) + + return response.json() + + def _prep_and_do_upload( + self, + file_obj, + rewind=False, + size=None, + content_type=None, + client=None, + predefined_acl=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + command=None, + crc32c_checksum_value=None, + ): + """Upload the contents of this blob from a file-like object. + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + .. note:: + The effect of uploading to an existing blob depends on the + "versioning" and "lifecycle" policies defined on the blob's + bucket. In the absence of those policies, upload will + overwrite any existing contents. + + See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning) + and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle) + API documents for details. + + If the size of the data to be uploaded exceeds 8 MB a resumable media + request will be used, otherwise the content and the metadata will be + uploaded in a single multipart upload request. + + For more fine-grained over the upload process, check out + [`google-resumable-media`](https://googleapis.dev/python/google-resumable-media/latest/index.html). + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type file_obj: file + :param file_obj: A file handle opened in binary mode for reading. + + :type rewind: bool + :param rewind: + If True, seek to the beginning of the file handle before writing + the file to Cloud Storage. + + :type size: int + :param size: + The number of bytes to be uploaded (which will be read from + ``file_obj``). If not provided, the upload will be concluded once + ``file_obj`` is exhausted. + + :type content_type: str + :param content_type: (Optional) Type of content being uploaded. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. If the upload is completed in a single + request, the checksum will be entirely precomputed and the remote + server will handle verification and error handling. If the upload + is too large and must be transmitted in multiple requests, the + checksum will be incrementally computed and the client will handle + verification and error handling, raising + google.cloud.storage.exceptions.DataCorruption on a mismatch and + attempting to delete the corrupted file. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type command: str + :param command: + (Optional) Information about which interface for upload was used, + to be included in the X-Goog-API-Client header. Please leave as None + unless otherwise directed. + + :type crc32c_checksum_value: str + :param crc32c_checksum_value: (Optional) This should be the checksum of + the entire contents of `file_obj`. Applicable while uploading object + greater than `_MAX_MULTIPART_SIZE` bytes. + + It can be obtained by running + + `gcloud storage hash /path/to/your/file` + + or + + .. code-block:: python + + import google_crc32c + import base64 + + data = b"Hello, world!" + crc32c_int = google_crc32c.value(data) + crc32c_hex = f"{crc32c_int:08x}" + crc32c_bytes = crc32c_int.to_bytes(4, "big") + base64_encoded = base64.b64encode(crc32c_bytes) + crc32c_base64 = base64_encoded.decode("utf-8") + + print(crc32c_base64) + + Above code block prints 8 char string of base64 encoded big-endian + bytes of 32 bit CRC32c integer. + + More details on CRC32c can be found in Appendix B: + https://datatracker.ietf.org/doc/html/rfc4960#appendix-B and + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + + :raises: :class:`~google.cloud.exceptions.GoogleCloudError` + if the upload response returns an error status. + """ + _maybe_rewind(file_obj, rewind=rewind) + predefined_acl = ACL.validate_predefined(predefined_acl) + + try: + created_json = self._do_upload( + client, + file_obj, + content_type, + size, + predefined_acl, + if_generation_match, + if_generation_not_match, + if_metageneration_match, + if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + command=command, + crc32c_checksum_value=crc32c_checksum_value, + ) + self._set_properties(created_json) + except InvalidResponse as exc: + _raise_from_invalid_response(exc) + + def upload_from_file( + self, + file_obj, + rewind=False, + size=None, + content_type=None, + client=None, + predefined_acl=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + crc32c_checksum_value=None, + ): + """Upload the contents of this blob from a file-like object. + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + .. note:: + The effect of uploading to an existing blob depends on the + "versioning" and "lifecycle" policies defined on the blob's + bucket. In the absence of those policies, upload will + overwrite any existing contents. + + See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning) + and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle) + API documents for details. + + If the size of the data to be uploaded exceeds 8 MB a resumable media + request will be used, otherwise the content and the metadata will be + uploaded in a single multipart upload request. + + For more fine-grained over the upload process, check out + [`google-resumable-media`](https://googleapis.dev/python/google-resumable-media/latest/index.html). + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type file_obj: file + :param file_obj: A file handle opened in binary mode for reading. + + :type rewind: bool + :param rewind: + If True, seek to the beginning of the file handle before writing + the file to Cloud Storage. + + :type size: int + :param size: + The number of bytes to be uploaded (which will be read from + ``file_obj``). If not provided, the upload will be concluded once + ``file_obj`` is exhausted. + + :type content_type: str + :param content_type: (Optional) Type of content being uploaded. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. If the upload is completed in a single + request, the checksum will be entirely precomputed and the remote + server will handle verification and error handling. If the upload + is too large and must be transmitted in multiple requests, the + checksum will be incrementally computed and the client will handle + verification and error handling, raising + google.cloud.storage.exceptions.DataCorruption on a mismatch and + attempting to delete the corrupted file. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type crc32c_checksum_value: str + :param crc32c_checksum_value: (Optional) This should be the checksum of + the entire contents of `file_obj`. Applicable while uploading object + greater than `_MAX_MULTIPART_SIZE` bytes. + + It can be obtained by running + + `gcloud storage hash /path/to/your/file` + + or + + .. code-block:: python + + import google_crc32c + import base64 + + data = b"Hello, world!" + crc32c_int = google_crc32c.value(data) + crc32c_hex = f"{crc32c_int:08x}" + crc32c_bytes = crc32c_int.to_bytes(4, "big") + base64_encoded = base64.b64encode(crc32c_bytes) + crc32c_base64 = base64_encoded.decode("utf-8") + + print(crc32c_base64) + + Above code block prints 8 char string of base64 encoded big-endian + bytes of 32 bit CRC32c integer. + + More details on CRC32c can be found in Appendix B: + https://datatracker.ietf.org/doc/html/rfc4960#appendix-B and + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + + :raises: :class:`~google.cloud.exceptions.GoogleCloudError` + if the upload response returns an error status. + """ + with create_trace_span(name="Storage.Blob.uploadFromFile"): + self._prep_and_do_upload( + file_obj, + rewind=rewind, + size=size, + content_type=content_type, + client=client, + predefined_acl=predefined_acl, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + crc32c_checksum_value=crc32c_checksum_value, + ) + + def _handle_filename_and_upload(self, filename, content_type=None, *args, **kwargs): + """Upload this blob's contents from the content of a named file. + + :type filename: str + :param filename: The path to the file. + + :type content_type: str + :param content_type: (Optional) Type of content being uploaded. + + For *args and **kwargs, refer to the documentation for upload_from_filename() for more information. + """ + + content_type = self._get_content_type(content_type, filename=filename) + + with open(filename, "rb") as file_obj: + total_bytes = os.fstat(file_obj.fileno()).st_size + self._prep_and_do_upload( + file_obj, + content_type=content_type, + size=total_bytes, + *args, + **kwargs, + ) + + def upload_from_filename( + self, + filename, + content_type=None, + client=None, + predefined_acl=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + crc32c_checksum_value=None, + ): + """Upload this blob's contents from the content of a named file. + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The value given by ``mimetypes.guess_type`` + - The default value ('application/octet-stream') + + .. note:: + The effect of uploading to an existing blob depends on the + "versioning" and "lifecycle" policies defined on the blob's + bucket. In the absence of those policies, upload will + overwrite any existing contents. + + See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning) + and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle) + API documents for details. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + See a [code sample](https://cloud.google.com/storage/docs/samples/storage-upload-encrypted-file#storage_upload_encrypted_file-python) + to upload a file with a + [`customer-supplied encryption key`](https://cloud.google.com/storage/docs/encryption#customer-supplied). + + :type filename: str + :param filename: The path to the file. + + :type content_type: str + :param content_type: (Optional) Type of content being uploaded. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. If the upload is completed in a single + request, the checksum will be entirely precomputed and the remote + server will handle verification and error handling. If the upload + is too large and must be transmitted in multiple requests, the + checksum will be incrementally computed and the client will handle + verification and error handling, raising + google.cloud.storage.exceptions.DataCorruption on a mismatch and + attempting to delete the corrupted file. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type crc32c_checksum_value: str + :param crc32c_checksum_value: (Optional) This should be the checksum of + the entire contents of `filename`. Applicable while uploading object + greater than `_MAX_MULTIPART_SIZE` bytes. + + It can be obtained by running + + `gcloud storage hash /path/to/your/file` + + or + + .. code-block:: python + + import google_crc32c + import base64 + + data = b"Hello, world!" + crc32c_int = google_crc32c.value(data) + crc32c_hex = f"{crc32c_int:08x}" + crc32c_bytes = crc32c_int.to_bytes(4, "big") + base64_encoded = base64.b64encode(crc32c_bytes) + crc32c_base64 = base64_encoded.decode("utf-8") + + print(crc32c_base64) + + Above code block prints 8 char string of base64 encoded big-endian + bytes of 32 bit CRC32c integer. + + More details on CRC32c can be found in Appendix B: + https://datatracker.ietf.org/doc/html/rfc4960#appendix-B and + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + """ + with create_trace_span(name="Storage.Blob.uploadFromFilename"): + self._handle_filename_and_upload( + filename, + content_type=content_type, + client=client, + predefined_acl=predefined_acl, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + crc32c_checksum_value=crc32c_checksum_value, + ) + + def upload_from_string( + self, + data, + content_type="text/plain", + client=None, + predefined_acl=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + crc32c_checksum_value=None, + ): + """Upload contents of this blob from the provided string. + + .. note:: + The effect of uploading to an existing blob depends on the + "versioning" and "lifecycle" policies defined on the blob's + bucket. In the absence of those policies, upload will + overwrite any existing contents. + + See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning) + and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle) + API documents for details. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type data: bytes or str + :param data: + The data to store in this blob. If the value is text, it will be + encoded as UTF-8. + + :type content_type: str + :param content_type: + (Optional) Type of content being uploaded. Defaults to + ``'text/plain'``. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. If the upload is completed in a single + request, the checksum will be entirely precomputed and the remote + server will handle verification and error handling. If the upload + is too large and must be transmitted in multiple requests, the + checksum will be incrementally computed and the client will handle + verification and error handling, raising + google.cloud.storage.exceptions.DataCorruption on a mismatch and + attempting to delete the corrupted file. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type crc32c_checksum_value: str + :param crc32c_checksum_value: (Optional) This should be the checksum of + the entire contents of `file_obj`. Applicable while uploading object + greater than `_MAX_MULTIPART_SIZE` bytes. + + It can be obtained by running + + `gcloud storage hash /path/to/your/file` + + or + + .. code-block:: python + + import google_crc32c + import base64 + + data = b"Hello, world!" + crc32c_int = google_crc32c.value(data) + crc32c_hex = f"{crc32c_int:08x}" + crc32c_bytes = crc32c_int.to_bytes(4, "big") + base64_encoded = base64.b64encode(crc32c_bytes) + crc32c_base64 = base64_encoded.decode("utf-8") + + print(crc32c_base64) + + Above code block prints 8 char string of base64 encoded big-endian + bytes of 32 bit CRC32c integer. + + More details on CRC32c can be found in Appendix B: + https://datatracker.ietf.org/doc/html/rfc4960#appendix-B and + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + """ + with create_trace_span(name="Storage.Blob.uploadFromString"): + data = _to_bytes(data, encoding="utf-8") + string_buffer = BytesIO(data) + self.upload_from_file( + file_obj=string_buffer, + size=len(data), + content_type=content_type, + client=client, + predefined_acl=predefined_acl, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + crc32c_checksum_value=crc32c_checksum_value, + ) + + def create_resumable_upload_session( + self, + content_type=None, + size=None, + origin=None, + client=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + predefined_acl=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + ): + """Create a resumable upload session. + + Resumable upload sessions allow you to start an upload session from + one client and complete the session in another. This method is called + by the initiator to set the metadata and limits. The initiator then + passes the session URL to the client that will upload the binary data. + The client performs a PUT request on the session URL to complete the + upload. This process allows untrusted clients to upload to an + access-controlled bucket. + + For more details, see the + documentation on [`signed URLs`](https://cloud.google.com/storage/docs/access-control/signed-urls#signing-resumable). + + The content type of the upload will be determined in order + of precedence: + + - The value passed in to this method (if not :data:`None`) + - The value stored on the current blob + - The default value ('application/octet-stream') + + .. note:: + The effect of uploading to an existing blob depends on the + "versioning" and "lifecycle" policies defined on the blob's + bucket. In the absence of those policies, upload will + overwrite any existing contents. + + See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning) + and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle) + API documents for details. + + If :attr:`encryption_key` is set, the blob will be encrypted with + a [`customer-supplied`](https://cloud.google.com/storage/docs/encryption#customer-supplied) + encryption key. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type size: int + :param size: + (Optional) The maximum number of bytes that can be uploaded using + this session. If the size is not known when creating the session, + this should be left blank. + + :type content_type: str + :param content_type: (Optional) Type of content being uploaded. + + :type origin: str + :param origin: + (Optional) If set, the upload can only be completed by a user-agent + that uploads from the given origin. This can be useful when passing + the session to a web client. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be checked + and google.cloud.storage.exceptions.DataCorruption will be raised on + a mismatch. On a validation failure, the client will attempt to + delete the uploaded object automatically. Supported values are + "md5", "crc32c", "auto" and None. The default is "auto", which will + try to detect if the C extension for crc32c is installed and fall + back to md5 otherwise. + + :type predefined_acl: str + :param predefined_acl: (Optional) Predefined access control list + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :rtype: str + :returns: The resumable upload session URL. The upload can be + completed by making an HTTP PUT request with the + file's contents. + + :raises: :class:`google.cloud.exceptions.GoogleCloudError` + if the session creation response returns an error status. + """ + with create_trace_span(name="Storage.Blob.createResumableUploadSession"): + # Handle ConditionalRetryPolicy. + if isinstance(retry, ConditionalRetryPolicy): + # Conditional retries are designed for non-media calls, which change + # arguments into query_params dictionaries. Media operations work + # differently, so here we make a "fake" query_params to feed to the + # ConditionalRetryPolicy. + query_params = { + "ifGenerationMatch": if_generation_match, + "ifMetagenerationMatch": if_metageneration_match, + } + retry = retry.get_retry_policy_if_conditions_met( + query_params=query_params + ) + + extra_headers = {} + if origin is not None: + # This header is specifically for client-side uploads, it + # determines the origins allowed for CORS. + extra_headers["Origin"] = origin + + try: + fake_stream = BytesIO(b"") + # Send a fake the chunk size which we **know** will be acceptable + # to the `ResumableUpload` constructor. The chunk size only + # matters when **sending** bytes to an upload. + upload, _ = self._initiate_resumable_upload( + client, + fake_stream, + content_type, + size, + predefined_acl=predefined_acl, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + extra_headers=extra_headers, + chunk_size=self._CHUNK_SIZE_MULTIPLE, + timeout=timeout, + checksum=checksum, + retry=retry, + ) + + return upload.resumable_url + except InvalidResponse as exc: + _raise_from_invalid_response(exc) + + def get_iam_policy( + self, + client=None, + requested_policy_version=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Retrieve the IAM policy for the object. + + .. note:: + + Blob- / object-level IAM support does not yet exist and methods + currently call an internal ACL backend not providing any utility + beyond the blob's :attr:`acl` at this time. The API may be enhanced + in the future and is currently undocumented. Use :attr:`acl` for + managing object access control. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the current object's bucket. + + :type requested_policy_version: int or ``NoneType`` + :param requested_policy_version: + (Optional) The version of IAM policies to request. If a policy + with a condition is requested without setting this, the server will + return an error. This must be set to a value of 3 to retrieve IAM + policies containing conditions. This is to prevent client code that + isn't aware of IAM conditions from interpreting and modifying + policies incorrectly. The service might return a policy with + version lower than the one that was requested, based on the feature + syntax in the policy fetched. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: :class:`google.api_core.iam.Policy` + :returns: the policy instance, based on the resource returned from + the ``getIamPolicy`` API request. + """ + with create_trace_span(name="Storage.Blob.getIamPolicy"): + client = self._require_client(client) + + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + if requested_policy_version is not None: + query_params["optionsRequestedPolicyVersion"] = requested_policy_version + + info = client._get_resource( + f"{self.path}/iam", + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + return Policy.from_api_repr(info) + + def set_iam_policy( + self, + policy, + client=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_ETAG_IN_JSON, + ): + """Update the IAM policy for the bucket. + + .. note:: + + Blob- / object-level IAM support does not yet exist and methods + currently call an internal ACL backend not providing any utility + beyond the blob's :attr:`acl` at this time. The API may be enhanced + in the future and is currently undocumented. Use :attr:`acl` for + managing object access control. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type policy: :class:`google.api_core.iam.Policy` + :param policy: policy instance used to update bucket's IAM policy. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the current bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: :class:`google.api_core.iam.Policy` + :returns: the policy instance, based on the resource returned from + the ``setIamPolicy`` API request. + """ + with create_trace_span(name="Storage.Blob.setIamPolicy"): + client = self._require_client(client) + + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + path = f"{self.path}/iam" + resource = policy.to_api_repr() + resource["resourceId"] = self.path + info = client._put_resource( + path, + resource, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + return Policy.from_api_repr(info) + + def test_iam_permissions( + self, + permissions, + client=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """API call: test permissions + + .. note:: + + Blob- / object-level IAM support does not yet exist and methods + currently call an internal ACL backend not providing any utility + beyond the blob's :attr:`acl` at this time. The API may be enhanced + in the future and is currently undocumented. Use :attr:`acl` for + managing object access control. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type permissions: list of string + :param permissions: the permissions to check + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the current bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: list of string + :returns: the permissions returned by the ``testIamPermissions`` API + request. + """ + with create_trace_span(name="Storage.Blob.testIamPermissions"): + client = self._require_client(client) + query_params = {"permissions": permissions} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + path = f"{self.path}/iam/testPermissions" + resp = client._get_resource( + path, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + + return resp.get("permissions", []) + + def make_public( + self, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + ): + """Update blob's ACL, granting read access to anonymous users. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the blob's bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.Blob.makePublic"): + self.acl.all().grant_read() + self.acl.save( + client=client, + timeout=timeout, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + def make_private( + self, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + ): + """Update blob's ACL, revoking read access for anonymous users. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the blob's bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.Blob.makePrivate"): + self.acl.all().revoke_read() + self.acl.save( + client=client, + timeout=timeout, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + def compose( + self, + sources, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_generation_match=None, + if_metageneration_match=None, + if_source_generation_match=None, + retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED, + ): + """Concatenate source blobs into this one. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/objects/compose) + and a [code sample](https://cloud.google.com/storage/docs/samples/storage-compose-file#storage_compose_file-python). + + :type sources: list of :class:`Blob` + :param sources: Blobs whose contents will be composed into this blob. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_generation_match: long + :param if_generation_match: + (Optional) Makes the operation conditional on whether the + destination object's current generation matches the given value. + Setting to 0 makes the operation succeed only if there are no live + versions of the object. + Note: In a previous version, this argument worked identically to the + ``if_source_generation_match`` argument. For + backwards-compatibility reasons, if a list is passed in, + this argument will behave like ``if_source_generation_match`` + and also issue a DeprecationWarning. + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) Makes the operation conditional on whether the + destination object's current metageneration matches the given + value. + + If a list of long is passed in, no match operation will be + performed. (Deprecated: type(list of long) is supported for + backwards-compatability reasons only.) + + :type if_source_generation_match: list of long + :param if_source_generation_match: + (Optional) Makes the operation conditional on whether the current + generation of each source blob matches the corresponding generation. + The list must match ``sources`` item-to-item. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. + The default value is ``DEFAULT_RETRY_IF_GENERATION_SPECIFIED``, a conditional retry + policy which will only enable retries if ``if_generation_match`` or ``generation`` + is set, in order to ensure requests are idempotent before retrying them. + Change the value to ``DEFAULT_RETRY`` or another `google.api_core.retry.Retry` object + to enable retries regardless of generation precondition setting. + See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + """ + with create_trace_span(name="Storage.Blob.compose"): + sources_len = len(sources) + client = self._require_client(client) + query_params = {} + + if isinstance(if_generation_match, list): + warnings.warn( + _COMPOSE_IF_GENERATION_LIST_DEPRECATED, + DeprecationWarning, + stacklevel=2, + ) + + if if_source_generation_match is not None: + raise ValueError( + _COMPOSE_IF_GENERATION_LIST_AND_IF_SOURCE_GENERATION_ERROR + ) + + if_source_generation_match = if_generation_match + if_generation_match = None + + if isinstance(if_metageneration_match, list): + warnings.warn( + _COMPOSE_IF_METAGENERATION_LIST_DEPRECATED, + DeprecationWarning, + stacklevel=2, + ) + + if_metageneration_match = None + + if if_source_generation_match is None: + if_source_generation_match = [None] * sources_len + if len(if_source_generation_match) != sources_len: + raise ValueError(_COMPOSE_IF_SOURCE_GENERATION_MISMATCH_ERROR) + + source_objects = [] + for source, source_generation in zip(sources, if_source_generation_match): + source_object = { + "name": source.name, + "generation": source.generation, + } + + preconditions = {} + if source_generation is not None: + preconditions["ifGenerationMatch"] = source_generation + + if preconditions: + source_object["objectPreconditions"] = preconditions + + source_objects.append(source_object) + + request = { + "sourceObjects": source_objects, + "destination": self._properties.copy(), + } + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_metageneration_match=if_metageneration_match, + ) + + api_response = client._post_resource( + f"{self.path}/compose", + request, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=self, + ) + self._set_properties(api_response) + + def rewrite( + self, + source, + token=None, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + if_source_generation_match=None, + if_source_generation_not_match=None, + if_source_metageneration_match=None, + if_source_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED, + ): + """Rewrite source blob into this one. + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + .. note:: + + ``rewrite`` is not supported in a ``Batch`` context. + + :type source: :class:`Blob` + :param source: blob whose contents will be rewritten into this blob. + + :type token: str + :param token: + (Optional) Token returned from an earlier, not-completed call to + rewrite the same source blob. If passed, result will include + updated status, total bytes written. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_source_generation_match: long + :param if_source_generation_match: + (Optional) Makes the operation conditional on whether the source + object's generation matches the given value. + + :type if_source_generation_not_match: long + :param if_source_generation_not_match: + (Optional) Makes the operation conditional on whether the source + object's generation does not match the given value. + + :type if_source_metageneration_match: long + :param if_source_metageneration_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration matches the given value. + + :type if_source_metageneration_not_match: long + :param if_source_metageneration_not_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration does not match the given value. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. + The default value is ``DEFAULT_RETRY_IF_GENERATION_SPECIFIED``, a conditional retry + policy which will only enable retries if ``if_generation_match`` or ``generation`` + is set, in order to ensure requests are idempotent before retrying them. + Change the value to ``DEFAULT_RETRY`` or another `google.api_core.retry.Retry` object + to enable retries regardless of generation precondition setting. + See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + + :rtype: tuple + :returns: ``(token, bytes_rewritten, total_bytes)``, where ``token`` + is a rewrite token (``None`` if the rewrite is complete), + ``bytes_rewritten`` is the number of bytes rewritten so far, + and ``total_bytes`` is the total number of bytes to be + rewritten. + """ + with create_trace_span(name="Storage.Blob.rewrite"): + client = self._require_client(client) + headers = _get_encryption_headers(self._encryption_key) + headers.update(_get_encryption_headers(source._encryption_key, source=True)) + + query_params = self._query_params + if "generation" in query_params: + del query_params["generation"] + + if token: + query_params["rewriteToken"] = token + + if source.generation: + query_params["sourceGeneration"] = source.generation + + # When a Customer Managed Encryption Key is used to encrypt Cloud Storage object + # at rest, object resource metadata will store the version of the Key Management + # Service cryptographic material. If a Blob instance with KMS Key metadata set is + # used to rewrite the object, then the existing kmsKeyName version + # value can't be used in the rewrite request and the client instead ignores it. + if ( + self.kms_key_name is not None + and "cryptoKeyVersions" not in self.kms_key_name + ): + query_params["destinationKmsKeyName"] = self.kms_key_name + + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + if_source_generation_match=if_source_generation_match, + if_source_generation_not_match=if_source_generation_not_match, + if_source_metageneration_match=if_source_metageneration_match, + if_source_metageneration_not_match=if_source_metageneration_not_match, + ) + + path = f"{source.path}/rewriteTo{self.path}" + api_response = client._post_resource( + path, + self._properties, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=self, + ) + rewritten = int(api_response["totalBytesRewritten"]) + size = int(api_response["objectSize"]) + + # The resource key is set if and only if the API response is + # completely done. Additionally, there is no rewrite token to return + # in this case. + if api_response["done"]: + self._set_properties(api_response["resource"]) + return None, rewritten, size + + return api_response["rewriteToken"], rewritten, size + + def update_storage_class( + self, + new_class, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + if_source_generation_match=None, + if_source_generation_not_match=None, + if_source_metageneration_match=None, + if_source_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED, + ): + """Update blob's storage class via a rewrite-in-place. This helper will + wait for the rewrite to complete before returning, so it may take some + time for large files. + + See + https://cloud.google.com/storage/docs/per-object-storage-class + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type new_class: str + :param new_class: + new storage class for the object. One of: + :attr:`~google.cloud.storage.constants.NEARLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.COLDLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.ARCHIVE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.STANDARD_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.MULTI_REGIONAL_LEGACY_STORAGE_CLASS`, + or + :attr:`~google.cloud.storage.constants.REGIONAL_LEGACY_STORAGE_CLASS`. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_source_generation_match: long + :param if_source_generation_match: + (Optional) Makes the operation conditional on whether the source + object's generation matches the given value. + + :type if_source_generation_not_match: long + :param if_source_generation_not_match: + (Optional) Makes the operation conditional on whether the source + object's generation does not match the given value. + + :type if_source_metageneration_match: long + :param if_source_metageneration_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration matches the given value. + + :type if_source_metageneration_not_match: long + :param if_source_metageneration_not_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration does not match the given value. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. + The default value is ``DEFAULT_RETRY_IF_GENERATION_SPECIFIED``, a conditional retry + policy which will only enable retries if ``if_generation_match`` or ``generation`` + is set, in order to ensure requests are idempotent before retrying them. + Change the value to ``DEFAULT_RETRY`` or another `google.api_core.retry.Retry` object + to enable retries regardless of generation precondition setting. + See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + """ + with create_trace_span(name="Storage.Blob.updateStorageClass"): + # Update current blob's storage class prior to rewrite + self._patch_property("storageClass", new_class) + + # Execute consecutive rewrite operations until operation is done + token, _, _ = self.rewrite( + self, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + if_source_generation_match=if_source_generation_match, + if_source_generation_not_match=if_source_generation_not_match, + if_source_metageneration_match=if_source_metageneration_match, + if_source_metageneration_not_match=if_source_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + while token is not None: + token, _, _ = self.rewrite( + self, + token=token, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + if_source_generation_match=if_source_generation_match, + if_source_generation_not_match=if_source_generation_not_match, + if_source_metageneration_match=if_source_metageneration_match, + if_source_metageneration_not_match=if_source_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + + def open( + self, + mode="r", + chunk_size=None, + ignore_flush=None, + encoding=None, + errors=None, + newline=None, + **kwargs, + ): + r"""Create a file handler for file-like I/O to or from this blob. + + This method can be used as a context manager, just like Python's + built-in 'open()' function. + + While reading, as with other read methods, if blob.generation is not set + the most recent blob generation will be used. Because the file-like IO + reader downloads progressively in chunks, this could result in data from + multiple versions being mixed together. If this is a concern, use + either bucket.get_blob(), or blob.reload(), which will download the + latest generation number and set it; or, if the generation is known, set + it manually, for instance with bucket.blob(generation=123456). + + Checksumming (hashing) to verify data integrity is disabled for reads + using this feature because reads are implemented using request ranges, + which do not provide checksums to validate. See + https://cloud.google.com/storage/docs/hashes-etags for details. + + See a [code sample](https://github.com/googleapis/python-storage/blob/main/samples/snippets/storage_fileio_write_read.py). + + Keyword arguments to pass to the underlying API calls. + For both uploads and downloads, the following arguments are + supported: + + - ``if_generation_match`` + - ``if_generation_not_match`` + - ``if_metageneration_match`` + - ``if_metageneration_not_match`` + - ``timeout`` + - ``retry`` + + For downloads only, the following additional arguments are supported: + + - ``raw_download`` + - ``single_shot_download`` + + For uploads only, the following additional arguments are supported: + + - ``content_type`` + - ``predefined_acl`` + - ``checksum`` + + :type mode: str + :param mode: + (Optional) A mode string, as per standard Python `open()` semantics.The first + character must be 'r', to open the blob for reading, or 'w' to open + it for writing. The second character, if present, must be 't' for + (unicode) text mode, or 'b' for bytes mode. If the second character + is omitted, text mode is the default. + + :type chunk_size: long + :param chunk_size: + (Optional) For reads, the minimum number of bytes to read at a time. + If fewer bytes than the chunk_size are requested, the remainder is + buffered. For writes, the maximum number of bytes to buffer before + sending data to the server, and the size of each request when data + is sent. Writes are implemented as a "resumable upload", so + chunk_size for writes must be exactly a multiple of 256KiB as with + other resumable uploads. The default is 40 MiB. + + :type ignore_flush: bool + :param ignore_flush: + (Optional) For non text-mode writes, makes flush() do nothing + instead of raising an error. flush() without closing is not + supported by the remote service and therefore calling it normally + results in io.UnsupportedOperation. However, that behavior is + incompatible with some consumers and wrappers of file objects in + Python, such as zipfile.ZipFile or io.TextIOWrapper. Setting + ignore_flush will cause flush() to successfully do nothing, for + compatibility with those contexts. The correct way to actually flush + data to the remote server is to close() (using a context manager, + such as in the example, will cause this to happen automatically). + + :type encoding: str + :param encoding: + (Optional) For text mode only, the name of the encoding that the stream will + be decoded or encoded with. If omitted, it defaults to + locale.getpreferredencoding(False). + + :type errors: str + :param errors: + (Optional) For text mode only, an optional string that specifies how encoding + and decoding errors are to be handled. Pass 'strict' to raise a + ValueError exception if there is an encoding error (the default of + None has the same effect), or pass 'ignore' to ignore errors. (Note + that ignoring encoding errors can lead to data loss.) Other more + rarely-used options are also available; see the Python 'io' module + documentation for 'io.TextIOWrapper' for a complete list. + + :type newline: str + :param newline: + (Optional) For text mode only, controls how line endings are handled. It can + be None, '', '\n', '\r', and '\r\n'. If None, reads use "universal + newline mode" and writes use the system default. See the Python + 'io' module documentation for 'io.TextIOWrapper' for details. + + :returns: A 'BlobReader' or 'BlobWriter' from + 'google.cloud.storage.fileio', or an 'io.TextIOWrapper' around one + of those classes, depending on the 'mode' argument. + """ + with create_trace_span(name="Storage.Blob.open"): + if mode == "rb": + if encoding or errors or newline: + raise ValueError( + "encoding, errors and newline arguments are for text mode only" + ) + if ignore_flush: + raise ValueError( + "ignore_flush argument is for non-text write mode only" + ) + return BlobReader(self, chunk_size=chunk_size, **kwargs) + elif mode == "wb": + if encoding or errors or newline: + raise ValueError( + "encoding, errors and newline arguments are for text mode only" + ) + return BlobWriter( + self, + chunk_size=chunk_size, + ignore_flush=ignore_flush, + **kwargs, + ) + elif mode in ("r", "rt"): + if ignore_flush: + raise ValueError( + "ignore_flush argument is for non-text write mode only" + ) + return TextIOWrapper( + BlobReader(self, chunk_size=chunk_size, **kwargs), + encoding=encoding, + errors=errors, + newline=newline, + ) + elif mode in ("w", "wt"): + if ignore_flush is False: + raise ValueError( + "ignore_flush is required for text mode writing and " + "cannot be set to False" + ) + return TextIOWrapper( + BlobWriter( + self, chunk_size=chunk_size, ignore_flush=True, **kwargs + ), + encoding=encoding, + errors=errors, + newline=newline, + ) + else: + raise NotImplementedError( + "Supported modes strings are 'r', 'rb', 'rt', 'w', 'wb', and 'wt' only." + ) + + cache_control = _scalar_property("cacheControl") + """HTTP 'Cache-Control' header for this object. + + See [`RFC 7234`](https://tools.ietf.org/html/rfc7234#section-5.2) + and [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + :rtype: str or ``NoneType`` + + """ + + content_disposition = _scalar_property("contentDisposition") + """HTTP 'Content-Disposition' header for this object. + + See [`RFC 6266`](https://tools.ietf.org/html/rfc7234#section-5.2) and + [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + :rtype: str or ``NoneType`` + """ + + content_encoding = _scalar_property("contentEncoding") + """HTTP 'Content-Encoding' header for this object. + + See [`RFC 7231`](https://tools.ietf.org/html/rfc7231#section-3.1.2.2) and + [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + :rtype: str or ``NoneType`` + """ + + content_language = _scalar_property("contentLanguage") + """HTTP 'Content-Language' header for this object. + + See [`BCP47`](https://tools.ietf.org/html/bcp47) and + [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + :rtype: str or ``NoneType`` + """ + + content_type = _scalar_property(_CONTENT_TYPE_FIELD) + """HTTP 'Content-Type' header for this object. + + See [`RFC 2616`](https://tools.ietf.org/html/rfc2616#section-14.17) and + [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + :rtype: str or ``NoneType`` + """ + + crc32c = _scalar_property("crc32c") + """CRC32C checksum for this object. + + This returns the blob's CRC32C checksum. To retrieve the value, first use a + reload method of the Blob class which loads the blob's properties from the server. + + See [`RFC 4960`](https://tools.ietf.org/html/rfc4960#appendix-B) and + [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + If not set before upload, the server will compute the hash. + + :rtype: str or ``NoneType`` + """ + + def _prep_and_do_download( + self, + file_obj, + client=None, + start=None, + end=None, + raw_download=False, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + command=None, + ): + """Download the contents of a blob object into a file-like object. + + See https://cloud.google.com/storage/docs/downloading-objects + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type file_obj: file + :param file_obj: A file handle to which to write the blob's data. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: + (Optional) The client to use. If not passed, falls back to the + ``client`` stored on the blob's bucket. + + :type start: int + :param start: (Optional) The first byte in a range to be downloaded. + + :type end: int + :param end: (Optional) The last byte in a range to be downloaded. + + :type raw_download: bool + :param raw_download: + (Optional) If true, download the object without any expansion. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type checksum: str + :param checksum: + (Optional) The type of checksum to compute to verify the integrity + of the object. The response headers must contain a checksum of the + requested type. If the headers lack an appropriate checksum (for + instance in the case of transcoded or ranged downloads where the + remote service does not know the correct checksum, including + downloads where chunk_size is set) an INFO-level log will be + emitted. Supported values are "md5", "crc32c", "auto" and None. The + default is "auto", which will try to detect if the C extension for + crc32c is installed and fall back to md5 otherwise. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :type single_shot_download: bool + :param single_shot_download: + (Optional) If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + :type command: str + :param command: + (Optional) Information about which interface for download was used, + to be included in the X-Goog-API-Client header. Please leave as None + unless otherwise directed. + """ + # Handle ConditionalRetryPolicy. + if isinstance(retry, ConditionalRetryPolicy): + # Conditional retries are designed for non-media calls, which change + # arguments into query_params dictionaries. Media operations work + # differently, so here we make a "fake" query_params to feed to the + # ConditionalRetryPolicy. + query_params = { + "ifGenerationMatch": if_generation_match, + "ifMetagenerationMatch": if_metageneration_match, + } + retry = retry.get_retry_policy_if_conditions_met(query_params=query_params) + + client = self._require_client(client) + + download_url = self._get_download_url( + client, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + headers = _get_encryption_headers(self._encryption_key) + headers["accept-encoding"] = "gzip" + _add_etag_match_headers( + headers, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + ) + # Add any client attached custom headers to be sent with the request. + headers = { + **_get_default_headers(client._connection.user_agent, command=command), + **headers, + **client._extra_headers, + } + + transport = client._http + + try: + self._do_download( + transport, + file_obj, + download_url, + headers, + start, + end, + raw_download, + timeout=timeout, + checksum=checksum, + retry=retry, + single_shot_download=single_shot_download, + ) + except InvalidResponse as exc: + _raise_from_invalid_response(exc) + + @property + def component_count(self): + """Number of underlying components that make up this object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: int or ``NoneType`` + :returns: The component count (in case of a composed object) or + ``None`` if the blob's resource has not been loaded from + the server. This property will not be set on objects + not created via ``compose``. + """ + component_count = self._properties.get("componentCount") + if component_count is not None: + return int(component_count) + + @property + def etag(self): + """Retrieve the ETag for the object. + + See [`RFC 2616 (etags)`](https://tools.ietf.org/html/rfc2616#section-3.11) and + [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + :rtype: str or ``NoneType`` + :returns: The blob etag or ``None`` if the blob's resource has not + been loaded from the server. + """ + return self._properties.get("etag") + + event_based_hold = _scalar_property("eventBasedHold") + """Is an event-based hold active on the object? + + See [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + If the property is not set locally, returns :data:`None`. + + :rtype: bool or ``NoneType`` + """ + + @property + def generation(self): + """Retrieve the generation for the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: int or ``NoneType`` + :returns: The generation of the blob or ``None`` if the blob's + resource has not been loaded from the server. + """ + generation = self._properties.get("generation") + if generation is not None: + return int(generation) + + @property + def id(self): + """Retrieve the ID for the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + The ID consists of the bucket name, object name, and generation number. + + :rtype: str or ``NoneType`` + :returns: The ID of the blob or ``None`` if the blob's + resource has not been loaded from the server. + """ + return self._properties.get("id") + + md5_hash = _scalar_property("md5Hash") + """MD5 hash for this object. + + This returns the blob's MD5 hash. To retrieve the value, first use a + reload method of the Blob class which loads the blob's properties from the server. + + See [`RFC 1321`](https://tools.ietf.org/html/rfc1321) and + [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + If not set before upload, the server will compute the hash. + + :rtype: str or ``NoneType`` + """ + + @property + def media_link(self): + """Retrieve the media download URI for the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: str or ``NoneType`` + :returns: The media link for the blob or ``None`` if the blob's + resource has not been loaded from the server. + """ + return self._properties.get("mediaLink") + + @property + def metadata(self): + """Retrieve arbitrary/application specific metadata for the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :setter: Update arbitrary/application specific metadata for the + object. + :getter: Retrieve arbitrary/application specific metadata for + the object. + + :rtype: dict or ``NoneType`` + :returns: The metadata associated with the blob or ``None`` if the + property is not set. + """ + return copy.deepcopy(self._properties.get("metadata")) + + @metadata.setter + def metadata(self, value): + """Update arbitrary/application specific metadata for the object. + + Values are stored to GCS as strings. To delete a key, set its value to + None and call blob.patch(). + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :type value: dict + :param value: The blob metadata to set. + """ + if value is not None: + value = {k: str(v) if v is not None else None for k, v in value.items()} + self._patch_property("metadata", value) + + @property + def metageneration(self): + """Retrieve the metageneration for the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: int or ``NoneType`` + :returns: The metageneration of the blob or ``None`` if the blob's + resource has not been loaded from the server. + """ + metageneration = self._properties.get("metageneration") + if metageneration is not None: + return int(metageneration) + + @property + def owner(self): + """Retrieve info about the owner of the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: dict or ``NoneType`` + :returns: Mapping of owner's role/ID, or ``None`` if the blob's + resource has not been loaded from the server. + """ + return copy.deepcopy(self._properties.get("owner")) + + @property + def retention_expiration_time(self): + """Retrieve timestamp at which the object's retention period expires. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the property is not set locally. + """ + value = self._properties.get("retentionExpirationTime") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def self_link(self): + """Retrieve the URI for the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: str or ``NoneType`` + :returns: The self link for the blob or ``None`` if the blob's + resource has not been loaded from the server. + """ + return self._properties.get("selfLink") + + @property + def size(self): + """Size of the object, in bytes. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: int or ``NoneType`` + :returns: The size of the blob or ``None`` if the blob's + resource has not been loaded from the server. + """ + size = self._properties.get("size") + if size is not None: + return int(size) + + @property + def kms_key_name(self): + """Resource name of Cloud KMS key used to encrypt the blob's contents. + + :rtype: str or ``NoneType`` + :returns: + The resource name or ``None`` if no Cloud KMS key was used, + or the blob's resource has not been loaded from the server. + """ + return self._properties.get("kmsKeyName") + + @kms_key_name.setter + def kms_key_name(self, value): + """Set KMS encryption key for object. + + :type value: str or ``NoneType`` + :param value: new KMS key name (None to clear any existing key). + """ + self._patch_property("kmsKeyName", value) + + storage_class = _scalar_property("storageClass") + """Retrieve the storage class for the object. + + This can only be set at blob / object **creation** time. If you'd + like to change the storage class **after** the blob / object already + exists in a bucket, call :meth:`update_storage_class` (which uses + :meth:`rewrite`). + + See https://cloud.google.com/storage/docs/storage-classes + + :rtype: str or ``NoneType`` + :returns: + If set, one of + :attr:`~google.cloud.storage.constants.STANDARD_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.NEARLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.COLDLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.ARCHIVE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.MULTI_REGIONAL_LEGACY_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.REGIONAL_LEGACY_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.DURABLE_REDUCED_AVAILABILITY_STORAGE_CLASS`, + else ``None``. + """ + + temporary_hold = _scalar_property("temporaryHold") + """Is a temporary hold active on the object? + + See [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects). + + If the property is not set locally, returns :data:`None`. + + :rtype: bool or ``NoneType`` + """ + + @property + def time_deleted(self): + """Retrieve the timestamp at which the object was deleted. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the blob's resource has not been loaded from + the server (see :meth:`reload`). If the blob has + not been deleted, this will never be set. + """ + value = self._properties.get("timeDeleted") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def time_created(self): + """Retrieve the timestamp at which the object was created. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the blob's resource has not been loaded from + the server (see :meth:`reload`). + """ + value = self._properties.get("timeCreated") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def updated(self): + """Retrieve the timestamp at which the object was updated. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the blob's resource has not been loaded from + the server (see :meth:`reload`). + """ + value = self._properties.get("updated") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def custom_time(self): + """Retrieve the custom time for the object. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the blob's resource has not been loaded from + the server (see :meth:`reload`). + """ + value = self._properties.get("customTime") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @custom_time.setter + def custom_time(self, value): + """Set the custom time for the object. + + Once set on the server side object, this value can't be unset, but may + only changed to a custom datetime in the future. + + If :attr:`custom_time` must be unset, either perform a rewrite + operation or upload the data again. + + See https://cloud.google.com/storage/docs/json_api/v1/objects + + :type value: :class:`datetime.datetime` + :param value: new value + """ + if value is not None: + value = _datetime_to_rfc3339(value) + + self._patch_property("customTime", value) + + @property + def retention(self): + """Retrieve the retention configuration for this object. + + :rtype: :class:`Retention` + :returns: an instance for managing the object's retention configuration. + """ + info = self._properties.get("retention", {}) + return Retention.from_api_repr(info, self) + + @property + def soft_delete_time(self): + """If this object has been soft-deleted, returns the time at which it became soft-deleted. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: + (readonly) The time that the object became soft-deleted. + Note this property is only set for soft-deleted objects. + """ + soft_delete_time = self._properties.get("softDeleteTime") + if soft_delete_time is not None: + return _rfc3339_nanos_to_datetime(soft_delete_time) + + @property + def hard_delete_time(self): + """If this object has been soft-deleted, returns the time at which it will be permanently deleted. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: + (readonly) The time that the object will be permanently deleted. + Note this property is only set for soft-deleted objects. + """ + hard_delete_time = self._properties.get("hardDeleteTime") + if hard_delete_time is not None: + return _rfc3339_nanos_to_datetime(hard_delete_time) + + @property + def finalized_time(self): + """If this object has been soft-deleted, returns the time at which it will be permanently deleted. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: + (readonly) The time that the object will be permanently deleted. + Note this property is only set for soft-deleted objects. + """ + finalize_time = self._properties.get("finalizedTime", None) + if finalize_time is not None: + return _rfc3339_nanos_to_datetime(finalize_time) + + +def _get_host_name(connection): + """Returns the host name from the given connection. + + :type connection: :class:`~google.cloud.storage._http.Connection` + :param connection: The connection object. + + :rtype: str + :returns: The host name. + """ + # TODO: After google-cloud-core 1.6.0 is stable and we upgrade it + # to 1.6.0 in setup.py, we no longer need to check the attribute + # existence. We can simply return connection.get_api_base_url_for_mtls(). + return ( + connection.API_BASE_URL + if not hasattr(connection, "get_api_base_url_for_mtls") + else connection.get_api_base_url_for_mtls() + ) + + +def _get_encryption_headers(key, source=False): + """Builds customer encryption key headers + + :type key: bytes + :param key: 32 byte key to build request key and hash. + + :type source: bool + :param source: If true, return headers for the "source" blob; otherwise, + return headers for the "destination" blob. + + :rtype: dict + :returns: dict of HTTP headers being sent in request. + """ + if key is None: + return {} + + key = _to_bytes(key) + key_hash = hashlib.sha256(key).digest() + key_hash = base64.b64encode(key_hash) + key = base64.b64encode(key) + + if source: + prefix = "X-Goog-Copy-Source-Encryption-" + else: + prefix = "X-Goog-Encryption-" + + return { + prefix + "Algorithm": "AES256", + prefix + "Key": _bytes_to_unicode(key), + prefix + "Key-Sha256": _bytes_to_unicode(key_hash), + } + + +def _quote(value, safe=b"~"): + """URL-quote a string. + + If the value is unicode, this method first UTF-8 encodes it as bytes and + then quotes the bytes. (In Python 3, ``urllib.parse.quote`` does this + encoding automatically, but in Python 2, non-ASCII characters cannot be + quoted.) + + :type value: str or bytes + :param value: The value to be URL-quoted. + + :type safe: bytes + :param safe: Bytes *not* to be quoted. By default, includes only ``b'~'``. + + :rtype: str + :returns: The encoded value (bytes in Python 2, unicode in Python 3). + """ + value = _to_bytes(value, encoding="utf-8") + return quote(value, safe=safe) + + +def _maybe_rewind(stream, rewind=False): + """Rewind the stream if desired. + + :type stream: IO[bytes] + :param stream: A bytes IO object open for reading. + + :type rewind: bool + :param rewind: Indicates if we should seek to the beginning of the stream. + """ + if rewind: + stream.seek(0, os.SEEK_SET) + + +def _raise_from_invalid_response(error): + """Re-wrap and raise an ``InvalidResponse`` exception. + + :type error: :exc:`google.cloud.storage.exceptions.InvalidResponse` + :param error: A caught exception from the ``google-resumable-media`` + library. + + :raises: :class:`~google.cloud.exceptions.GoogleCloudError` corresponding + to the failed status code + """ + response = error.response + + # The 'response.text' gives the actual reason of error, where 'error' gives + # the message of expected status code. + if response.text: + error_message = response.text + ": " + str(error) + else: + error_message = str(error) + + message = f"{response.request.method} {response.request.url}: {error_message}" + + raise exceptions.from_http_status(response.status_code, message, response=response) + + +def _add_query_parameters(base_url, name_value_pairs): + """Add one query parameter to a base URL. + + :type base_url: string + :param base_url: Base URL (may already contain query parameters) + + :type name_value_pairs: list of (string, string) tuples. + :param name_value_pairs: Names and values of the query parameters to add + + :rtype: string + :returns: URL with additional query strings appended. + """ + if len(name_value_pairs) == 0: + return base_url + + scheme, netloc, path, query, frag = urlsplit(base_url) + query = parse_qsl(query) + query.extend(name_value_pairs) + return urlunsplit((scheme, netloc, path, urlencode(query), frag)) + + +class Retention(dict): + """Map an object's retention configuration. + + :type blob: :class:`Blob` + :params blob: blob for which this retention configuration applies to. + + :type mode: str or ``NoneType`` + :params mode: + (Optional) The mode of the retention configuration, which can be either Unlocked or Locked. + See: https://cloud.google.com/storage/docs/object-lock + + :type retain_until_time: :class:`datetime.datetime` or ``NoneType`` + :params retain_until_time: + (Optional) The earliest time that the object can be deleted or replaced, which is the + retention configuration set for this object. + + :type retention_expiration_time: :class:`datetime.datetime` or ``NoneType`` + :params retention_expiration_time: + (Optional) The earliest time that the object can be deleted, which depends on any + retention configuration set for the object and any retention policy set for the bucket + that contains the object. This value should normally only be set by the back-end API. + """ + + def __init__( + self, + blob, + mode=None, + retain_until_time=None, + retention_expiration_time=None, + ): + data = {"mode": mode} + if retain_until_time is not None: + retain_until_time = _datetime_to_rfc3339(retain_until_time) + data["retainUntilTime"] = retain_until_time + + if retention_expiration_time is not None: + retention_expiration_time = _datetime_to_rfc3339(retention_expiration_time) + data["retentionExpirationTime"] = retention_expiration_time + + super(Retention, self).__init__(data) + self._blob = blob + + @classmethod + def from_api_repr(cls, resource, blob): + """Factory: construct instance from resource. + + :type blob: :class:`Blob` + :params blob: Blob for which this retention configuration applies to. + + :type resource: dict + :param resource: mapping as returned from API call. + + :rtype: :class:`Retention` + :returns: Retention configuration created from resource. + """ + instance = cls(blob) + instance.update(resource) + return instance + + @property + def blob(self): + """Blob for which this retention configuration applies to. + + :rtype: :class:`Blob` + :returns: the instance's blob. + """ + return self._blob + + @property + def mode(self): + """The mode of the retention configuration. Options are 'Unlocked' or 'Locked'. + + :rtype: string + :returns: The mode of the retention configuration, which can be either set to 'Unlocked' or 'Locked'. + """ + return self.get("mode") + + @mode.setter + def mode(self, value): + self["mode"] = value + self.blob._patch_property("retention", self) + + @property + def retain_until_time(self): + """The earliest time that the object can be deleted or replaced, which is the + retention configuration set for this object. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the blob's resource has not been loaded from + the server (see :meth:`reload`). + """ + value = self.get("retainUntilTime") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @retain_until_time.setter + def retain_until_time(self, value): + """Set the retain_until_time for the object retention configuration. + + :type value: :class:`datetime.datetime` + :param value: The earliest time that the object can be deleted or replaced. + """ + if value is not None: + value = _datetime_to_rfc3339(value) + self["retainUntilTime"] = value + self.blob._patch_property("retention", self) + + @property + def retention_expiration_time(self): + """The earliest time that the object can be deleted, which depends on any + retention configuration set for the object and any retention policy set for + the bucket that contains the object. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: + (readonly) The earliest time that the object can be deleted. + """ + retention_expiration_time = self.get("retentionExpirationTime") + if retention_expiration_time is not None: + return _rfc3339_nanos_to_datetime(retention_expiration_time) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/bucket.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..b4001e09df7310b85cef21a599a3041881970977 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/bucket.py @@ -0,0 +1,4342 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Create / interact with Google Cloud Storage buckets.""" + +import base64 +import copy +import datetime +import json +from urllib.parse import urlsplit +import warnings + +from google.api_core import datetime_helpers +from google.cloud._helpers import _datetime_to_rfc3339 +from google.cloud._helpers import _rfc3339_nanos_to_datetime +from google.cloud.exceptions import NotFound +from google.api_core.iam import Policy +from google.cloud.storage import _signing +from google.cloud.storage._helpers import _add_etag_match_headers +from google.cloud.storage._helpers import _add_generation_match_parameters +from google.cloud.storage._helpers import _NOW +from google.cloud.storage._helpers import _PropertyMixin +from google.cloud.storage._helpers import _UTC +from google.cloud.storage._helpers import _scalar_property +from google.cloud.storage._helpers import _validate_name +from google.cloud.storage._signing import generate_signed_url_v2 +from google.cloud.storage._signing import generate_signed_url_v4 +from google.cloud.storage._helpers import _bucket_bound_hostname_url +from google.cloud.storage._helpers import _virtual_hosted_style_base_url +from google.cloud.storage._opentelemetry_tracing import create_trace_span +from google.cloud.storage.acl import BucketACL +from google.cloud.storage.acl import DefaultObjectACL +from google.cloud.storage.blob import _quote +from google.cloud.storage.blob import Blob +from google.cloud.storage.constants import ( + _DEFAULT_TIMEOUT, + ENFORCEMENT_MODE_FULLY_RESTRICTED, + ENFORCEMENT_MODE_NOT_RESTRICTED, +) +from google.cloud.storage.constants import ARCHIVE_STORAGE_CLASS +from google.cloud.storage.constants import COLDLINE_STORAGE_CLASS +from google.cloud.storage.constants import DUAL_REGION_LOCATION_TYPE +from google.cloud.storage.constants import ( + DURABLE_REDUCED_AVAILABILITY_LEGACY_STORAGE_CLASS, +) +from google.cloud.storage.constants import MULTI_REGIONAL_LEGACY_STORAGE_CLASS +from google.cloud.storage.constants import MULTI_REGION_LOCATION_TYPE +from google.cloud.storage.constants import NEARLINE_STORAGE_CLASS +from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_INHERITED +from google.cloud.storage.constants import REGIONAL_LEGACY_STORAGE_CLASS +from google.cloud.storage.constants import REGION_LOCATION_TYPE +from google.cloud.storage.constants import STANDARD_STORAGE_CLASS +from google.cloud.storage.ip_filter import IPFilter +from google.cloud.storage.notification import BucketNotification +from google.cloud.storage.notification import NONE_PAYLOAD_FORMAT +from google.cloud.storage.retry import DEFAULT_RETRY +from google.cloud.storage.retry import DEFAULT_RETRY_IF_GENERATION_SPECIFIED +from google.cloud.storage.retry import DEFAULT_RETRY_IF_ETAG_IN_JSON +from google.cloud.storage.retry import DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED + +_UBLA_BPO_ENABLED_MESSAGE = ( + "Pass only one of 'uniform_bucket_level_access_enabled' / " + "'bucket_policy_only_enabled' to 'IAMConfiguration'." +) +_BPO_ENABLED_MESSAGE = ( + "'IAMConfiguration.bucket_policy_only_enabled' is deprecated. " + "Instead, use 'IAMConfiguration.uniform_bucket_level_access_enabled'." +) +_UBLA_BPO_LOCK_TIME_MESSAGE = ( + "Pass only one of 'uniform_bucket_level_access_lock_time' / " + "'bucket_policy_only_lock_time' to 'IAMConfiguration'." +) +_BPO_LOCK_TIME_MESSAGE = ( + "'IAMConfiguration.bucket_policy_only_lock_time' is deprecated. " + "Instead, use 'IAMConfiguration.uniform_bucket_level_access_lock_time'." +) +_LOCATION_SETTER_MESSAGE = ( + "Assignment to 'Bucket.location' is deprecated, as it is only " + "valid before the bucket is created. Instead, pass the location " + "to `Bucket.create`." +) +_FROM_STRING_MESSAGE = ( + "Bucket.from_string() is deprecated. " "Use Bucket.from_uri() instead." +) +_IP_FILTER_PROPERTY = "ipFilter" + + +def _blobs_page_start(iterator, page, response): + """Grab prefixes after a :class:`~google.cloud.iterator.Page` started. + + :type iterator: :class:`~google.api_core.page_iterator.Iterator` + :param iterator: The iterator that is currently in use. + + :type page: :class:`~google.cloud.api.core.page_iterator.Page` + :param page: The page that was just created. + + :type response: dict + :param response: The JSON API response for a page of blobs. + """ + page.prefixes = tuple(response.get("prefixes", ())) + iterator.prefixes.update(page.prefixes) + + +def _item_to_blob(iterator, item): + """Convert a JSON blob to the native object. + + .. note:: + + This assumes that the ``bucket`` attribute has been + added to the iterator after being created. + + :type iterator: :class:`~google.api_core.page_iterator.Iterator` + :param iterator: The iterator that has retrieved the item. + + :type item: dict + :param item: An item to be converted to a blob. + + :rtype: :class:`.Blob` + :returns: The next blob in the page. + """ + name = item.get("name") + blob = Blob(name, bucket=iterator.bucket) + blob._set_properties(item) + return blob + + +def _item_to_notification(iterator, item): + """Convert a JSON blob to the native object. + + .. note:: + + This assumes that the ``bucket`` attribute has been + added to the iterator after being created. + + :type iterator: :class:`~google.api_core.page_iterator.Iterator` + :param iterator: The iterator that has retrieved the item. + + :type item: dict + :param item: An item to be converted to a blob. + + :rtype: :class:`.BucketNotification` + :returns: The next notification being iterated. + """ + return BucketNotification.from_api_repr(item, bucket=iterator.bucket) + + +class LifecycleRuleConditions(dict): + """Map a single lifecycle rule for a bucket. + + See: https://cloud.google.com/storage/docs/lifecycle + + :type age: int + :param age: (Optional) Apply rule action to items whose age, in days, + exceeds this value. + + :type created_before: datetime.date + :param created_before: (Optional) Apply rule action to items created + before this date. + + :type is_live: bool + :param is_live: (Optional) If true, apply rule action to non-versioned + items, or to items with no newer versions. If false, apply + rule action to versioned items with at least one newer + version. + + :type matches_prefix: list(str) + :param matches_prefix: (Optional) Apply rule action to items which + any prefix matches the beginning of the item name. + + :type matches_storage_class: list(str), one or more of + :attr:`Bucket.STORAGE_CLASSES`. + :param matches_storage_class: (Optional) Apply rule action to items + whose storage class matches this value. + + :type matches_suffix: list(str) + :param matches_suffix: (Optional) Apply rule action to items which + any suffix matches the end of the item name. + + :type number_of_newer_versions: int + :param number_of_newer_versions: (Optional) Apply rule action to versioned + items having N newer versions. + + :type days_since_custom_time: int + :param days_since_custom_time: (Optional) Apply rule action to items whose number of days + elapsed since the custom timestamp. This condition is relevant + only for versioned objects. The value of the field must be a non + negative integer. If it's zero, the object version will become + eligible for lifecycle action as soon as it becomes custom. + + :type custom_time_before: :class:`datetime.date` + :param custom_time_before: (Optional) Date object parsed from RFC3339 valid date, apply rule action + to items whose custom time is before this date. This condition is relevant + only for versioned objects, e.g., 2019-03-16. + + :type days_since_noncurrent_time: int + :param days_since_noncurrent_time: (Optional) Apply rule action to items whose number of days + elapsed since the non current timestamp. This condition + is relevant only for versioned objects. The value of the field + must be a non negative integer. If it's zero, the object version + will become eligible for lifecycle action as soon as it becomes + non current. + + :type noncurrent_time_before: :class:`datetime.date` + :param noncurrent_time_before: (Optional) Date object parsed from RFC3339 valid date, apply + rule action to items whose non current time is before this date. + This condition is relevant only for versioned objects, e.g, 2019-03-16. + + :raises ValueError: if no arguments are passed. + """ + + def __init__( + self, + age=None, + created_before=None, + is_live=None, + matches_storage_class=None, + number_of_newer_versions=None, + days_since_custom_time=None, + custom_time_before=None, + days_since_noncurrent_time=None, + noncurrent_time_before=None, + matches_prefix=None, + matches_suffix=None, + _factory=False, + ): + conditions = {} + + if age is not None: + conditions["age"] = age + + if created_before is not None: + conditions["createdBefore"] = created_before.isoformat() + + if is_live is not None: + conditions["isLive"] = is_live + + if matches_storage_class is not None: + conditions["matchesStorageClass"] = matches_storage_class + + if number_of_newer_versions is not None: + conditions["numNewerVersions"] = number_of_newer_versions + + if days_since_custom_time is not None: + conditions["daysSinceCustomTime"] = days_since_custom_time + + if custom_time_before is not None: + conditions["customTimeBefore"] = custom_time_before.isoformat() + + if days_since_noncurrent_time is not None: + conditions["daysSinceNoncurrentTime"] = days_since_noncurrent_time + + if noncurrent_time_before is not None: + conditions["noncurrentTimeBefore"] = noncurrent_time_before.isoformat() + + if matches_prefix is not None: + conditions["matchesPrefix"] = matches_prefix + + if matches_suffix is not None: + conditions["matchesSuffix"] = matches_suffix + + if not _factory and not conditions: + raise ValueError("Supply at least one condition") + + super(LifecycleRuleConditions, self).__init__(conditions) + + @classmethod + def from_api_repr(cls, resource): + """Factory: construct instance from resource. + + :type resource: dict + :param resource: mapping as returned from API call. + + :rtype: :class:`LifecycleRuleConditions` + :returns: Instance created from resource. + """ + instance = cls(_factory=True) + instance.update(resource) + return instance + + @property + def age(self): + """Conditon's age value.""" + return self.get("age") + + @property + def created_before(self): + """Conditon's created_before value.""" + before = self.get("createdBefore") + if before is not None: + return datetime_helpers.from_iso8601_date(before) + + @property + def is_live(self): + """Conditon's 'is_live' value.""" + return self.get("isLive") + + @property + def matches_prefix(self): + """Conditon's 'matches_prefix' value.""" + return self.get("matchesPrefix") + + @property + def matches_storage_class(self): + """Conditon's 'matches_storage_class' value.""" + return self.get("matchesStorageClass") + + @property + def matches_suffix(self): + """Conditon's 'matches_suffix' value.""" + return self.get("matchesSuffix") + + @property + def number_of_newer_versions(self): + """Conditon's 'number_of_newer_versions' value.""" + return self.get("numNewerVersions") + + @property + def days_since_custom_time(self): + """Conditon's 'days_since_custom_time' value.""" + return self.get("daysSinceCustomTime") + + @property + def custom_time_before(self): + """Conditon's 'custom_time_before' value.""" + before = self.get("customTimeBefore") + if before is not None: + return datetime_helpers.from_iso8601_date(before) + + @property + def days_since_noncurrent_time(self): + """Conditon's 'days_since_noncurrent_time' value.""" + return self.get("daysSinceNoncurrentTime") + + @property + def noncurrent_time_before(self): + """Conditon's 'noncurrent_time_before' value.""" + before = self.get("noncurrentTimeBefore") + if before is not None: + return datetime_helpers.from_iso8601_date(before) + + +class LifecycleRuleDelete(dict): + """Map a lifecycle rule deleting matching items. + + :type kw: dict + :params kw: arguments passed to :class:`LifecycleRuleConditions`. + """ + + def __init__(self, **kw): + conditions = LifecycleRuleConditions(**kw) + rule = {"action": {"type": "Delete"}, "condition": dict(conditions)} + super().__init__(rule) + + @classmethod + def from_api_repr(cls, resource): + """Factory: construct instance from resource. + + :type resource: dict + :param resource: mapping as returned from API call. + + :rtype: :class:`LifecycleRuleDelete` + :returns: Instance created from resource. + """ + instance = cls(_factory=True) + instance.update(resource) + return instance + + +class LifecycleRuleSetStorageClass(dict): + """Map a lifecycle rule updating storage class of matching items. + + :type storage_class: str, one of :attr:`Bucket.STORAGE_CLASSES`. + :param storage_class: new storage class to assign to matching items. + + :type kw: dict + :params kw: arguments passed to :class:`LifecycleRuleConditions`. + """ + + def __init__(self, storage_class, **kw): + conditions = LifecycleRuleConditions(**kw) + rule = { + "action": { + "type": "SetStorageClass", + "storageClass": storage_class, + }, + "condition": dict(conditions), + } + super().__init__(rule) + + @classmethod + def from_api_repr(cls, resource): + """Factory: construct instance from resource. + + :type resource: dict + :param resource: mapping as returned from API call. + + :rtype: :class:`LifecycleRuleSetStorageClass` + :returns: Instance created from resource. + """ + action = resource["action"] + instance = cls(action["storageClass"], _factory=True) + instance.update(resource) + return instance + + +class LifecycleRuleAbortIncompleteMultipartUpload(dict): + """Map a rule aborting incomplete multipart uploads of matching items. + + The "age" lifecycle condition is the only supported condition for this rule. + + :type kw: dict + :params kw: arguments passed to :class:`LifecycleRuleConditions`. + """ + + def __init__(self, **kw): + conditions = LifecycleRuleConditions(**kw) + rule = { + "action": {"type": "AbortIncompleteMultipartUpload"}, + "condition": dict(conditions), + } + super().__init__(rule) + + @classmethod + def from_api_repr(cls, resource): + """Factory: construct instance from resource. + + :type resource: dict + :param resource: mapping as returned from API call. + + :rtype: :class:`LifecycleRuleAbortIncompleteMultipartUpload` + :returns: Instance created from resource. + """ + instance = cls(_factory=True) + instance.update(resource) + return instance + + +_default = object() + + +class IAMConfiguration(dict): + """Map a bucket's IAM configuration. + + :type bucket: :class:`Bucket` + :params bucket: Bucket for which this instance is the policy. + + :type public_access_prevention: str + :params public_access_prevention: + (Optional) Whether the public access prevention policy is 'inherited' (default) or 'enforced' + See: https://cloud.google.com/storage/docs/public-access-prevention + + :type uniform_bucket_level_access_enabled: bool + :params bucket_policy_only_enabled: + (Optional) Whether the IAM-only policy is enabled for the bucket. + + :type uniform_bucket_level_access_locked_time: :class:`datetime.datetime` + :params uniform_bucket_level_locked_time: + (Optional) When the bucket's IAM-only policy was enabled. + This value should normally only be set by the back-end API. + + :type bucket_policy_only_enabled: bool + :params bucket_policy_only_enabled: + Deprecated alias for :data:`uniform_bucket_level_access_enabled`. + + :type bucket_policy_only_locked_time: :class:`datetime.datetime` + :params bucket_policy_only_locked_time: + Deprecated alias for :data:`uniform_bucket_level_access_locked_time`. + """ + + def __init__( + self, + bucket, + public_access_prevention=_default, + uniform_bucket_level_access_enabled=_default, + uniform_bucket_level_access_locked_time=_default, + bucket_policy_only_enabled=_default, + bucket_policy_only_locked_time=_default, + ): + if bucket_policy_only_enabled is not _default: + if uniform_bucket_level_access_enabled is not _default: + raise ValueError(_UBLA_BPO_ENABLED_MESSAGE) + + warnings.warn(_BPO_ENABLED_MESSAGE, DeprecationWarning, stacklevel=2) + uniform_bucket_level_access_enabled = bucket_policy_only_enabled + + if bucket_policy_only_locked_time is not _default: + if uniform_bucket_level_access_locked_time is not _default: + raise ValueError(_UBLA_BPO_LOCK_TIME_MESSAGE) + + warnings.warn(_BPO_LOCK_TIME_MESSAGE, DeprecationWarning, stacklevel=2) + uniform_bucket_level_access_locked_time = bucket_policy_only_locked_time + + if uniform_bucket_level_access_enabled is _default: + uniform_bucket_level_access_enabled = False + + if public_access_prevention is _default: + public_access_prevention = PUBLIC_ACCESS_PREVENTION_INHERITED + + data = { + "uniformBucketLevelAccess": { + "enabled": uniform_bucket_level_access_enabled + }, + "publicAccessPrevention": public_access_prevention, + } + if uniform_bucket_level_access_locked_time is not _default: + data["uniformBucketLevelAccess"]["lockedTime"] = _datetime_to_rfc3339( + uniform_bucket_level_access_locked_time + ) + super(IAMConfiguration, self).__init__(data) + self._bucket = bucket + + @classmethod + def from_api_repr(cls, resource, bucket): + """Factory: construct instance from resource. + + :type bucket: :class:`Bucket` + :params bucket: Bucket for which this instance is the policy. + + :type resource: dict + :param resource: mapping as returned from API call. + + :rtype: :class:`IAMConfiguration` + :returns: Instance created from resource. + """ + instance = cls(bucket) + instance.update(resource) + return instance + + @property + def bucket(self): + """Bucket for which this instance is the policy. + + :rtype: :class:`Bucket` + :returns: the instance's bucket. + """ + return self._bucket + + @property + def public_access_prevention(self): + """Setting for public access prevention policy. Options are 'inherited' (default) or 'enforced'. + + See: https://cloud.google.com/storage/docs/public-access-prevention + + :rtype: string + :returns: the public access prevention status, either 'enforced' or 'inherited'. + """ + return self["publicAccessPrevention"] + + @public_access_prevention.setter + def public_access_prevention(self, value): + self["publicAccessPrevention"] = value + self.bucket._patch_property("iamConfiguration", self) + + @property + def uniform_bucket_level_access_enabled(self): + """If set, access checks only use bucket-level IAM policies or above. + + :rtype: bool + :returns: whether the bucket is configured to allow only IAM. + """ + ubla = self.get("uniformBucketLevelAccess", {}) + return ubla.get("enabled", False) + + @uniform_bucket_level_access_enabled.setter + def uniform_bucket_level_access_enabled(self, value): + ubla = self.setdefault("uniformBucketLevelAccess", {}) + ubla["enabled"] = bool(value) + self.bucket._patch_property("iamConfiguration", self) + + @property + def uniform_bucket_level_access_locked_time(self): + """Deadline for changing :attr:`uniform_bucket_level_access_enabled` from true to false. + + If the bucket's :attr:`uniform_bucket_level_access_enabled` is true, this property + is time time after which that setting becomes immutable. + + If the bucket's :attr:`uniform_bucket_level_access_enabled` is false, this property + is ``None``. + + :rtype: Union[:class:`datetime.datetime`, None] + :returns: (readonly) Time after which :attr:`uniform_bucket_level_access_enabled` will + be frozen as true. + """ + ubla = self.get("uniformBucketLevelAccess", {}) + stamp = ubla.get("lockedTime") + if stamp is not None: + stamp = _rfc3339_nanos_to_datetime(stamp) + return stamp + + @property + def bucket_policy_only_enabled(self): + """Deprecated alias for :attr:`uniform_bucket_level_access_enabled`. + + :rtype: bool + :returns: whether the bucket is configured to allow only IAM. + """ + return self.uniform_bucket_level_access_enabled + + @bucket_policy_only_enabled.setter + def bucket_policy_only_enabled(self, value): + warnings.warn(_BPO_ENABLED_MESSAGE, DeprecationWarning, stacklevel=2) + self.uniform_bucket_level_access_enabled = value + + @property + def bucket_policy_only_locked_time(self): + """Deprecated alias for :attr:`uniform_bucket_level_access_locked_time`. + + :rtype: Union[:class:`datetime.datetime`, None] + :returns: + (readonly) Time after which :attr:`bucket_policy_only_enabled` will + be frozen as true. + """ + return self.uniform_bucket_level_access_locked_time + + +class Bucket(_PropertyMixin): + """A class representing a Bucket on Cloud Storage. + + :type client: :class:`google.cloud.storage.client.Client` + :param client: A client which holds credentials and project configuration + for the bucket (which requires a project). + + :type name: str + :param name: The name of the bucket. Bucket names must start and end with a + number or letter. + + :type user_project: str + :param user_project: (Optional) the project ID to be billed for API + requests made via this instance. + + :type generation: int + :param generation: (Optional) If present, selects a specific revision of + this bucket. + """ + + _MAX_OBJECTS_FOR_ITERATION = 256 + """Maximum number of existing objects allowed in iteration. + + This is used in Bucket.delete() and Bucket.make_public(). + """ + + STORAGE_CLASSES = ( + STANDARD_STORAGE_CLASS, + NEARLINE_STORAGE_CLASS, + COLDLINE_STORAGE_CLASS, + ARCHIVE_STORAGE_CLASS, + MULTI_REGIONAL_LEGACY_STORAGE_CLASS, # legacy + REGIONAL_LEGACY_STORAGE_CLASS, # legacy + DURABLE_REDUCED_AVAILABILITY_LEGACY_STORAGE_CLASS, # legacy + ) + """Allowed values for :attr:`storage_class`. + + Default value is :attr:`STANDARD_STORAGE_CLASS`. + + See + https://cloud.google.com/storage/docs/json_api/v1/buckets#storageClass + https://cloud.google.com/storage/docs/storage-classes + """ + + _LOCATION_TYPES = ( + MULTI_REGION_LOCATION_TYPE, + REGION_LOCATION_TYPE, + DUAL_REGION_LOCATION_TYPE, + ) + """Allowed values for :attr:`location_type`.""" + + def __init__(self, client, name=None, user_project=None, generation=None): + """ + property :attr:`name` + Get the bucket's name. + """ + name = _validate_name(name) + super(Bucket, self).__init__(name=name) + self._client = client + self._acl = BucketACL(self) + self._default_object_acl = DefaultObjectACL(self) + self._label_removals = set() + self._user_project = user_project + + if generation is not None: + self._properties["generation"] = generation + + def __repr__(self): + return f"" + + @property + def client(self): + """The client bound to this bucket.""" + return self._client + + def _set_properties(self, value): + """Set the properties for the current object. + + :type value: dict or :class:`google.cloud.storage.batch._FutureDict` + :param value: The properties to be set. + """ + self._label_removals.clear() + return super(Bucket, self)._set_properties(value) + + @property + def rpo(self): + """Get the RPO (Recovery Point Objective) of this bucket + + See: https://cloud.google.com/storage/docs/managing-turbo-replication + + "ASYNC_TURBO" or "DEFAULT" + :rtype: str + """ + return self._properties.get("rpo") + + @rpo.setter + def rpo(self, value): + """ + Set the RPO (Recovery Point Objective) of this bucket. + + See: https://cloud.google.com/storage/docs/managing-turbo-replication + + :type value: str + :param value: "ASYNC_TURBO" or "DEFAULT" + """ + self._patch_property("rpo", value) + + @property + def user_project(self): + """Project ID to be billed for API requests made via this bucket. + + If unset, API requests are billed to the bucket owner. + + A user project is required for all operations on Requester Pays buckets. + + See https://cloud.google.com/storage/docs/requester-pays#requirements for details. + + :rtype: str + """ + return self._user_project + + @property + def generation(self): + """Retrieve the generation for the bucket. + + :rtype: int or ``NoneType`` + :returns: The generation of the bucket or ``None`` if the bucket's + resource has not been loaded from the server. + """ + generation = self._properties.get("generation") + if generation is not None: + return int(generation) + + @property + def soft_delete_time(self): + """If this bucket has been soft-deleted, returns the time at which it became soft-deleted. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: + (readonly) The time that the bucket became soft-deleted. + Note this property is only set for soft-deleted buckets. + """ + soft_delete_time = self._properties.get("softDeleteTime") + if soft_delete_time is not None: + return _rfc3339_nanos_to_datetime(soft_delete_time) + + @property + def hard_delete_time(self): + """If this bucket has been soft-deleted, returns the time at which it will be permanently deleted. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: + (readonly) The time that the bucket will be permanently deleted. + Note this property is only set for soft-deleted buckets. + """ + hard_delete_time = self._properties.get("hardDeleteTime") + if hard_delete_time is not None: + return _rfc3339_nanos_to_datetime(hard_delete_time) + + @property + def _query_params(self): + """Default query parameters.""" + params = super()._query_params + return params + + @classmethod + def from_uri(cls, uri, client=None): + """Get a constructor for bucket object by URI. + + .. code-block:: python + + from google.cloud import storage + from google.cloud.storage.bucket import Bucket + client = storage.Client() + bucket = Bucket.from_uri("gs://bucket", client=client) + + :type uri: str + :param uri: The bucket uri pass to get bucket object. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. Application code should + *always* pass ``client``. + + :rtype: :class:`google.cloud.storage.bucket.Bucket` + :returns: The bucket object created. + """ + scheme, netloc, path, query, frag = urlsplit(uri) + + if scheme != "gs": + raise ValueError("URI scheme must be gs") + + return cls(client, name=netloc) + + @classmethod + def from_string(cls, uri, client=None): + """Get a constructor for bucket object by URI. + + .. note:: + Deprecated alias for :meth:`from_uri`. + + .. code-block:: python + + from google.cloud import storage + from google.cloud.storage.bucket import Bucket + client = storage.Client() + bucket = Bucket.from_string("gs://bucket", client=client) + + :type uri: str + :param uri: The bucket uri pass to get bucket object. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. Application code should + *always* pass ``client``. + + :rtype: :class:`google.cloud.storage.bucket.Bucket` + :returns: The bucket object created. + """ + warnings.warn(_FROM_STRING_MESSAGE, PendingDeprecationWarning, stacklevel=2) + return Bucket.from_uri(uri=uri, client=client) + + def blob( + self, + blob_name, + chunk_size=None, + encryption_key=None, + kms_key_name=None, + generation=None, + ): + """Factory constructor for blob object. + + .. note:: + This will not make an HTTP request; it simply instantiates + a blob object owned by this bucket. + + :type blob_name: str + :param blob_name: The name of the blob to be instantiated. + + :type chunk_size: int + :param chunk_size: The size of a chunk of data whenever iterating + (in bytes). This must be a multiple of 256 KB per + the API specification. + + :type encryption_key: bytes + :param encryption_key: + (Optional) 32 byte encryption key for customer-supplied encryption. + + :type kms_key_name: str + :param kms_key_name: + (Optional) Resource name of KMS key used to encrypt blob's content. + + :type generation: long + :param generation: (Optional) If present, selects a specific revision of + this object. + + :type crc32c_checksum: str + :param crc32c_checksum: + (Optional) If set, the CRC32C checksum of the blob's content. + CRC32c checksum, as described in RFC 4960, Appendix B; encoded using + base64 in big-endian byte order. See + Apenndix B: https://datatracker.ietf.org/doc/html/rfc4960#appendix-B + base64: https://datatracker.ietf.org/doc/html/rfc4648#section-4 + + :rtype: :class:`google.cloud.storage.blob.Blob` + :returns: The blob object created. + """ + return Blob( + name=blob_name, + bucket=self, + chunk_size=chunk_size, + encryption_key=encryption_key, + kms_key_name=kms_key_name, + generation=generation, + ) + + def notification( + self, + topic_name=None, + topic_project=None, + custom_attributes=None, + event_types=None, + blob_name_prefix=None, + payload_format=NONE_PAYLOAD_FORMAT, + notification_id=None, + ): + """Factory: create a notification resource for the bucket. + + See: :class:`.BucketNotification` for parameters. + + :rtype: :class:`.BucketNotification` + """ + return BucketNotification( + self, + topic_name=topic_name, + topic_project=topic_project, + custom_attributes=custom_attributes, + event_types=event_types, + blob_name_prefix=blob_name_prefix, + payload_format=payload_format, + notification_id=notification_id, + ) + + def exists( + self, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_etag_match=None, + if_etag_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + ): + """Determines whether or not this bucket exists. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: (Optional) Make the operation conditional on whether the + bucket's current ETag matches the given value. + + :type if_etag_not_match: Union[str, Set[str]]) + :param if_etag_not_match: (Optional) Make the operation conditional on whether the + bucket's current ETag does not match the given value. + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + bucket's current metageneration matches the given value. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + bucket's current metageneration does not match the given value. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: bool + :returns: True if the bucket exists in Cloud Storage. + """ + with create_trace_span(name="Storage.Bucket.exists"): + client = self._require_client(client) + # We only need the status code (200 or not) so we seek to + # minimize the returned payload. + query_params = {"fields": "name"} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + _add_generation_match_parameters( + query_params, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + + headers = {} + _add_etag_match_headers( + headers, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + ) + + try: + # We intentionally pass `_target_object=None` since fields=name + # would limit the local properties. + client._get_resource( + self.path, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=None, + ) + except NotFound: + # NOTE: This will not fail immediately in a batch. However, when + # Batch.finish() is called, the resulting `NotFound` will be + # raised. + return False + return True + + def create( + self, + client=None, + project=None, + location=None, + predefined_acl=None, + predefined_default_object_acl=None, + enable_object_retention=False, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Creates current bucket. + + If the bucket already exists, will raise + :class:`google.cloud.exceptions.Conflict`. + + This implements "storage.buckets.insert". + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type project: str + :param project: (Optional) The project under which the bucket is to + be created. If not passed, uses the project set on + the client. + :raises ValueError: if ``project`` is None and client's + :attr:`project` is also None. + + :type location: str + :param location: (Optional) The location of the bucket. If not passed, + the default location, US, will be used. See + https://cloud.google.com/storage/docs/bucket-locations + + :type predefined_acl: str + :param predefined_acl: + (Optional) Name of predefined ACL to apply to bucket. See: + https://cloud.google.com/storage/docs/access-control/lists#predefined-acl + + :type predefined_default_object_acl: str + :param predefined_default_object_acl: + (Optional) Name of predefined ACL to apply to bucket's objects. See: + https://cloud.google.com/storage/docs/access-control/lists#predefined-acl + + :type enable_object_retention: bool + :param enable_object_retention: + (Optional) Whether object retention should be enabled on this bucket. See: + https://cloud.google.com/storage/docs/object-lock + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.Bucket.create"): + client = self._require_client(client) + client.create_bucket( + bucket_or_name=self, + project=project, + user_project=self.user_project, + location=location, + predefined_acl=predefined_acl, + predefined_default_object_acl=predefined_default_object_acl, + enable_object_retention=enable_object_retention, + timeout=timeout, + retry=retry, + ) + + def update( + self, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Sends all properties in a PUT request. + + Updates the ``_properties`` with the response from the backend. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current object. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + blob's current metageneration matches the given value. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + blob's current metageneration does not match the given value. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.Bucket.update"): + super(Bucket, self).update( + client=client, + timeout=timeout, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + def reload( + self, + client=None, + projection="noAcl", + timeout=_DEFAULT_TIMEOUT, + if_etag_match=None, + if_etag_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + soft_deleted=None, + ): + """Reload properties from Cloud Storage. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current object. + + :type projection: str + :param projection: (Optional) If used, must be 'full' or 'noAcl'. + Defaults to ``'noAcl'``. Specifies the set of + properties to return. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: (Optional) Make the operation conditional on whether the + bucket's current ETag matches the given value. + + :type if_etag_not_match: Union[str, Set[str]]) + :param if_etag_not_match: (Optional) Make the operation conditional on whether the + bucket's current ETag does not match the given value. + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + bucket's current metageneration matches the given value. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + bucket's current metageneration does not match the given value. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type soft_deleted: bool + :param soft_deleted: (Optional) If True, looks for a soft-deleted + bucket. Will only return the bucket metadata if the bucket exists + and is in a soft-deleted state. The bucket ``generation`` must be + set if ``soft_deleted`` is set to True. + See: https://cloud.google.com/storage/docs/soft-delete + """ + with create_trace_span(name="Storage.Bucket.reload"): + super(Bucket, self).reload( + client=client, + projection=projection, + timeout=timeout, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + soft_deleted=soft_deleted, + ) + + def patch( + self, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Sends all changed properties in a PATCH request. + + Updates the ``_properties`` with the response from the backend. + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. If not passed, falls back to the + ``client`` stored on the current object. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + blob's current metageneration matches the given value. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + blob's current metageneration does not match the given value. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + """ + with create_trace_span(name="Storage.Bucket.patch"): + # Special case: For buckets, it is possible that labels are being + # removed; this requires special handling. + if self._label_removals: + self._changes.add("labels") + self._properties.setdefault("labels", {}) + for removed_label in self._label_removals: + self._properties["labels"][removed_label] = None + + # Call the superclass method. + super(Bucket, self).patch( + client=client, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + retry=retry, + ) + + @property + def acl(self): + """Create our ACL on demand.""" + return self._acl + + @property + def default_object_acl(self): + """Create our defaultObjectACL on demand.""" + return self._default_object_acl + + @staticmethod + def path_helper(bucket_name): + """Relative URL path for a bucket. + + :type bucket_name: str + :param bucket_name: The bucket name in the path. + + :rtype: str + :returns: The relative URL path for ``bucket_name``. + """ + return "/b/" + bucket_name + + @property + def path(self): + """The URL path to this bucket.""" + if not self.name: + raise ValueError("Cannot determine path without bucket name.") + + return self.path_helper(self.name) + + def get_blob( + self, + blob_name, + client=None, + encryption_key=None, + generation=None, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + soft_deleted=None, + **kwargs, + ): + """Get a blob object by name. + + See a [code sample](https://cloud.google.com/storage/docs/samples/storage-get-metadata#storage_get_metadata-python) + on how to retrieve metadata of an object. + + If :attr:`user_project` is set, bills the API request to that project. + + :type blob_name: str + :param blob_name: The name of the blob to retrieve. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type encryption_key: bytes + :param encryption_key: + (Optional) 32 byte encryption key for customer-supplied encryption. + See + https://cloud.google.com/storage/docs/encryption#customer-supplied. + + :type generation: long + :param generation: + (Optional) If present, selects a specific revision of this object. + + :type if_etag_match: Union[str, Set[str]] + :param if_etag_match: + (Optional) See :ref:`using-if-etag-match` + + :type if_etag_not_match: Union[str, Set[str]] + :param if_etag_not_match: + (Optional) See :ref:`using-if-etag-not-match` + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type soft_deleted: bool + :param soft_deleted: + (Optional) If True, looks for a soft-deleted object. Will only return + the object metadata if the object exists and is in a soft-deleted state. + Object ``generation`` is required if ``soft_deleted`` is set to True. + See: https://cloud.google.com/storage/docs/soft-delete + + :param kwargs: Keyword arguments to pass to the + :class:`~google.cloud.storage.blob.Blob` constructor. + + :rtype: :class:`google.cloud.storage.blob.Blob` or None + :returns: The blob object if it exists, otherwise None. + """ + with create_trace_span(name="Storage.Bucket.getBlob"): + blob = Blob( + bucket=self, + name=blob_name, + encryption_key=encryption_key, + generation=generation, + **kwargs, + ) + try: + # NOTE: This will not fail immediately in a batch. However, when + # Batch.finish() is called, the resulting `NotFound` will be + # raised. + blob.reload( + client=client, + timeout=timeout, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + soft_deleted=soft_deleted, + ) + except NotFound: + return None + else: + return blob + + def list_blobs( + self, + max_results=None, + page_token=None, + prefix=None, + delimiter=None, + start_offset=None, + end_offset=None, + include_trailing_delimiter=None, + versions=None, + projection="noAcl", + fields=None, + client=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + match_glob=None, + include_folders_as_prefixes=None, + soft_deleted=None, + page_size=None, + ): + """Return an iterator used to find blobs in the bucket. + + If :attr:`user_project` is set, bills the API request to that project. + + :type max_results: int + :param max_results: + (Optional) The maximum number of blobs to return. + + :type page_token: str + :param page_token: + (Optional) If present, return the next batch of blobs, using the + value, which must correspond to the ``nextPageToken`` value + returned in the previous response. Deprecated: use the ``pages`` + property of the returned iterator instead of manually passing the + token. + + :type prefix: str + :param prefix: (Optional) Prefix used to filter blobs. + + :type delimiter: str + :param delimiter: (Optional) Delimiter, used with ``prefix`` to + emulate hierarchy. + + :type start_offset: str + :param start_offset: + (Optional) Filter results to objects whose names are + lexicographically equal to or after ``startOffset``. If + ``endOffset`` is also set, the objects listed will have names + between ``startOffset`` (inclusive) and ``endOffset`` (exclusive). + + :type end_offset: str + :param end_offset: + (Optional) Filter results to objects whose names are + lexicographically before ``endOffset``. If ``startOffset`` is also + set, the objects listed will have names between ``startOffset`` + (inclusive) and ``endOffset`` (exclusive). + + :type include_trailing_delimiter: boolean + :param include_trailing_delimiter: + (Optional) If true, objects that end in exactly one instance of + ``delimiter`` will have their metadata included in ``items`` in + addition to ``prefixes``. + + :type versions: bool + :param versions: (Optional) Whether object versions should be returned + as separate blobs. + + :type projection: str + :param projection: (Optional) If used, must be 'full' or 'noAcl'. + Defaults to ``'noAcl'``. Specifies the set of + properties to return. + + :type fields: str + :param fields: + (Optional) Selector specifying which fields to include + in a partial response. Must be a list of fields. For + example to get a partial response with just the next + page token and the name and language of each blob returned: + ``'items(name,contentLanguage),nextPageToken'``. + See: https://cloud.google.com/storage/docs/json_api/v1/parameters#fields + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type match_glob: str + :param match_glob: + (Optional) A glob pattern used to filter results (for example, foo*bar). + The string value must be UTF-8 encoded. See: + https://cloud.google.com/storage/docs/json_api/v1/objects/list#list-object-glob + + :type include_folders_as_prefixes: bool + (Optional) If true, includes Folders and Managed Folders in the set of + ``prefixes`` returned by the query. Only applicable if ``delimiter`` is set to /. + See: https://cloud.google.com/storage/docs/managed-folders + + :type soft_deleted: bool + :param soft_deleted: + (Optional) If true, only soft-deleted objects will be listed as distinct results in order of increasing + generation number. This parameter can only be used successfully if the bucket has a soft delete policy. + Note ``soft_deleted`` and ``versions`` cannot be set to True simultaneously. See: + https://cloud.google.com/storage/docs/soft-delete + + :type page_size: int + :param page_size: + (Optional) Maximum number of blobs to return in each page. + Defaults to a value set by the API. + + :rtype: :class:`~google.api_core.page_iterator.Iterator` + :returns: Iterator of all :class:`~google.cloud.storage.blob.Blob` + in this bucket matching the arguments. + """ + with create_trace_span(name="Storage.Bucket.listBlobs"): + client = self._require_client(client) + return client.list_blobs( + self, + max_results=max_results, + page_token=page_token, + prefix=prefix, + delimiter=delimiter, + start_offset=start_offset, + end_offset=end_offset, + include_trailing_delimiter=include_trailing_delimiter, + versions=versions, + projection=projection, + fields=fields, + page_size=page_size, + timeout=timeout, + retry=retry, + match_glob=match_glob, + include_folders_as_prefixes=include_folders_as_prefixes, + soft_deleted=soft_deleted, + ) + + def list_notifications( + self, client=None, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY + ): + """List Pub / Sub notifications for this bucket. + + See: + https://cloud.google.com/storage/docs/json_api/v1/notifications/list + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: list of :class:`.BucketNotification` + :returns: notification instances + """ + with create_trace_span(name="Storage.Bucket.listNotifications"): + client = self._require_client(client) + path = self.path + "/notificationConfigs" + iterator = client._list_resource( + path, + _item_to_notification, + timeout=timeout, + retry=retry, + ) + iterator.bucket = self + return iterator + + def get_notification( + self, + notification_id, + client=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Get Pub / Sub notification for this bucket. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/notifications/get) + and a [code sample](https://cloud.google.com/storage/docs/samples/storage-print-pubsub-bucket-notification#storage_print_pubsub_bucket_notification-python). + + If :attr:`user_project` is set, bills the API request to that project. + + :type notification_id: str + :param notification_id: The notification id to retrieve the notification configuration. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: :class:`.BucketNotification` + :returns: notification instance. + """ + with create_trace_span(name="Storage.Bucket.getNotification"): + notification = self.notification(notification_id=notification_id) + notification.reload(client=client, timeout=timeout, retry=retry) + return notification + + def delete( + self, + force=False, + client=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Delete this bucket. + + The bucket **must** be empty in order to submit a delete request. If + ``force=True`` is passed, this will first attempt to delete all the + objects / blobs in the bucket (i.e. try to empty the bucket). + + If the bucket doesn't exist, this will raise + :class:`google.cloud.exceptions.NotFound`. If the bucket is not empty + (and ``force=False``), will raise :class:`google.cloud.exceptions.Conflict`. + + If ``force=True`` and the bucket contains more than 256 objects / blobs + this will cowardly refuse to delete the objects (or the bucket). This + is to prevent accidental bucket deletion and to prevent extremely long + runtime of this method. Also note that ``force=True`` is not supported + in a ``Batch`` context. + + If :attr:`user_project` is set, bills the API request to that project. + + :type force: bool + :param force: If True, empties the bucket's objects then deletes it. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + blob's current metageneration matches the given value. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + blob's current metageneration does not match the given value. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises: :class:`ValueError` if ``force`` is ``True`` and the bucket + contains more than 256 objects / blobs. + """ + with create_trace_span(name="Storage.Bucket.delete"): + client = self._require_client(client) + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + _add_generation_match_parameters( + query_params, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + if force: + blobs = list( + self.list_blobs( + max_results=self._MAX_OBJECTS_FOR_ITERATION + 1, + client=client, + timeout=timeout, + retry=retry, + versions=True, + ) + ) + if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION: + message = ( + "Refusing to delete bucket with more than " + "%d objects. If you actually want to delete " + "this bucket, please delete the objects " + "yourself before calling Bucket.delete()." + ) % (self._MAX_OBJECTS_FOR_ITERATION,) + raise ValueError(message) + + # Ignore 404 errors on delete. + self.delete_blobs( + blobs, + on_error=lambda blob: None, + client=client, + timeout=timeout, + retry=retry, + preserve_generation=True, + ) + + # We intentionally pass `_target_object=None` since a DELETE + # request has no response value (whether in a standard request or + # in a batch request). + client._delete_resource( + self.path, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + + def delete_blob( + self, + blob_name, + client=None, + generation=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Deletes a blob from the current bucket. + + If :attr:`user_project` is set, bills the API request to that project. + + :type blob_name: str + :param blob_name: A blob name to delete. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type generation: long + :param generation: (Optional) If present, permanently deletes a specific + revision of this object. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :raises: :class:`google.cloud.exceptions.NotFound` Raises a NotFound + if the blob isn't found. To suppress + the exception, use :meth:`delete_blobs` by passing a no-op + ``on_error`` callback. + """ + with create_trace_span(name="Storage.Bucket.deleteBlob"): + client = self._require_client(client) + blob = Blob(blob_name, bucket=self, generation=generation) + + query_params = copy.deepcopy(blob._query_params) + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + # We intentionally pass `_target_object=None` since a DELETE + # request has no response value (whether in a standard request or + # in a batch request). + client._delete_resource( + blob.path, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + + def delete_blobs( + self, + blobs, + on_error=None, + client=None, + preserve_generation=False, + timeout=_DEFAULT_TIMEOUT, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + ): + """Deletes a list of blobs from the current bucket. + + Uses :meth:`delete_blob` to delete each individual blob. + + By default, any generation information in the list of blobs is ignored, and the + live versions of all blobs are deleted. Set `preserve_generation` to True + if blob generation should instead be propagated from the list of blobs. + + If :attr:`user_project` is set, bills the API request to that project. + + :type blobs: list + :param blobs: A list of :class:`~google.cloud.storage.blob.Blob`-s or + blob names to delete. + + :type on_error: callable + :param on_error: (Optional) Takes single argument: ``blob``. + Called once for each blob raising + :class:`~google.cloud.exceptions.NotFound`; + otherwise, the exception is propagated. + Note that ``on_error`` is not supported in a ``Batch`` context. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type preserve_generation: bool + :param preserve_generation: (Optional) Deletes only the generation specified on the blob object, + instead of the live version, if set to True. Only :class:~google.cloud.storage.blob.Blob + objects can have their generation set in this way. + Default: False. + + :type if_generation_match: list of long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + Note that the length of the list must match the length of + The list must match ``blobs`` item-to-item. + + :type if_generation_not_match: list of long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + The list must match ``blobs`` item-to-item. + + :type if_metageneration_match: list of long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + The list must match ``blobs`` item-to-item. + + :type if_metageneration_not_match: list of long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + The list must match ``blobs`` item-to-item. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_generation_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + :raises: :class:`~google.cloud.exceptions.NotFound` (if + `on_error` is not passed). + """ + with create_trace_span(name="Storage.Bucket.deleteBlobs"): + _raise_if_len_differs( + len(blobs), + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + if_generation_match = iter(if_generation_match or []) + if_generation_not_match = iter(if_generation_not_match or []) + if_metageneration_match = iter(if_metageneration_match or []) + if_metageneration_not_match = iter(if_metageneration_not_match or []) + + for blob in blobs: + try: + blob_name = blob + generation = None + if not isinstance(blob_name, str): + blob_name = blob.name + generation = blob.generation if preserve_generation else None + + self.delete_blob( + blob_name, + client=client, + generation=generation, + if_generation_match=next(if_generation_match, None), + if_generation_not_match=next(if_generation_not_match, None), + if_metageneration_match=next(if_metageneration_match, None), + if_metageneration_not_match=next( + if_metageneration_not_match, None + ), + timeout=timeout, + retry=retry, + ) + except NotFound: + if on_error is not None: + on_error(blob) + else: + raise + + def copy_blob( + self, + blob, + destination_bucket, + new_name=None, + client=None, + preserve_acl=True, + source_generation=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + if_source_generation_match=None, + if_source_generation_not_match=None, + if_source_metageneration_match=None, + if_source_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED, + ): + """Copy the given blob to the given bucket, optionally with a new name. + + If :attr:`user_project` is set, bills the API request to that project. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/objects/copy) + and a [code sample](https://cloud.google.com/storage/docs/samples/storage-copy-file#storage_copy_file-python). + + :type blob: :class:`google.cloud.storage.blob.Blob` + :param blob: The blob to be copied. + + :type destination_bucket: :class:`google.cloud.storage.bucket.Bucket` + :param destination_bucket: The bucket into which the blob should be + copied. + + :type new_name: str + :param new_name: (Optional) The new name for the copied file. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type preserve_acl: bool + :param preserve_acl: DEPRECATED. This argument is not functional! + (Optional) Copies ACL from old blob to new blob. + Default: True. + Note that ``preserve_acl`` is not supported in a + ``Batch`` context. + + :type source_generation: long + :param source_generation: (Optional) The generation of the blob to be + copied. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_source_generation_match: long + :param if_source_generation_match: + (Optional) Makes the operation conditional on whether the source + object's generation matches the given value. + + :type if_source_generation_not_match: long + :param if_source_generation_not_match: + (Optional) Makes the operation conditional on whether the source + object's generation does not match the given value. + + :type if_source_metageneration_match: long + :param if_source_metageneration_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration matches the given value. + + :type if_source_metageneration_not_match: long + :param if_source_metageneration_not_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration does not match the given value. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. + The default value is ``DEFAULT_RETRY_IF_GENERATION_SPECIFIED``, a conditional retry + policy which will only enable retries if ``if_generation_match`` or ``generation`` + is set, in order to ensure requests are idempotent before retrying them. + Change the value to ``DEFAULT_RETRY`` or another `google.api_core.retry.Retry` object + to enable retries regardless of generation precondition setting. + See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + + :rtype: :class:`google.cloud.storage.blob.Blob` + :returns: The new Blob. + """ + with create_trace_span(name="Storage.Bucket.copyBlob"): + client = self._require_client(client) + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + if source_generation is not None: + query_params["sourceGeneration"] = source_generation + + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + if_source_generation_match=if_source_generation_match, + if_source_generation_not_match=if_source_generation_not_match, + if_source_metageneration_match=if_source_metageneration_match, + if_source_metageneration_not_match=if_source_metageneration_not_match, + ) + + if new_name is None: + new_name = blob.name + + new_blob = Blob(bucket=destination_bucket, name=new_name) + api_path = blob.path + "/copyTo" + new_blob.path + copy_result = client._post_resource( + api_path, + None, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=new_blob, + ) + + if not preserve_acl: + new_blob.acl.save(acl={}, client=client, timeout=timeout) + + new_blob._set_properties(copy_result) + return new_blob + + def rename_blob( + self, + blob, + new_name, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + if_source_generation_match=None, + if_source_generation_not_match=None, + if_source_metageneration_match=None, + if_source_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED, + ): + """Rename the given blob using copy and delete operations. + + If :attr:`user_project` is set, bills the API request to that project. + + Effectively, copies blob to the same bucket with a new name, then + deletes the blob. + + .. warning:: + + This method will first duplicate the data and then delete the + old blob. This means that with very large objects renaming + could be a very (temporarily) costly or a very slow operation. + If you need more control over the copy and deletion, instead + use ``google.cloud.storage.blob.Blob.copy_to`` and + ``google.cloud.storage.blob.Blob.delete`` directly. + + Also note that this method is not fully supported in a + ``Batch`` context. + + :type blob: :class:`google.cloud.storage.blob.Blob` + :param blob: The blob to be renamed. + + :type new_name: str + :param new_name: The new name for this blob. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_source_generation_match: long + :param if_source_generation_match: + (Optional) Makes the operation conditional on whether the source + object's generation matches the given value. Also used in the + (implied) delete request. + + :type if_source_generation_not_match: long + :param if_source_generation_not_match: + (Optional) Makes the operation conditional on whether the source + object's generation does not match the given value. Also used in + the (implied) delete request. + + :type if_source_metageneration_match: long + :param if_source_metageneration_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration matches the given value. Also used + in the (implied) delete request. + + :type if_source_metageneration_not_match: long + :param if_source_metageneration_not_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration does not match the given value. + Also used in the (implied) delete request. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. + The default value is ``DEFAULT_RETRY_IF_GENERATION_SPECIFIED``, a conditional retry + policy which will only enable retries if ``if_generation_match`` or ``generation`` + is set, in order to ensure requests are idempotent before retrying them. + Change the value to ``DEFAULT_RETRY`` or another `google.api_core.retry.Retry` object + to enable retries regardless of generation precondition setting. + See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + + :rtype: :class:`Blob` + :returns: The newly-renamed blob. + """ + with create_trace_span(name="Storage.Bucket.renameBlob"): + same_name = blob.name == new_name + + new_blob = self.copy_blob( + blob, + self, + new_name, + client=client, + timeout=timeout, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + if_source_generation_match=if_source_generation_match, + if_source_generation_not_match=if_source_generation_not_match, + if_source_metageneration_match=if_source_metageneration_match, + if_source_metageneration_not_match=if_source_metageneration_not_match, + retry=retry, + ) + + if not same_name: + blob.delete( + client=client, + timeout=timeout, + if_generation_match=if_source_generation_match, + if_generation_not_match=if_source_generation_not_match, + if_metageneration_match=if_source_metageneration_match, + if_metageneration_not_match=if_source_metageneration_not_match, + retry=retry, + ) + return new_blob + + def move_blob( + self, + blob, + new_name, + client=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + if_source_generation_match=None, + if_source_generation_not_match=None, + if_source_metageneration_match=None, + if_source_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED, + ): + """Move a blob to a new name atomically. + + If :attr:`user_project` is set on the bucket, bills the API request to that project. + + :type blob: :class:`google.cloud.storage.blob.Blob` + :param blob: The blob to be renamed. + + :type new_name: str + :param new_name: The new name for this blob. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type if_generation_match: int + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_generation_not_match: int + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + Note that the generation to be matched is that of the + ``destination`` blob. + + :type if_metageneration_match: int + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_metageneration_not_match: int + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + Note that the metageneration to be matched is that of the + ``destination`` blob. + + :type if_source_generation_match: int + :param if_source_generation_match: + (Optional) Makes the operation conditional on whether the source + object's generation matches the given value. + + :type if_source_generation_not_match: int + :param if_source_generation_not_match: + (Optional) Makes the operation conditional on whether the source + object's generation does not match the given value. + + :type if_source_metageneration_match: int + :param if_source_metageneration_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration matches the given value. + + :type if_source_metageneration_not_match: int + :param if_source_metageneration_not_match: + (Optional) Makes the operation conditional on whether the source + object's current metageneration does not match the given value. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry + :param retry: + (Optional) How to retry the RPC. + See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + + :rtype: :class:`Blob` + :returns: The newly-moved blob. + """ + with create_trace_span(name="Storage.Bucket.moveBlob"): + client = self._require_client(client) + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + if_source_generation_match=if_source_generation_match, + if_source_generation_not_match=if_source_generation_not_match, + if_source_metageneration_match=if_source_metageneration_match, + if_source_metageneration_not_match=if_source_metageneration_not_match, + ) + + new_blob = Blob(bucket=self, name=new_name) + api_path = "{blob_path}/moveTo/o/{new_name}".format( + blob_path=blob.path, new_name=_quote(new_blob.name) + ) + + move_result = client._post_resource( + api_path, + None, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=new_blob, + ) + + new_blob._set_properties(move_result) + return new_blob + + def restore_blob( + self, + blob_name, + client=None, + generation=None, + copy_source_acl=None, + projection=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED, + ): + """Restores a soft-deleted object. + + If :attr:`user_project` is set on the bucket, bills the API request to that project. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/objects/restore) + + :type blob_name: str + :param blob_name: The name of the blob to be restored. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type generation: int + :param generation: Selects the specific revision of the object. + + :type copy_source_acl: bool + :param copy_source_acl: (Optional) If true, copy the soft-deleted object's access controls. + + :type projection: str + :param projection: (Optional) Specifies the set of properties to return. + If used, must be 'full' or 'noAcl'. + + :type if_generation_match: long + :param if_generation_match: + (Optional) See :ref:`using-if-generation-match` + + :type if_generation_not_match: long + :param if_generation_not_match: + (Optional) See :ref:`using-if-generation-not-match` + + :type if_metageneration_match: long + :param if_metageneration_match: + (Optional) See :ref:`using-if-metageneration-match` + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: + (Optional) See :ref:`using-if-metageneration-not-match` + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. + The default value is ``DEFAULT_RETRY_IF_GENERATION_SPECIFIED``, which + only restore operations with ``if_generation_match`` or ``generation`` set + will be retried. + + Users can configure non-default retry behavior. A ``None`` value will + disable retries. A ``DEFAULT_RETRY`` value will enable retries + even if restore operations are not guaranteed to be idempotent. + See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + + :rtype: :class:`google.cloud.storage.blob.Blob` + :returns: The restored Blob. + """ + with create_trace_span(name="Storage.Bucket.restore_blob"): + client = self._require_client(client) + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + if generation is not None: + query_params["generation"] = generation + if copy_source_acl is not None: + query_params["copySourceAcl"] = copy_source_acl + if projection is not None: + query_params["projection"] = projection + + _add_generation_match_parameters( + query_params, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + + blob = Blob(bucket=self, name=blob_name) + api_response = client._post_resource( + f"{blob.path}/restore", + None, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + blob._set_properties(api_response) + return blob + + @property + def cors(self): + """Retrieve or set CORS policies configured for this bucket. + + See http://www.w3.org/TR/cors/ and + https://cloud.google.com/storage/docs/json_api/v1/buckets + + .. note:: + + The getter for this property returns a list which contains + *copies* of the bucket's CORS policy mappings. Mutating the list + or one of its dicts has no effect unless you then re-assign the + dict via the setter. E.g.: + + >>> policies = bucket.cors + >>> policies.append({'origin': '/foo', ...}) + >>> policies[1]['maxAgeSeconds'] = 3600 + >>> del policies[0] + >>> bucket.cors = policies + >>> bucket.update() + + :setter: Set CORS policies for this bucket. + :getter: Gets the CORS policies for this bucket. + + :rtype: list of dictionaries + :returns: A sequence of mappings describing each CORS policy. + """ + return [copy.deepcopy(policy) for policy in self._properties.get("cors", ())] + + @cors.setter + def cors(self, entries): + """Set CORS policies configured for this bucket. + + See http://www.w3.org/TR/cors/ and + https://cloud.google.com/storage/docs/json_api/v1/buckets + + :type entries: list of dictionaries + :param entries: A sequence of mappings describing each CORS policy. + """ + self._patch_property("cors", entries) + + default_event_based_hold = _scalar_property("defaultEventBasedHold") + """Are uploaded objects automatically placed under an even-based hold? + + If True, uploaded objects will be placed under an event-based hold to + be released at a future time. When released an object will then begin + the retention period determined by the policy retention period for the + object bucket. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + If the property is not set locally, returns ``None``. + + :rtype: bool or ``NoneType`` + """ + + @property + def encryption(self): + """Retrieve encryption configuration for this bucket. + + :rtype: :class:`BucketEncryption` + :returns: an instance for managing the bucket's encryption configuration. + """ + info = self._properties.get("encryption", {}) + return BucketEncryption.from_api_repr(info, self) + + @encryption.setter + def encryption(self, value): + """Set encryption configuration for this bucket. + + :type value: :class:`BucketEncryption` or dict + :param value: The encryption configuration. + """ + self._patch_property("encryption", value) + + @property + def default_kms_key_name(self): + """Retrieve / set default KMS encryption key for objects in the bucket. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :setter: Set default KMS encryption key for items in this bucket. + :getter: Get default KMS encryption key for items in this bucket. + + :rtype: str + :returns: Default KMS encryption key, or ``None`` if not set. + """ + encryption_config = self._properties.get("encryption", {}) + return encryption_config.get("defaultKmsKeyName") + + @default_kms_key_name.setter + def default_kms_key_name(self, value): + """Set default KMS encryption key for objects in the bucket. + + :type value: str or None + :param value: new KMS key name (None to clear any existing key). + """ + encryption_config = self._properties.get("encryption", {}) + encryption_config["defaultKmsKeyName"] = value + self._patch_property("encryption", encryption_config) + + @property + def labels(self): + """Retrieve or set labels assigned to this bucket. + + See + https://cloud.google.com/storage/docs/json_api/v1/buckets#labels + + .. note:: + + The getter for this property returns a dict which is a *copy* + of the bucket's labels. Mutating that dict has no effect unless + you then re-assign the dict via the setter. E.g.: + + >>> labels = bucket.labels + >>> labels['new_key'] = 'some-label' + >>> del labels['old_key'] + >>> bucket.labels = labels + >>> bucket.update() + + :setter: Set labels for this bucket. + :getter: Gets the labels for this bucket. + + :rtype: :class:`dict` + :returns: Name-value pairs (string->string) labelling the bucket. + """ + labels = self._properties.get("labels") + if labels is None: + return {} + return copy.deepcopy(labels) + + @labels.setter + def labels(self, mapping): + """Set labels assigned to this bucket. + + See + https://cloud.google.com/storage/docs/json_api/v1/buckets#labels + + :type mapping: :class:`dict` + :param mapping: Name-value pairs (string->string) labelling the bucket. + """ + # If any labels have been expressly removed, we need to track this + # so that a future .patch() call can do the correct thing. + existing = set([k for k in self.labels.keys()]) + incoming = set([k for k in mapping.keys()]) + self._label_removals = self._label_removals.union(existing.difference(incoming)) + mapping = {k: str(v) for k, v in mapping.items()} + + # Actually update the labels on the object. + self._patch_property("labels", copy.deepcopy(mapping)) + + @property + def etag(self): + """Retrieve the ETag for the bucket. + + See https://tools.ietf.org/html/rfc2616#section-3.11 and + https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: str or ``NoneType`` + :returns: The bucket etag or ``None`` if the bucket's + resource has not been loaded from the server. + """ + return self._properties.get("etag") + + @property + def id(self): + """Retrieve the ID for the bucket. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: str or ``NoneType`` + :returns: The ID of the bucket or ``None`` if the bucket's + resource has not been loaded from the server. + """ + return self._properties.get("id") + + @property + def iam_configuration(self): + """Retrieve IAM configuration for this bucket. + + :rtype: :class:`IAMConfiguration` + :returns: an instance for managing the bucket's IAM configuration. + """ + info = self._properties.get("iamConfiguration", {}) + return IAMConfiguration.from_api_repr(info, self) + + @property + def soft_delete_policy(self): + """Retrieve the soft delete policy for this bucket. + + See https://cloud.google.com/storage/docs/soft-delete + + :rtype: :class:`SoftDeletePolicy` + :returns: an instance for managing the bucket's soft delete policy. + """ + policy = self._properties.get("softDeletePolicy", {}) + return SoftDeletePolicy.from_api_repr(policy, self) + + @property + def lifecycle_rules(self): + """Retrieve or set lifecycle rules configured for this bucket. + + See https://cloud.google.com/storage/docs/lifecycle and + https://cloud.google.com/storage/docs/json_api/v1/buckets + + .. note:: + + The getter for this property returns a generator which yields + *copies* of the bucket's lifecycle rules mappings. Mutating the + output dicts has no effect unless you then re-assign the dict via + the setter. E.g.: + + >>> rules = list(bucket.lifecycle_rules) + >>> rules.append({'origin': '/foo', ...}) + >>> rules[1]['rule']['action']['type'] = 'Delete' + >>> del rules[0] + >>> bucket.lifecycle_rules = rules + >>> bucket.update() + + :setter: Set lifecycle rules for this bucket. + :getter: Gets the lifecycle rules for this bucket. + + :rtype: generator(dict) + :returns: A sequence of mappings describing each lifecycle rule. + """ + info = self._properties.get("lifecycle", {}) + for rule in info.get("rule", ()): + action_type = rule["action"]["type"] + if action_type == "Delete": + yield LifecycleRuleDelete.from_api_repr(rule) + elif action_type == "SetStorageClass": + yield LifecycleRuleSetStorageClass.from_api_repr(rule) + elif action_type == "AbortIncompleteMultipartUpload": + yield LifecycleRuleAbortIncompleteMultipartUpload.from_api_repr(rule) + else: + warnings.warn( + "Unknown lifecycle rule type received: {}. Please upgrade to the latest version of google-cloud-storage.".format( + rule + ), + UserWarning, + stacklevel=1, + ) + + @lifecycle_rules.setter + def lifecycle_rules(self, rules): + """Set lifecycle rules configured for this bucket. + + See https://cloud.google.com/storage/docs/lifecycle and + https://cloud.google.com/storage/docs/json_api/v1/buckets + + :type rules: list of dictionaries + :param rules: A sequence of mappings describing each lifecycle rule. + """ + rules = [dict(rule) for rule in rules] # Convert helpers if needed + self._patch_property("lifecycle", {"rule": rules}) + + def clear_lifecycle_rules(self): + """Clear lifecycle rules configured for this bucket. + + See https://cloud.google.com/storage/docs/lifecycle and + https://cloud.google.com/storage/docs/json_api/v1/buckets + """ + self.lifecycle_rules = [] + + def clear_lifecyle_rules(self): + """Deprecated alias for clear_lifecycle_rules.""" + return self.clear_lifecycle_rules() + + def add_lifecycle_delete_rule(self, **kw): + """Add a "delete" rule to lifecycle rules configured for this bucket. + + This defines a [lifecycle configuration](https://cloud.google.com/storage/docs/lifecycle), + which is set on the bucket. For the general format of a lifecycle configuration, see the + [bucket resource representation for JSON](https://cloud.google.com/storage/docs/json_api/v1/buckets). + See also a [code sample](https://cloud.google.com/storage/docs/samples/storage-enable-bucket-lifecycle-management#storage_enable_bucket_lifecycle_management-python). + + :type kw: dict + :params kw: arguments passed to :class:`LifecycleRuleConditions`. + """ + rules = list(self.lifecycle_rules) + rules.append(LifecycleRuleDelete(**kw)) + self.lifecycle_rules = rules + + def add_lifecycle_set_storage_class_rule(self, storage_class, **kw): + """Add a "set storage class" rule to lifecycle rules. + + This defines a [lifecycle configuration](https://cloud.google.com/storage/docs/lifecycle), + which is set on the bucket. For the general format of a lifecycle configuration, see the + [bucket resource representation for JSON](https://cloud.google.com/storage/docs/json_api/v1/buckets). + + :type storage_class: str, one of :attr:`STORAGE_CLASSES`. + :param storage_class: new storage class to assign to matching items. + + :type kw: dict + :params kw: arguments passed to :class:`LifecycleRuleConditions`. + """ + rules = list(self.lifecycle_rules) + rules.append(LifecycleRuleSetStorageClass(storage_class, **kw)) + self.lifecycle_rules = rules + + def add_lifecycle_abort_incomplete_multipart_upload_rule(self, **kw): + """Add a "abort incomplete multipart upload" rule to lifecycle rules. + + .. note:: + The "age" lifecycle condition is the only supported condition + for this rule. + + This defines a [lifecycle configuration](https://cloud.google.com/storage/docs/lifecycle), + which is set on the bucket. For the general format of a lifecycle configuration, see the + [bucket resource representation for JSON](https://cloud.google.com/storage/docs/json_api/v1/buckets). + + :type kw: dict + :params kw: arguments passed to :class:`LifecycleRuleConditions`. + """ + rules = list(self.lifecycle_rules) + rules.append(LifecycleRuleAbortIncompleteMultipartUpload(**kw)) + self.lifecycle_rules = rules + + _location = _scalar_property("location") + + @property + def location(self): + """Retrieve location configured for this bucket. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets and + https://cloud.google.com/storage/docs/locations + + Returns ``None`` if the property has not been set before creation, + or if the bucket's resource has not been loaded from the server. + :rtype: str or ``NoneType`` + """ + return self._location + + @location.setter + def location(self, value): + """(Deprecated) Set `Bucket.location` + + This can only be set at bucket **creation** time. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets and + https://cloud.google.com/storage/docs/bucket-locations + + .. warning:: + + Assignment to 'Bucket.location' is deprecated, as it is only + valid before the bucket is created. Instead, pass the location + to `Bucket.create`. + """ + warnings.warn(_LOCATION_SETTER_MESSAGE, DeprecationWarning, stacklevel=2) + self._location = value + + @property + def data_locations(self): + """Retrieve the list of regional locations for custom dual-region buckets. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets and + https://cloud.google.com/storage/docs/locations + + Returns ``None`` if the property has not been set before creation, + if the bucket's resource has not been loaded from the server, + or if the bucket is not a dual-regions bucket. + :rtype: list of str or ``NoneType`` + """ + custom_placement_config = self._properties.get("customPlacementConfig", {}) + return custom_placement_config.get("dataLocations") + + @property + def location_type(self): + """Retrieve the location type for the bucket. + + See https://cloud.google.com/storage/docs/storage-classes + + :getter: Gets the the location type for this bucket. + + :rtype: str or ``NoneType`` + :returns: + If set, one of + :attr:`~google.cloud.storage.constants.MULTI_REGION_LOCATION_TYPE`, + :attr:`~google.cloud.storage.constants.REGION_LOCATION_TYPE`, or + :attr:`~google.cloud.storage.constants.DUAL_REGION_LOCATION_TYPE`, + else ``None``. + """ + return self._properties.get("locationType") + + def get_logging(self): + """Return info about access logging for this bucket. + + See https://cloud.google.com/storage/docs/access-logs#status + + :rtype: dict or None + :returns: a dict w/ keys, ``logBucket`` and ``logObjectPrefix`` + (if logging is enabled), or None (if not). + """ + info = self._properties.get("logging") + return copy.deepcopy(info) + + def enable_logging(self, bucket_name, object_prefix=""): + """Enable access logging for this bucket. + + See https://cloud.google.com/storage/docs/access-logs + + :type bucket_name: str + :param bucket_name: name of bucket in which to store access logs + + :type object_prefix: str + :param object_prefix: prefix for access log filenames + """ + info = {"logBucket": bucket_name, "logObjectPrefix": object_prefix} + self._patch_property("logging", info) + + def disable_logging(self): + """Disable access logging for this bucket. + + See https://cloud.google.com/storage/docs/access-logs#disabling + """ + self._patch_property("logging", None) + + @property + def metageneration(self): + """Retrieve the metageneration for the bucket. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: int or ``NoneType`` + :returns: The metageneration of the bucket or ``None`` if the bucket's + resource has not been loaded from the server. + """ + metageneration = self._properties.get("metageneration") + if metageneration is not None: + return int(metageneration) + + @property + def owner(self): + """Retrieve info about the owner of the bucket. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: dict or ``NoneType`` + :returns: Mapping of owner's role/ID. Returns ``None`` if the bucket's + resource has not been loaded from the server. + """ + return copy.deepcopy(self._properties.get("owner")) + + @property + def project_number(self): + """Retrieve the number of the project to which the bucket is assigned. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: int or ``NoneType`` + :returns: The project number that owns the bucket or ``None`` if + the bucket's resource has not been loaded from the server. + """ + project_number = self._properties.get("projectNumber") + if project_number is not None: + return int(project_number) + + @property + def retention_policy_effective_time(self): + """Retrieve the effective time of the bucket's retention policy. + + :rtype: datetime.datetime or ``NoneType`` + :returns: point-in time at which the bucket's retention policy is + effective, or ``None`` if the property is not + set locally. + """ + policy = self._properties.get("retentionPolicy") + if policy is not None: + timestamp = policy.get("effectiveTime") + if timestamp is not None: + return _rfc3339_nanos_to_datetime(timestamp) + + @property + def retention_policy_locked(self): + """Retrieve whthere the bucket's retention policy is locked. + + :rtype: bool + :returns: True if the bucket's policy is locked, or else False + if the policy is not locked, or the property is not + set locally. + """ + policy = self._properties.get("retentionPolicy") + if policy is not None: + return policy.get("isLocked") + + @property + def retention_period(self): + """Retrieve or set the retention period for items in the bucket. + + :rtype: int or ``NoneType`` + :returns: number of seconds to retain items after upload or release + from event-based lock, or ``None`` if the property is not + set locally. + """ + policy = self._properties.get("retentionPolicy") + if policy is not None: + period = policy.get("retentionPeriod") + if period is not None: + return int(period) + + @retention_period.setter + def retention_period(self, value): + """Set the retention period for items in the bucket. + + :type value: int + :param value: + number of seconds to retain items after upload or release from + event-based lock. + + :raises ValueError: if the bucket's retention policy is locked. + """ + policy = self._properties.setdefault("retentionPolicy", {}) + if value is not None: + policy["retentionPeriod"] = str(value) + else: + policy = None + self._patch_property("retentionPolicy", policy) + + @property + def self_link(self): + """Retrieve the URI for the bucket. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: str or ``NoneType`` + :returns: The self link for the bucket or ``None`` if + the bucket's resource has not been loaded from the server. + """ + return self._properties.get("selfLink") + + @property + def storage_class(self): + """Retrieve or set the storage class for the bucket. + + See https://cloud.google.com/storage/docs/storage-classes + + :setter: Set the storage class for this bucket. + :getter: Gets the the storage class for this bucket. + + :rtype: str or ``NoneType`` + :returns: + If set, one of + :attr:`~google.cloud.storage.constants.NEARLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.COLDLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.ARCHIVE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.STANDARD_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.MULTI_REGIONAL_LEGACY_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.REGIONAL_LEGACY_STORAGE_CLASS`, + or + :attr:`~google.cloud.storage.constants.DURABLE_REDUCED_AVAILABILITY_LEGACY_STORAGE_CLASS`, + else ``None``. + """ + return self._properties.get("storageClass") + + @storage_class.setter + def storage_class(self, value): + """Set the storage class for the bucket. + + See https://cloud.google.com/storage/docs/storage-classes + + :type value: str + :param value: + One of + :attr:`~google.cloud.storage.constants.NEARLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.COLDLINE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.ARCHIVE_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.STANDARD_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.MULTI_REGIONAL_LEGACY_STORAGE_CLASS`, + :attr:`~google.cloud.storage.constants.REGIONAL_LEGACY_STORAGE_CLASS`, + or + :attr:`~google.cloud.storage.constants.DURABLE_REDUCED_AVAILABILITY_LEGACY_STORAGE_CLASS`, + """ + self._patch_property("storageClass", value) + + @property + def time_created(self): + """Retrieve the timestamp at which the bucket was created. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the bucket's resource has not been loaded + from the server. + """ + value = self._properties.get("timeCreated") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def updated(self): + """Retrieve the timestamp at which the bucket was last updated. + + See https://cloud.google.com/storage/docs/json_api/v1/buckets + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the bucket's resource has not been loaded + from the server. + """ + value = self._properties.get("updated") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def versioning_enabled(self): + """Is versioning enabled for this bucket? + + See https://cloud.google.com/storage/docs/object-versioning for + details. + + :setter: Update whether versioning is enabled for this bucket. + :getter: Query whether versioning is enabled for this bucket. + + :rtype: bool + :returns: True if enabled, else False. + """ + versioning = self._properties.get("versioning", {}) + return versioning.get("enabled", False) + + @versioning_enabled.setter + def versioning_enabled(self, value): + """Enable versioning for this bucket. + + See https://cloud.google.com/storage/docs/object-versioning for + details. + + :type value: convertible to boolean + :param value: should versioning be enabled for the bucket? + """ + self._patch_property("versioning", {"enabled": bool(value)}) + + @property + def requester_pays(self): + """Does the requester pay for API requests for this bucket? + + See https://cloud.google.com/storage/docs/requester-pays for + details. + + :setter: Update whether requester pays for this bucket. + :getter: Query whether requester pays for this bucket. + + :rtype: bool + :returns: True if requester pays for API requests for the bucket, + else False. + """ + versioning = self._properties.get("billing", {}) + return versioning.get("requesterPays", False) + + @requester_pays.setter + def requester_pays(self, value): + """Update whether requester pays for API requests for this bucket. + + See https://cloud.google.com/storage/docs/using-requester-pays for + details. + + :type value: convertible to boolean + :param value: should requester pay for API requests for the bucket? + """ + self._patch_property("billing", {"requesterPays": bool(value)}) + + @property + def autoclass_enabled(self): + """Whether Autoclass is enabled for this bucket. + + See https://cloud.google.com/storage/docs/using-autoclass for details. + + :setter: Update whether autoclass is enabled for this bucket. + :getter: Query whether autoclass is enabled for this bucket. + + :rtype: bool + :returns: True if enabled, else False. + """ + autoclass = self._properties.get("autoclass", {}) + return autoclass.get("enabled", False) + + @autoclass_enabled.setter + def autoclass_enabled(self, value): + """Enable or disable Autoclass at the bucket-level. + + See https://cloud.google.com/storage/docs/using-autoclass for details. + + :type value: convertible to boolean + :param value: If true, enable Autoclass for this bucket. + If false, disable Autoclass for this bucket. + """ + autoclass = self._properties.get("autoclass", {}) + autoclass["enabled"] = bool(value) + self._patch_property("autoclass", autoclass) + + @property + def autoclass_toggle_time(self): + """Retrieve the toggle time when Autoclaass was last enabled or disabled for the bucket. + :rtype: datetime.datetime or ``NoneType`` + :returns: point-in time at which the bucket's autoclass is toggled, or ``None`` if the property is not set locally. + """ + autoclass = self._properties.get("autoclass") + if autoclass is not None: + timestamp = autoclass.get("toggleTime") + if timestamp is not None: + return _rfc3339_nanos_to_datetime(timestamp) + + @property + def autoclass_terminal_storage_class(self): + """The storage class that objects in an Autoclass bucket eventually transition to if + they are not read for a certain length of time. Valid values are NEARLINE and ARCHIVE. + + See https://cloud.google.com/storage/docs/using-autoclass for details. + + :setter: Set the terminal storage class for Autoclass configuration. + :getter: Get the terminal storage class for Autoclass configuration. + + :rtype: str + :returns: The terminal storage class if Autoclass is enabled, else ``None``. + """ + autoclass = self._properties.get("autoclass", {}) + return autoclass.get("terminalStorageClass", None) + + @autoclass_terminal_storage_class.setter + def autoclass_terminal_storage_class(self, value): + """The storage class that objects in an Autoclass bucket eventually transition to if + they are not read for a certain length of time. Valid values are NEARLINE and ARCHIVE. + + See https://cloud.google.com/storage/docs/using-autoclass for details. + + :type value: str + :param value: The only valid values are `"NEARLINE"` and `"ARCHIVE"`. + """ + autoclass = self._properties.get("autoclass", {}) + autoclass["terminalStorageClass"] = value + self._patch_property("autoclass", autoclass) + + @property + def autoclass_terminal_storage_class_update_time(self): + """The time at which the Autoclass terminal_storage_class field was last updated for this bucket + :rtype: datetime.datetime or ``NoneType`` + :returns: point-in time at which the bucket's terminal_storage_class is last updated, or ``None`` if the property is not set locally. + """ + autoclass = self._properties.get("autoclass") + if autoclass is not None: + timestamp = autoclass.get("terminalStorageClassUpdateTime") + if timestamp is not None: + return _rfc3339_nanos_to_datetime(timestamp) + + @property + def object_retention_mode(self): + """Retrieve the object retention mode set on the bucket. + + :rtype: str + :returns: When set to Enabled, retention configurations can be + set on objects in the bucket. + """ + object_retention = self._properties.get("objectRetention") + if object_retention is not None: + return object_retention.get("mode") + + @property + def hierarchical_namespace_enabled(self): + """Whether hierarchical namespace is enabled for this bucket. + + :setter: Update whether hierarchical namespace is enabled for this bucket. + :getter: Query whether hierarchical namespace is enabled for this bucket. + + :rtype: bool + :returns: True if enabled, else False. + """ + hns = self._properties.get("hierarchicalNamespace", {}) + return hns.get("enabled") + + @hierarchical_namespace_enabled.setter + def hierarchical_namespace_enabled(self, value): + """Enable or disable hierarchical namespace at the bucket-level. + + :type value: convertible to boolean + :param value: If true, enable hierarchical namespace for this bucket. + If false, disable hierarchical namespace for this bucket. + + .. note:: + To enable hierarchical namespace, you must set it at bucket creation time. + Currently, hierarchical namespace configuration cannot be changed after bucket creation. + """ + hns = self._properties.get("hierarchicalNamespace", {}) + hns["enabled"] = bool(value) + self._patch_property("hierarchicalNamespace", hns) + + def configure_website(self, main_page_suffix=None, not_found_page=None): + """Configure website-related properties. + + See https://cloud.google.com/storage/docs/static-website + + .. note:: + This configures the bucket's website-related properties,controlling how + the service behaves when accessing bucket contents as a web site. + See [tutorials](https://cloud.google.com/storage/docs/hosting-static-website) and + [code samples](https://cloud.google.com/storage/docs/samples/storage-define-bucket-website-configuration#storage_define_bucket_website_configuration-python) + for more information. + + :type main_page_suffix: str + :param main_page_suffix: The page to use as the main page + of a directory. + Typically something like index.html. + + :type not_found_page: str + :param not_found_page: The file to use when a page isn't found. + """ + data = { + "mainPageSuffix": main_page_suffix, + "notFoundPage": not_found_page, + } + self._patch_property("website", data) + + def disable_website(self): + """Disable the website configuration for this bucket. + + This is really just a shortcut for setting the website-related + attributes to ``None``. + """ + return self.configure_website(None, None) + + def get_iam_policy( + self, + client=None, + requested_policy_version=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Retrieve the IAM policy for the bucket. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy) + and a [code sample](https://cloud.google.com/storage/docs/samples/storage-view-bucket-iam-members#storage_view_bucket_iam_members-python). + + If :attr:`user_project` is set, bills the API request to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type requested_policy_version: int or ``NoneType`` + :param requested_policy_version: (Optional) The version of IAM policies to request. + If a policy with a condition is requested without + setting this, the server will return an error. + This must be set to a value of 3 to retrieve IAM + policies containing conditions. This is to prevent + client code that isn't aware of IAM conditions from + interpreting and modifying policies incorrectly. + The service might return a policy with version lower + than the one that was requested, based on the + feature syntax in the policy fetched. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: :class:`google.api_core.iam.Policy` + :returns: the policy instance, based on the resource returned from + the ``getIamPolicy`` API request. + """ + with create_trace_span(name="Storage.Bucket.getIamPolicy"): + client = self._require_client(client) + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + if requested_policy_version is not None: + query_params["optionsRequestedPolicyVersion"] = requested_policy_version + + info = client._get_resource( + f"{self.path}/iam", + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + return Policy.from_api_repr(info) + + def set_iam_policy( + self, + policy, + client=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY_IF_ETAG_IN_JSON, + ): + """Update the IAM policy for the bucket. + + See + https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy + + If :attr:`user_project` is set, bills the API request to that project. + + :type policy: :class:`google.api_core.iam.Policy` + :param policy: policy instance used to update bucket's IAM policy. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: :class:`google.api_core.iam.Policy` + :returns: the policy instance, based on the resource returned from + the ``setIamPolicy`` API request. + """ + with create_trace_span(name="Storage.Bucket.setIamPolicy"): + client = self._require_client(client) + query_params = {} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + path = f"{self.path}/iam" + resource = policy.to_api_repr() + resource["resourceId"] = self.path + + info = client._put_resource( + path, + resource, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + + return Policy.from_api_repr(info) + + def test_iam_permissions( + self, + permissions, + client=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """API call: test permissions + + See + https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions + + If :attr:`user_project` is set, bills the API request to that project. + + :type permissions: list of string + :param permissions: the permissions to check + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: list of string + :returns: the permissions returned by the ``testIamPermissions`` API + request. + """ + with create_trace_span(name="Storage.Bucket.testIamPermissions"): + client = self._require_client(client) + query_params = {"permissions": permissions} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + path = f"{self.path}/iam/testPermissions" + resp = client._get_resource( + path, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=None, + ) + return resp.get("permissions", []) + + def make_public( + self, + recursive=False, + future=False, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Update bucket's ACL, granting read access to anonymous users. + + :type recursive: bool + :param recursive: If True, this will make all blobs inside the bucket + public as well. + + :type future: bool + :param future: If True, this will make all objects created in the + future public as well. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + blob's current metageneration matches the given value. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + blob's current metageneration does not match the given value. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises ValueError: + If ``recursive`` is True, and the bucket contains more than 256 + blobs. This is to prevent extremely long runtime of this + method. For such buckets, iterate over the blobs returned by + :meth:`list_blobs` and call + :meth:`~google.cloud.storage.blob.Blob.make_public` + for each blob. + """ + with create_trace_span(name="Storage.Bucket.makePublic"): + self.acl.all().grant_read() + self.acl.save( + client=client, + timeout=timeout, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + if future: + doa = self.default_object_acl + if not doa.loaded: + doa.reload(client=client, timeout=timeout) + doa.all().grant_read() + doa.save( + client=client, + timeout=timeout, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + if recursive: + blobs = list( + self.list_blobs( + projection="full", + max_results=self._MAX_OBJECTS_FOR_ITERATION + 1, + client=client, + timeout=timeout, + ) + ) + if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION: + message = ( + "Refusing to make public recursively with more than " + "%d objects. If you actually want to make every object " + "in this bucket public, iterate through the blobs " + "returned by 'Bucket.list_blobs()' and call " + "'make_public' on each one." + ) % (self._MAX_OBJECTS_FOR_ITERATION,) + raise ValueError(message) + + for blob in blobs: + blob.acl.all().grant_read() + blob.acl.save( + client=client, + timeout=timeout, + ) + + def make_private( + self, + recursive=False, + future=False, + client=None, + timeout=_DEFAULT_TIMEOUT, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED, + ): + """Update bucket's ACL, revoking read access for anonymous users. + + :type recursive: bool + :param recursive: If True, this will make all blobs inside the bucket + private as well. + + :type future: bool + :param future: If True, this will make all objects created in the + future private as well. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + blob's current metageneration matches the given value. + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + blob's current metageneration does not match the given value. + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises ValueError: + If ``recursive`` is True, and the bucket contains more than 256 + blobs. This is to prevent extremely long runtime of this + method. For such buckets, iterate over the blobs returned by + :meth:`list_blobs` and call + :meth:`~google.cloud.storage.blob.Blob.make_private` + for each blob. + """ + with create_trace_span(name="Storage.Bucket.makePrivate"): + self.acl.all().revoke_read() + self.acl.save( + client=client, + timeout=timeout, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + if future: + doa = self.default_object_acl + if not doa.loaded: + doa.reload(client=client, timeout=timeout) + doa.all().revoke_read() + doa.save( + client=client, + timeout=timeout, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + + if recursive: + blobs = list( + self.list_blobs( + projection="full", + max_results=self._MAX_OBJECTS_FOR_ITERATION + 1, + client=client, + timeout=timeout, + ) + ) + if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION: + message = ( + "Refusing to make private recursively with more than " + "%d objects. If you actually want to make every object " + "in this bucket private, iterate through the blobs " + "returned by 'Bucket.list_blobs()' and call " + "'make_private' on each one." + ) % (self._MAX_OBJECTS_FOR_ITERATION,) + raise ValueError(message) + + for blob in blobs: + blob.acl.all().revoke_read() + blob.acl.save(client=client, timeout=timeout) + + def generate_upload_policy(self, conditions, expiration=None, client=None): + """Create a signed upload policy for uploading objects. + + This method generates and signs a policy document. You can use + [`policy documents`](https://cloud.google.com/storage/docs/xml-api/post-object-forms) + to allow visitors to a website to upload files to + Google Cloud Storage without giving them direct write access. + See a [code sample](https://cloud.google.com/storage/docs/xml-api/post-object-forms#python). + + :type expiration: datetime + :param expiration: (Optional) Expiration in UTC. If not specified, the + policy will expire in 1 hour. + + :type conditions: list + :param conditions: A list of conditions as described in the + `policy documents` documentation. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + + :rtype: dict + :returns: A dictionary of (form field name, form field value) of form + fields that should be added to your HTML upload form in order + to attach the signature. + """ + client = self._require_client(client) + credentials = client._credentials + _signing.ensure_signed_credentials(credentials) + + if expiration is None: + expiration = _NOW(_UTC).replace(tzinfo=None) + datetime.timedelta(hours=1) + + conditions = conditions + [{"bucket": self.name}] + + policy_document = { + "expiration": _datetime_to_rfc3339(expiration), + "conditions": conditions, + } + + encoded_policy_document = base64.b64encode( + json.dumps(policy_document).encode("utf-8") + ) + signature = base64.b64encode(credentials.sign_bytes(encoded_policy_document)) + + fields = { + "bucket": self.name, + "GoogleAccessId": credentials.signer_email, + "policy": encoded_policy_document.decode("utf-8"), + "signature": signature.decode("utf-8"), + } + + return fields + + def lock_retention_policy( + self, client=None, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY + ): + """Lock the bucket's retention policy. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the blob's bucket. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises ValueError: + if the bucket has no metageneration (i.e., new or never reloaded); + if the bucket has no retention policy assigned; + if the bucket's retention policy is already locked. + """ + with create_trace_span(name="Storage.Bucket.lockRetentionPolicy"): + if "metageneration" not in self._properties: + raise ValueError( + "Bucket has no retention policy assigned: try 'reload'?" + ) + + policy = self._properties.get("retentionPolicy") + + if policy is None: + raise ValueError( + "Bucket has no retention policy assigned: try 'reload'?" + ) + + if policy.get("isLocked"): + raise ValueError("Bucket's retention policy is already locked.") + + client = self._require_client(client) + + query_params = {"ifMetagenerationMatch": self.metageneration} + + if self.user_project is not None: + query_params["userProject"] = self.user_project + + path = f"/b/{self.name}/lockRetentionPolicy" + api_response = client._post_resource( + path, + None, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=self, + ) + self._set_properties(api_response) + + def generate_signed_url( + self, + expiration=None, + api_access_endpoint=None, + method="GET", + headers=None, + query_parameters=None, + client=None, + credentials=None, + version=None, + virtual_hosted_style=False, + bucket_bound_hostname=None, + scheme="http", + ): + """Generates a signed URL for this bucket. + + .. note:: + + If you are on Google Compute Engine, you can't generate a signed + URL using GCE service account. If you'd like to be able to generate + a signed URL from GCE, you can use a standard service account from a + JSON file rather than a GCE service account. + + If you have a bucket that you want to allow access to for a set + amount of time, you can use this method to generate a URL that + is only valid within a certain time period. + + If ``bucket_bound_hostname`` is set as an argument of :attr:`api_access_endpoint`, + ``https`` works only if using a ``CDN``. + + :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] + :param expiration: Point in time when the signed URL should expire. If + a ``datetime`` instance is passed without an explicit + ``tzinfo`` set, it will be assumed to be ``UTC``. + + :type api_access_endpoint: str + :param api_access_endpoint: (Optional) URI base, for instance + "https://storage.googleapis.com". If not specified, the client's + api_endpoint will be used. Incompatible with bucket_bound_hostname. + + :type method: str + :param method: The HTTP verb that will be used when requesting the URL. + + :type headers: dict + :param headers: + (Optional) Additional HTTP headers to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers + Requests using the signed URL *must* pass the specified header + (name and value) with each request for the URL. + + :type query_parameters: dict + :param query_parameters: + (Optional) Additional query parameters to be included as part of the + signed URLs. See: + https://cloud.google.com/storage/docs/xml-api/reference-headers#query + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the blob's bucket. + + :type credentials: :class:`google.auth.credentials.Credentials` or + :class:`NoneType` + :param 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. + + :type version: str + :param version: (Optional) The version of signed credential to create. + Must be one of 'v2' | 'v4'. + + :type virtual_hosted_style: bool + :param virtual_hosted_style: + (Optional) If true, then construct the URL relative the bucket's + virtual hostname, e.g., '.storage.googleapis.com'. + Incompatible with bucket_bound_hostname. + + :type bucket_bound_hostname: str + :param bucket_bound_hostname: + (Optional) If passed, then construct the URL relative to the bucket-bound hostname. + Value can be a bare or with scheme, e.g., 'example.com' or 'http://example.com'. + Incompatible with api_access_endpoint and virtual_hosted_style. + See: https://cloud.google.com/storage/docs/request-endpoints#cname + + :type scheme: str + :param scheme: + (Optional) If ``bucket_bound_hostname`` is passed as a bare hostname, use + this value as the scheme. ``https`` will work only when using a CDN. + Defaults to ``"http"``. + + :raises: :exc:`ValueError` when version is invalid or mutually exclusive arguments are used. + :raises: :exc:`TypeError` when expiration is not a valid type. + :raises: :exc:`AttributeError` if credentials is not an instance + of :class:`google.auth.credentials.Signing`. + + :rtype: str + :returns: A signed URL you can use to access the resource + until expiration. + """ + if version is None: + version = "v2" + elif version not in ("v2", "v4"): + raise ValueError("'version' must be either 'v2' or 'v4'") + + if ( + api_access_endpoint is not None or virtual_hosted_style + ) and bucket_bound_hostname: + raise ValueError( + "The bucket_bound_hostname argument is not compatible with " + "either api_access_endpoint or virtual_hosted_style." + ) + + if api_access_endpoint is None: + client = self._require_client(client) + api_access_endpoint = client.api_endpoint + + # If you are on Google Compute Engine, you can't generate a signed URL + # using GCE service account. + # See https://github.com/googleapis/google-auth-library-python/issues/50 + if virtual_hosted_style: + api_access_endpoint = _virtual_hosted_style_base_url( + api_access_endpoint, self.name + ) + resource = "/" + elif bucket_bound_hostname: + api_access_endpoint = _bucket_bound_hostname_url( + bucket_bound_hostname, scheme + ) + resource = "/" + else: + resource = f"/{self.name}" + + if credentials is None: + client = self._require_client(client) # May be redundant, but that's ok. + credentials = client._credentials + + if version == "v2": + helper = generate_signed_url_v2 + else: + helper = generate_signed_url_v4 + + return helper( + credentials, + resource=resource, + expiration=expiration, + api_access_endpoint=api_access_endpoint, + method=method.upper(), + headers=headers, + query_parameters=query_parameters, + ) + + @property + def ip_filter(self): + """Retrieve or set the IP Filter configuration for this bucket. + + See https://cloud.google.com/storage/docs/ip-filtering-overview and + https://cloud.google.com/storage/docs/json_api/v1/buckets#ipFilter + + .. note:: + The getter for this property returns an + :class:`~google.cloud.storage.ip_filter.IPFilter` object, which is a + structured representation of the bucket's IP filter configuration. + Modifying the returned object has no effect. To update the bucket's + IP filter, create and assign a new ``IPFilter`` object to this + property and then call + :meth:`~google.cloud.storage.bucket.Bucket.patch`. + + .. code-block:: python + + from google.cloud.storage.ip_filter import ( + IPFilter, + PublicNetworkSource, + ) + + ip_filter = IPFilter() + ip_filter.mode = "Enabled" + ip_filter.public_network_source = PublicNetworkSource( + allowed_ip_cidr_ranges=["203.0.113.5/32"] + ) + bucket.ip_filter = ip_filter + bucket.patch() + + :setter: Set the IP Filter configuration for this bucket. + :getter: Gets the IP Filter configuration for this bucket. + + :rtype: :class:`~google.cloud.storage.ip_filter.IPFilter` or ``NoneType`` + :returns: + An ``IPFilter`` object representing the configuration, or ``None`` + if no filter is configured. + """ + resource = self._properties.get(_IP_FILTER_PROPERTY) + if resource: + return IPFilter._from_api_resource(resource) + return None + + @ip_filter.setter + def ip_filter(self, value): + if value is None: + self._patch_property(_IP_FILTER_PROPERTY, None) + elif isinstance(value, IPFilter): + self._patch_property(_IP_FILTER_PROPERTY, value._to_api_resource()) + else: + self._patch_property(_IP_FILTER_PROPERTY, value) + + +class EncryptionEnforcementConfig(dict): + """Map a bucket's encryption enforcement configuration. + + :type restriction_mode: str + :param restriction_mode: + (Optional) The restriction mode for the encryption type. + When set to ``FullyRestricted``, the bucket will only allow objects encrypted with the encryption type corresponding to this configuration. + When set to ``NotRestricted``, the bucket will allow objects encrypted with any encryption type. + + :type effective_time: :class:`datetime.datetime` + :param effective_time: + (Output only) The time when the encryption enforcement configuration became effective. + """ + + def __init__(self, restriction_mode=None): + data = {} + if restriction_mode is not None: + # Validate input against allowed constants + allowed = ( + ENFORCEMENT_MODE_FULLY_RESTRICTED, + ENFORCEMENT_MODE_NOT_RESTRICTED, + ) + if restriction_mode not in allowed: + raise ValueError( + f"Invalid restriction_mode: {restriction_mode}. " + f"Must be one of {allowed}" + ) + data["restrictionMode"] = restriction_mode + + super().__init__(data) + + @classmethod + def from_api_repr(cls, resource): + """Factory: construct instance from resource. + + :type resource: dict + :param resource: mapping as returned from API call. + + :rtype: :class:`EncryptionEnforcementConfig` + :returns: Instance created from resource. + """ + instance = cls() + instance.update(resource) + return instance + + @property + def restriction_mode(self): + """Get the restriction mode. + + :rtype: str or ``NoneType`` + :returns: The restriction mode or ``None`` if the property is not set. + """ + return self.get("restrictionMode") + + @restriction_mode.setter + def restriction_mode(self, value): + """Set the restriction mode. + + :type value: str + :param value: The restriction mode. + """ + self["restrictionMode"] = value + + @property + def effective_time(self): + """Get the effective time. + + :rtype: datetime.datetime or ``NoneType`` + :returns: point-in time at which the configuration is effective, + or ``None`` if the property is not set. + """ + timestamp = self.get("effectiveTime") + if timestamp is not None: + return _rfc3339_nanos_to_datetime(timestamp) + + +class BucketEncryption(dict): + """Map a bucket's encryption configuration. + + :type bucket: :class:`Bucket` + :param bucket: Bucket for which this instance is the policy. + + :type default_kms_key_name: str + :param default_kms_key_name: + (Optional) Resource name of KMS key used to encrypt bucket's content. + + :type google_managed_encryption_enforcement_config: :class:`EncryptionEnforcementConfig` + :param google_managed_encryption_enforcement_config: + (Optional) Encryption enforcement configuration for Google managed encryption. + + :type customer_managed_encryption_enforcement_config: :class:`EncryptionEnforcementConfig` + :param customer_managed_encryption_enforcement_config: + (Optional) Encryption enforcement configuration for Customer managed encryption. + + :type customer_supplied_encryption_enforcement_config: :class:`EncryptionEnforcementConfig` + :param customer_supplied_encryption_enforcement_config: + (Optional) Encryption enforcement configuration for Customer supplied encryption. + """ + + def __init__( + self, + bucket, + default_kms_key_name=None, + google_managed_encryption_enforcement_config=None, + customer_managed_encryption_enforcement_config=None, + customer_supplied_encryption_enforcement_config=None, + ): + data = {} + if default_kms_key_name is not None: + data["defaultKmsKeyName"] = default_kms_key_name + + if google_managed_encryption_enforcement_config is not None: + data["googleManagedEncryptionEnforcementConfig"] = ( + google_managed_encryption_enforcement_config + ) + + if customer_managed_encryption_enforcement_config is not None: + data["customerManagedEncryptionEnforcementConfig"] = ( + customer_managed_encryption_enforcement_config + ) + + if customer_supplied_encryption_enforcement_config is not None: + data["customerSuppliedEncryptionEnforcementConfig"] = ( + customer_supplied_encryption_enforcement_config + ) + + super().__init__(data) + self._bucket = bucket + + @classmethod + def from_api_repr(cls, resource, bucket): + """Factory: construct instance from resource. + + :type resource: dict + :param resource: mapping as returned from API call. + + :type bucket: :class:`Bucket` + :params bucket: Bucket for which this instance is the policy. + + :rtype: :class:`BucketEncryption` + :returns: Instance created from resource. + """ + instance = cls(bucket) + instance.update(resource) + return instance + + @property + def bucket(self): + """Bucket for which this instance is the policy. + + :rtype: :class:`Bucket` + :returns: the instance's bucket. + """ + return self._bucket + + @property + def default_kms_key_name(self): + """Retrieve default KMS encryption key for objects in the bucket. + + :rtype: str or ``NoneType`` + :returns: Default KMS encryption key, or ``None`` if not set. + """ + return self.get("defaultKmsKeyName") + + @default_kms_key_name.setter + def default_kms_key_name(self, value): + """Set default KMS encryption key for objects in the bucket. + + :type value: str or None + :param value: new KMS key name (None to clear any existing key). + """ + self["defaultKmsKeyName"] = value + self.bucket._patch_property("encryption", self) + + @property + def google_managed_encryption_enforcement_config(self): + """Retrieve the encryption enforcement configuration for Google managed encryption. + + :rtype: :class:`EncryptionEnforcementConfig` + :returns: The configuration instance. + """ + data = self.get("googleManagedEncryptionEnforcementConfig") + if data: + return EncryptionEnforcementConfig.from_api_repr(data) + return None + + @google_managed_encryption_enforcement_config.setter + def google_managed_encryption_enforcement_config(self, value): + """Set the encryption enforcement configuration for Google managed encryption. + + :type value: :class:`EncryptionEnforcementConfig` or dict + :param value: The configuration instance or dictionary. + """ + self["googleManagedEncryptionEnforcementConfig"] = value + self.bucket._patch_property("encryption", self) + + @property + def customer_managed_encryption_enforcement_config(self): + """Retrieve the encryption enforcement configuration for Customer managed encryption. + + :rtype: :class:`EncryptionEnforcementConfig` + :returns: The configuration instance. + """ + data = self.get("customerManagedEncryptionEnforcementConfig") + if data: + return EncryptionEnforcementConfig.from_api_repr(data) + return None + + @customer_managed_encryption_enforcement_config.setter + def customer_managed_encryption_enforcement_config(self, value): + """Set the encryption enforcement configuration for Customer managed encryption. + + :type value: :class:`EncryptionEnforcementConfig` or dict + :param value: The configuration instance or dictionary. + """ + self["customerManagedEncryptionEnforcementConfig"] = value + self.bucket._patch_property("encryption", self) + + @property + def customer_supplied_encryption_enforcement_config(self): + """Retrieve the encryption enforcement configuration for Customer supplied encryption. + + :rtype: :class:`EncryptionEnforcementConfig` + :returns: The configuration instance. + """ + data = self.get("customerSuppliedEncryptionEnforcementConfig") + if data: + return EncryptionEnforcementConfig.from_api_repr(data) + return None + + @customer_supplied_encryption_enforcement_config.setter + def customer_supplied_encryption_enforcement_config(self, value): + """Set the encryption enforcement configuration for Customer supplied encryption. + + :type value: :class:`EncryptionEnforcementConfig` or dict + :param value: The configuration instance or dictionary. + """ + self["customerSuppliedEncryptionEnforcementConfig"] = value + self.bucket._patch_property("encryption", self) + + +class SoftDeletePolicy(dict): + """Map a bucket's soft delete policy. + + See https://cloud.google.com/storage/docs/soft-delete + + :type bucket: :class:`Bucket` + :param bucket: Bucket for which this instance is the policy. + + :type retention_duration_seconds: int + :param retention_duration_seconds: + (Optional) The period of time in seconds that soft-deleted objects in the bucket + will be retained and cannot be permanently deleted. + + :type effective_time: :class:`datetime.datetime` + :param effective_time: + (Optional) When the bucket's soft delete policy is effective. + This value should normally only be set by the back-end API. + """ + + def __init__(self, bucket, **kw): + data = {} + retention_duration_seconds = kw.get("retention_duration_seconds") + data["retentionDurationSeconds"] = retention_duration_seconds + + effective_time = kw.get("effective_time") + if effective_time is not None: + effective_time = _datetime_to_rfc3339(effective_time) + data["effectiveTime"] = effective_time + + super().__init__(data) + self._bucket = bucket + + @classmethod + def from_api_repr(cls, resource, bucket): + """Factory: construct instance from resource. + + :type resource: dict + :param resource: mapping as returned from API call. + + :type bucket: :class:`Bucket` + :params bucket: Bucket for which this instance is the policy. + + :rtype: :class:`SoftDeletePolicy` + :returns: Instance created from resource. + """ + instance = cls(bucket) + instance.update(resource) + return instance + + @property + def bucket(self): + """Bucket for which this instance is the policy. + + :rtype: :class:`Bucket` + :returns: the instance's bucket. + """ + return self._bucket + + @property + def retention_duration_seconds(self): + """Get the retention duration of the bucket's soft delete policy. + + :rtype: int or ``NoneType`` + :returns: The period of time in seconds that soft-deleted objects in the bucket + will be retained and cannot be permanently deleted; Or ``None`` if the + property is not set. + """ + duration = self.get("retentionDurationSeconds") + if duration is not None: + return int(duration) + + @retention_duration_seconds.setter + def retention_duration_seconds(self, value): + """Set the retention duration of the bucket's soft delete policy. + + :type value: int + :param value: + The period of time in seconds that soft-deleted objects in the bucket + will be retained and cannot be permanently deleted. + """ + self["retentionDurationSeconds"] = value + self.bucket._patch_property("softDeletePolicy", self) + + @property + def effective_time(self): + """Get the effective time of the bucket's soft delete policy. + + :rtype: datetime.datetime or ``NoneType`` + :returns: point-in time at which the bucket's soft delte policy is + effective, or ``None`` if the property is not set. + """ + timestamp = self.get("effectiveTime") + if timestamp is not None: + return _rfc3339_nanos_to_datetime(timestamp) + + +def _raise_if_len_differs(expected_len, **generation_match_args): + """ + Raise an error if any generation match argument + is set and its len differs from the given value. + + :type expected_len: int + :param expected_len: Expected argument length in case it's set. + + :type generation_match_args: dict + :param generation_match_args: Lists, which length must be checked. + + :raises: :exc:`ValueError` if any argument set, but has an unexpected length. + """ + for name, value in generation_match_args.items(): + if value is not None and len(value) != expected_len: + raise ValueError(f"'{name}' length must be the same as 'blobs' length") diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/client.py new file mode 100644 index 0000000000000000000000000000000000000000..85575f067b2ddf1126d8cb7d03e19cff481b1649 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/client.py @@ -0,0 +1,2021 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Client for interacting with the Google Cloud Storage API.""" + +import base64 +import binascii +import collections +import datetime +import functools +import json +import os +import warnings +import google.api_core.client_options + +from google.auth.credentials import AnonymousCredentials +from google.auth.transport import mtls +from google.api_core import page_iterator +from google.cloud._helpers import _LocalStack +from google.cloud.client import ClientWithProject +from google.cloud.exceptions import NotFound + +from google.cloud.storage._helpers import _add_generation_match_parameters +from google.cloud.storage._helpers import _bucket_bound_hostname_url +from google.cloud.storage._helpers import _get_api_endpoint_override +from google.cloud.storage._helpers import _get_environ_project +from google.cloud.storage._helpers import _get_storage_emulator_override +from google.cloud.storage._helpers import _virtual_hosted_style_base_url +from google.cloud.storage._helpers import _DEFAULT_UNIVERSE_DOMAIN +from google.cloud.storage._helpers import _DEFAULT_SCHEME +from google.cloud.storage._helpers import _STORAGE_HOST_TEMPLATE +from google.cloud.storage._helpers import _NOW +from google.cloud.storage._helpers import _UTC +from google.cloud.storage._opentelemetry_tracing import create_trace_span + +from google.cloud.storage._http import Connection +from google.cloud.storage._signing import ( + get_expiration_seconds_v4, + get_v4_now_dtstamps, + ensure_signed_credentials, + _sign_message, +) +from google.cloud.storage.batch import Batch +from google.cloud.storage.bucket import Bucket, _item_to_blob, _blobs_page_start +from google.cloud.storage.blob import Blob +from google.cloud.storage.hmac_key import HMACKeyMetadata +from google.cloud.storage.acl import BucketACL +from google.cloud.storage.acl import DefaultObjectACL +from google.cloud.storage.constants import _DEFAULT_TIMEOUT +from google.cloud.storage.retry import DEFAULT_RETRY + + +_marker = object() + + +def _buckets_page_start(iterator, page, response): + """Grab unreachable buckets after a :class:`~google.cloud.iterator.Page` started.""" + unreachable = response.get("unreachable", []) + if not isinstance(unreachable, list): + raise TypeError( + f"expected unreachable to be list, but obtained {type(unreachable)}" + ) + page.unreachable = unreachable + + +class Client(ClientWithProject): + """Client to bundle configuration needed for API requests. + + :type project: str or None + :param project: the project which the client acts on behalf of. Will be + passed when creating a topic. If not passed, + falls back to the default inferred from the environment. + + :type credentials: :class:`~google.auth.credentials.Credentials` + :param credentials: (Optional) The OAuth2 Credentials to use for this + client. If not passed (and if no ``_http`` object is + passed), falls back to the default inferred from the + environment. + + :type _http: :class:`~requests.Session` + :param _http: (Optional) HTTP object to make requests. Can be any object + that defines ``request()`` with the same interface as + :meth:`requests.Session.request`. If not passed, an + ``_http`` object is created that is bound to the + ``credentials`` for the current object. + This parameter should be considered private, and could + change in the future. + + :type client_info: :class:`~google.api_core.client_info.ClientInfo` + :param client_info: + 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 library + or partner tool. + + :type client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict` + :param client_options: (Optional) Client options used to set user options on the client. + A non-default universe domain or api endpoint should be set through client_options. + + :type use_auth_w_custom_endpoint: bool + :param use_auth_w_custom_endpoint: + (Optional) Whether authentication is required under custom endpoints. + If false, uses AnonymousCredentials and bypasses authentication. + Defaults to True. Note this is only used when a custom endpoint is set in conjunction. + + :type extra_headers: dict + :param extra_headers: + (Optional) Custom headers to be sent with the requests attached to the client. + For example, you can add custom audit logging headers. + + :type api_key: string + :param api_key: + (Optional) An API key. Mutually exclusive with any other credentials. + This parameter is an alias for setting `client_options.api_key` and + will supercede any api key set in the `client_options` parameter. + """ + + SCOPE = ( + "https://www.googleapis.com/auth/devstorage.full_control", + "https://www.googleapis.com/auth/devstorage.read_only", + "https://www.googleapis.com/auth/devstorage.read_write", + ) + """The scopes required for authenticating as a Cloud Storage consumer.""" + + def __init__( + self, + project=_marker, + credentials=None, + _http=None, + client_info=None, + client_options=None, + use_auth_w_custom_endpoint=True, + extra_headers={}, + *, + api_key=None, + ): + self._base_connection = None + + if project is None: + no_project = True + project = "" + else: + no_project = False + + if project is _marker: + project = None + + # Save the initial value of constructor arguments before they + # are passed along, for use in __reduce__ defined elsewhere. + self._initial_client_info = client_info + self._initial_client_options = client_options + self._extra_headers = extra_headers + + connection_kw_args = {"client_info": client_info} + + # api_key should set client_options.api_key. Set it here whether + # client_options was specified as a dict, as a ClientOptions object, or + # None. + if api_key: + if client_options and not isinstance(client_options, dict): + client_options.api_key = api_key + else: + if not client_options: + client_options = {} + client_options["api_key"] = api_key + + if client_options: + if isinstance(client_options, dict): + client_options = google.api_core.client_options.from_dict( + client_options + ) + + if client_options and client_options.universe_domain: + self._universe_domain = client_options.universe_domain + else: + self._universe_domain = None + + storage_emulator_override = _get_storage_emulator_override() + api_endpoint_override = _get_api_endpoint_override() + + # Determine the api endpoint. The rules are as follows: + + # 1. If the `api_endpoint` is set in `client_options`, use that as the + # endpoint. + if client_options and client_options.api_endpoint: + api_endpoint = client_options.api_endpoint + + # 2. Elif the "STORAGE_EMULATOR_HOST" env var is set, then use that as the + # endpoint. + elif storage_emulator_override: + api_endpoint = storage_emulator_override + + # 3. Elif the "API_ENDPOINT_OVERRIDE" env var is set, then use that as the + # endpoint. + elif api_endpoint_override: + api_endpoint = api_endpoint_override + + # 4. Elif the `universe_domain` is set in `client_options`, + # create the endpoint using that as the default. + # + # Mutual TLS is not compatible with a non-default universe domain + # at this time. If such settings are enabled along with the + # "GOOGLE_API_USE_CLIENT_CERTIFICATE" env variable, a ValueError will + # be raised. + + elif self._universe_domain: + # The final decision of whether to use mTLS takes place in + # google-auth-library-python. We peek at the environment variable + # here only to issue an exception in case of a conflict. + use_client_cert = False + if hasattr(mtls, "should_use_client_cert"): + use_client_cert = mtls.should_use_client_cert() + else: + use_client_cert = ( + os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE") == "true" + ) + + if use_client_cert: + raise ValueError( + 'The "GOOGLE_API_USE_CLIENT_CERTIFICATE" env variable is ' + 'set to "true" and a non-default universe domain is ' + "configured. mTLS is not supported in any universe other than" + "googleapis.com." + ) + api_endpoint = _DEFAULT_SCHEME + _STORAGE_HOST_TEMPLATE.format( + universe_domain=self._universe_domain + ) + + # 5. Else, use the default, which is to use the default + # universe domain of "googleapis.com" and create the endpoint + # "storage.googleapis.com" from that. + else: + api_endpoint = None + + connection_kw_args["api_endpoint"] = api_endpoint + + self._is_emulator_set = True if storage_emulator_override else False + + # If a custom endpoint is set, the client checks for credentials + # or finds the default credentials based on the current environment. + # Authentication may be bypassed under certain conditions: + # (1) STORAGE_EMULATOR_HOST is set (for backwards compatibility), OR + # (2) use_auth_w_custom_endpoint is set to False. + if connection_kw_args["api_endpoint"] is not None: + if self._is_emulator_set or not use_auth_w_custom_endpoint: + if credentials is None: + credentials = AnonymousCredentials() + if project is None: + project = _get_environ_project() + if project is None: + no_project = True + project = "" + + super(Client, self).__init__( + project=project, + credentials=credentials, + client_options=client_options, + _http=_http, + ) + + # Validate that the universe domain of the credentials matches the + # universe domain of the client. + if self._credentials.universe_domain != self.universe_domain: + raise ValueError( + "The configured universe domain ({client_ud}) does not match " + "the universe domain found in the credentials ({cred_ud}). If " + "you haven't configured the universe domain explicitly, " + "`googleapis.com` is the default.".format( + client_ud=self.universe_domain, + cred_ud=self._credentials.universe_domain, + ) + ) + + if no_project: + self.project = None + + # Pass extra_headers to Connection + connection = Connection(self, **connection_kw_args) + connection.extra_headers = extra_headers + self._connection = connection + self._batch_stack = _LocalStack() + + @classmethod + def create_anonymous_client(cls): + """Factory: return client with anonymous credentials. + + .. note:: + + Such a client has only limited access to "public" buckets: + listing their contents and downloading their blobs. + + :rtype: :class:`google.cloud.storage.client.Client` + :returns: Instance w/ anonymous credentials and no project. + """ + client = cls(project="", credentials=AnonymousCredentials()) + client.project = None + return client + + @property + def universe_domain(self): + return self._universe_domain or _DEFAULT_UNIVERSE_DOMAIN + + @property + def api_endpoint(self): + return self._connection.API_BASE_URL + + def update_user_agent(self, user_agent): + """Update the user-agent string for this client. + + :type user_agent: str + :param user_agent: The string to add to the user-agent. + """ + existing_user_agent = self._connection._client_info.user_agent + if existing_user_agent is None: + self._connection.user_agent = user_agent + else: + self._connection.user_agent = f"{user_agent} {existing_user_agent}" + + @property + def _connection(self): + """Get connection or batch on the client. + + :rtype: :class:`google.cloud.storage._http.Connection` + :returns: The connection set on the client, or the batch + if one is set. + """ + if self.current_batch is not None: + return self.current_batch + else: + return self._base_connection + + @_connection.setter + def _connection(self, value): + """Set connection on the client. + + Intended to be used by constructor (since the base class calls) + self._connection = connection + Will raise if the connection is set more than once. + + :type value: :class:`google.cloud.storage._http.Connection` + :param value: The connection set on the client. + + :raises: :class:`ValueError` if connection has already been set. + """ + if self._base_connection is not None: + raise ValueError("Connection already set on client") + self._base_connection = value + + def _push_batch(self, batch): + """Push a batch onto our stack. + + "Protected", intended for use by batch context mgrs. + + :type batch: :class:`google.cloud.storage.batch.Batch` + :param batch: newly-active batch + """ + self._batch_stack.push(batch) + + def _pop_batch(self): + """Pop a batch from our stack. + + "Protected", intended for use by batch context mgrs. + + :raises: IndexError if the stack is empty. + :rtype: :class:`google.cloud.storage.batch.Batch` + :returns: the top-most batch/transaction, after removing it. + """ + return self._batch_stack.pop() + + @property + def current_batch(self): + """Currently-active batch. + + :rtype: :class:`google.cloud.storage.batch.Batch` or ``NoneType`` (if + no batch is active). + :returns: The batch at the top of the batch stack. + """ + return self._batch_stack.top + + def get_service_account_email( + self, project=None, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY + ): + """Get the email address of the project's GCS service account + + :type project: str + :param project: + (Optional) Project ID to use for retreiving GCS service account + email address. Defaults to the client's project. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: str + :returns: service account email address + """ + with create_trace_span(name="Storage.Client.getServiceAccountEmail"): + if project is None: + project = self.project + + path = f"/projects/{project}/serviceAccount" + api_response = self._get_resource(path, timeout=timeout, retry=retry) + return api_response["email_address"] + + def bucket(self, bucket_name, user_project=None, generation=None): + """Factory constructor for bucket object. + + .. note:: + This will not make an HTTP request; it simply instantiates + a bucket object owned by this client. + + :type bucket_name: str + :param bucket_name: The name of the bucket to be instantiated. + + :type user_project: str + :param user_project: (Optional) The project ID to be billed for API + requests made via the bucket. + + :type generation: int + :param generation: (Optional) If present, selects a specific revision of + this bucket. + + :rtype: :class:`google.cloud.storage.bucket.Bucket` + :returns: The bucket object created. + """ + return Bucket( + client=self, + name=bucket_name, + user_project=user_project, + generation=generation, + ) + + def batch(self, raise_exception=True): + """Factory constructor for batch object. + + .. note:: + This will not make an HTTP request; it simply instantiates + a batch object owned by this client. + + :type raise_exception: bool + :param raise_exception: + (Optional) Defaults to True. If True, instead of adding exceptions + to the list of return responses, the final exception will be raised. + Note that exceptions are unwrapped after all operations are complete + in success or failure, and only the last exception is raised. + + :rtype: :class:`google.cloud.storage.batch.Batch` + :returns: The batch object created. + """ + return Batch(client=self, raise_exception=raise_exception) + + def _get_resource( + self, + path, + query_params=None, + headers=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + _target_object=None, + ): + """Helper for bucket / blob methods making API 'GET' calls. + + Args: + path str: + The path of the resource to fetch. + + query_params Optional[dict]: + HTTP query parameters to be passed + + headers Optional[dict]: + HTTP headers to be passed + + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + _target_object (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + :class:`~google.cloud.storage.bucket.blob`, \ + ]): + Object to which future data is to be applied -- only relevant + in the context of a batch. + + Returns: + dict + The JSON resource fetched + + Raises: + google.cloud.exceptions.NotFound + If the bucket is not found. + """ + return self._connection.api_request( + method="GET", + path=path, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=_target_object, + ) + + def _list_resource( + self, + path, + item_to_value, + page_token=None, + max_results=None, + extra_params=None, + page_start=page_iterator._do_nothing_page_start, + page_size=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + kwargs = { + "method": "GET", + "path": path, + "timeout": timeout, + } + with create_trace_span( + name="Storage.Client._list_resource_returns_iterator", + client=self, + api_request=kwargs, + retry=retry, + ): + api_request = functools.partial( + self._connection.api_request, timeout=timeout, retry=retry + ) + return page_iterator.HTTPIterator( + client=self, + api_request=api_request, + path=path, + item_to_value=item_to_value, + page_token=page_token, + max_results=max_results, + extra_params=extra_params, + page_start=page_start, + page_size=page_size, + ) + + def _patch_resource( + self, + path, + data, + query_params=None, + headers=None, + timeout=_DEFAULT_TIMEOUT, + retry=None, + _target_object=None, + ): + """Helper for bucket / blob methods making API 'PATCH' calls. + + Args: + path str: + The path of the resource to fetch. + + data dict: + The data to be patched. + + query_params Optional[dict]: + HTTP query parameters to be passed + + headers Optional[dict]: + HTTP headers to be passed + + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + _target_object (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + :class:`~google.cloud.storage.bucket.blob`, \ + ]): + Object to which future data is to be applied -- only relevant + in the context of a batch. + + Returns: + dict + The JSON resource fetched + + Raises: + google.cloud.exceptions.NotFound + If the bucket is not found. + """ + return self._connection.api_request( + method="PATCH", + path=path, + data=data, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=_target_object, + ) + + def _put_resource( + self, + path, + data, + query_params=None, + headers=None, + timeout=_DEFAULT_TIMEOUT, + retry=None, + _target_object=None, + ): + """Helper for bucket / blob methods making API 'PUT' calls. + + Args: + path str: + The path of the resource to fetch. + + data dict: + The data to be patched. + + query_params Optional[dict]: + HTTP query parameters to be passed + + headers Optional[dict]: + HTTP headers to be passed + + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + _target_object (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + :class:`~google.cloud.storage.bucket.blob`, \ + ]): + Object to which future data is to be applied -- only relevant + in the context of a batch. + + Returns: + dict + The JSON resource fetched + + Raises: + google.cloud.exceptions.NotFound + If the bucket is not found. + """ + return self._connection.api_request( + method="PUT", + path=path, + data=data, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=_target_object, + ) + + def _post_resource( + self, + path, + data, + query_params=None, + headers=None, + timeout=_DEFAULT_TIMEOUT, + retry=None, + _target_object=None, + ): + """Helper for bucket / blob methods making API 'POST' calls. + + Args: + path str: + The path of the resource to which to post. + + data dict: + The data to be posted. + + query_params Optional[dict]: + HTTP query parameters to be passed + + headers Optional[dict]: + HTTP headers to be passed + + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + _target_object (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + :class:`~google.cloud.storage.bucket.blob`, \ + ]): + Object to which future data is to be applied -- only relevant + in the context of a batch. + + Returns: + dict + The JSON resource returned from the post. + + Raises: + google.cloud.exceptions.NotFound + If the bucket is not found. + """ + + return self._connection.api_request( + method="POST", + path=path, + data=data, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=_target_object, + ) + + def _delete_resource( + self, + path, + query_params=None, + headers=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + _target_object=None, + ): + """Helper for bucket / blob methods making API 'DELETE' calls. + + Args: + path str: + The path of the resource to delete. + + query_params Optional[dict]: + HTTP query parameters to be passed + + headers Optional[dict]: + HTTP headers to be passed + + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + _target_object (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + :class:`~google.cloud.storage.bucket.blob`, \ + ]): + Object to which future data is to be applied -- only relevant + in the context of a batch. + + Returns: + dict + The JSON resource fetched + + Raises: + google.cloud.exceptions.NotFound + If the bucket is not found. + """ + return self._connection.api_request( + method="DELETE", + path=path, + query_params=query_params, + headers=headers, + timeout=timeout, + retry=retry, + _target_object=_target_object, + ) + + def _bucket_arg_to_bucket(self, bucket_or_name, generation=None): + """Helper to return given bucket or create new by name. + + Args: + bucket_or_name (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + str, \ + ]): + The bucket resource to pass or name to create. + generation (Optional[int]): + The bucket generation. If generation is specified, + bucket_or_name must be a name (str). + + Returns: + google.cloud.storage.bucket.Bucket + The newly created bucket or the given one. + """ + if isinstance(bucket_or_name, Bucket): + if generation: + raise ValueError( + "The generation can only be specified if a " + "name is used to specify a bucket, not a Bucket object. " + "Create a new Bucket object with the correct generation " + "instead." + ) + bucket = bucket_or_name + if bucket.client is None: + bucket._client = self + else: + bucket = Bucket(self, name=bucket_or_name, generation=generation) + return bucket + + def get_bucket( + self, + bucket_or_name, + timeout=_DEFAULT_TIMEOUT, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + *, + generation=None, + soft_deleted=None, + ): + """Retrieve a bucket via a GET request. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/buckets/get) and a [code sample](https://cloud.google.com/storage/docs/samples/storage-get-bucket-metadata#storage_get_bucket_metadata-python). + + Args: + bucket_or_name (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + str, \ + ]): + The bucket resource to pass or name to create. + + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + if_metageneration_match (Optional[int]): + Make the operation conditional on whether the + bucket's current metageneration matches the given value. + + if_metageneration_not_match (Optional[int]): + Make the operation conditional on whether the bucket's + current metageneration does not match the given value. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + generation (Optional[int]): + The generation of the bucket. The generation can be used to + specify a specific soft-deleted version of the bucket, in + conjunction with the ``soft_deleted`` argument below. If + ``soft_deleted`` is not True, the generation is unused. + + soft_deleted (Optional[bool]): + If True, looks for a soft-deleted bucket. Will only return + the bucket metadata if the bucket exists and is in a + soft-deleted state. The bucket ``generation`` is required if + ``soft_deleted`` is set to True. + See: https://cloud.google.com/storage/docs/soft-delete + + Returns: + google.cloud.storage.bucket.Bucket + The bucket matching the name provided. + + Raises: + google.cloud.exceptions.NotFound + If the bucket is not found. + """ + with create_trace_span(name="Storage.Client.getBucket"): + bucket = self._bucket_arg_to_bucket(bucket_or_name, generation=generation) + bucket.reload( + client=self, + timeout=timeout, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + soft_deleted=soft_deleted, + ) + return bucket + + def lookup_bucket( + self, + bucket_name, + timeout=_DEFAULT_TIMEOUT, + if_metageneration_match=None, + if_metageneration_not_match=None, + retry=DEFAULT_RETRY, + ): + """Get a bucket by name, returning None if not found. + + You can use this if you would rather check for a None value + than catching a NotFound exception. + + :type bucket_name: str + :param bucket_name: The name of the bucket to get. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type if_metageneration_match: long + :param if_metageneration_match: (Optional) Make the operation conditional on whether the + blob's current metageneration matches the given value. + + :type if_metageneration_not_match: long + :param if_metageneration_not_match: (Optional) Make the operation conditional on whether the + blob's current metageneration does not match the given value. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: :class:`google.cloud.storage.bucket.Bucket` or ``NoneType`` + :returns: The bucket matching the name provided or None if not found. + """ + with create_trace_span(name="Storage.Client.lookupBucket"): + try: + return self.get_bucket( + bucket_name, + timeout=timeout, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + retry=retry, + ) + except NotFound: + return None + + def create_bucket( + self, + bucket_or_name, + requester_pays=None, + project=None, + user_project=None, + location=None, + data_locations=None, + predefined_acl=None, + predefined_default_object_acl=None, + enable_object_retention=False, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Create a new bucket via a POST request. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/buckets/insert) and a [code sample](https://cloud.google.com/storage/docs/samples/storage-create-bucket#storage_create_bucket-python). + + Args: + bucket_or_name (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + str, \ + ]): + The bucket resource to pass or name to create. + requester_pays (bool): + DEPRECATED. Use Bucket().requester_pays instead. + (Optional) Whether requester pays for API requests for + this bucket and its blobs. + project (str): + (Optional) The project under which the bucket is to be created. + If not passed, uses the project set on the client. + user_project (str): + (Optional) The project ID to be billed for API requests + made via created bucket. + location (str): + (Optional) The location of the bucket. If not passed, + the default location, US, will be used. If specifying a dual-region, + `data_locations` should be set in conjunction. See: + https://cloud.google.com/storage/docs/locations + data_locations (list of str): + (Optional) The list of regional locations of a custom dual-region bucket. + Dual-regions require exactly 2 regional locations. See: + https://cloud.google.com/storage/docs/locations + predefined_acl (str): + (Optional) Name of predefined ACL to apply to bucket. See: + https://cloud.google.com/storage/docs/access-control/lists#predefined-acl + predefined_default_object_acl (str): + (Optional) Name of predefined ACL to apply to bucket's objects. See: + https://cloud.google.com/storage/docs/access-control/lists#predefined-acl + enable_object_retention (bool): + (Optional) Whether object retention should be enabled on this bucket. See: + https://cloud.google.com/storage/docs/object-lock + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + Returns: + google.cloud.storage.bucket.Bucket + The newly created bucket. + + Raises: + google.cloud.exceptions.Conflict + If the bucket already exists. + """ + with create_trace_span(name="Storage.Client.createBucket"): + bucket = self._bucket_arg_to_bucket(bucket_or_name) + query_params = {} + + if project is None: + project = self.project + + # Use no project if STORAGE_EMULATOR_HOST is set + if self._is_emulator_set: + if project is None: + project = _get_environ_project() + if project is None: + project = "" + + # Only include the project parameter if a project is set. + # If a project is not set, falls back to API validation (BadRequest). + if project is not None: + query_params = {"project": project} + + if requester_pays is not None: + warnings.warn( + "requester_pays arg is deprecated. Use Bucket().requester_pays instead.", + PendingDeprecationWarning, + stacklevel=1, + ) + bucket.requester_pays = requester_pays + + if predefined_acl is not None: + predefined_acl = BucketACL.validate_predefined(predefined_acl) + query_params["predefinedAcl"] = predefined_acl + + if predefined_default_object_acl is not None: + predefined_default_object_acl = DefaultObjectACL.validate_predefined( + predefined_default_object_acl + ) + query_params[ + "predefinedDefaultObjectAcl" + ] = predefined_default_object_acl + + if user_project is not None: + query_params["userProject"] = user_project + + if enable_object_retention: + query_params["enableObjectRetention"] = enable_object_retention + + properties = {key: bucket._properties[key] for key in bucket._changes} + properties["name"] = bucket.name + + if location is not None: + properties["location"] = location + + if data_locations is not None: + properties["customPlacementConfig"] = {"dataLocations": data_locations} + + api_response = self._post_resource( + "/b", + properties, + query_params=query_params, + timeout=timeout, + retry=retry, + _target_object=bucket, + ) + + bucket._set_properties(api_response) + return bucket + + def download_blob_to_file( + self, + blob_or_uri, + file_obj, + start=None, + end=None, + raw_download=False, + if_etag_match=None, + if_etag_not_match=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + """Download the contents of a blob object or blob URI into a file-like object. + + See https://cloud.google.com/storage/docs/downloading-objects + + Args: + blob_or_uri (Union[ \ + :class:`~google.cloud.storage.blob.Blob`, \ + str, \ + ]): + The blob resource to pass or URI to download. + + file_obj (file): + A file handle to which to write the blob's data. + + start (int): + (Optional) The first byte in a range to be downloaded. + + end (int): + (Optional) The last byte in a range to be downloaded. + + raw_download (bool): + (Optional) If true, download the object without any expansion. + + if_etag_match (Union[str, Set[str]]): + (Optional) See :ref:`using-if-etag-match` + + if_etag_not_match (Union[str, Set[str]]): + (Optional) See :ref:`using-if-etag-not-match` + + if_generation_match (long): + (Optional) See :ref:`using-if-generation-match` + + if_generation_not_match (long): + (Optional) See :ref:`using-if-generation-not-match` + + if_metageneration_match (long): + (Optional) See :ref:`using-if-metageneration-match` + + if_metageneration_not_match (long): + (Optional) See :ref:`using-if-metageneration-not-match` + + timeout ([Union[float, Tuple[float, float]]]): + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + checksum (str): + (Optional) The type of checksum to compute to verify the integrity + of the object. The response headers must contain a checksum of the + requested type. If the headers lack an appropriate checksum (for + instance in the case of transcoded or ranged downloads where the + remote service does not know the correct checksum, including + downloads where chunk_size is set) an INFO-level log will be + emitted. Supported values are "md5", "crc32c", "auto" and None. + The default is "auto", which will try to detect if the C + extension for crc32c is installed and fall back to md5 otherwise. + + retry (google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy) + (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + single_shot_download (bool): + (Optional) If true, download the object in a single request. + """ + with create_trace_span(name="Storage.Client.downloadBlobToFile"): + if not isinstance(blob_or_uri, Blob): + blob_or_uri = Blob.from_uri(blob_or_uri) + + blob_or_uri._prep_and_do_download( + file_obj, + client=self, + start=start, + end=end, + raw_download=raw_download, + if_etag_match=if_etag_match, + if_etag_not_match=if_etag_not_match, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + timeout=timeout, + checksum=checksum, + retry=retry, + single_shot_download=single_shot_download, + ) + + def list_blobs( + self, + bucket_or_name, + max_results=None, + page_token=None, + prefix=None, + delimiter=None, + start_offset=None, + end_offset=None, + include_trailing_delimiter=None, + versions=None, + projection="noAcl", + fields=None, + page_size=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + match_glob=None, + include_folders_as_prefixes=None, + soft_deleted=None, + ): + """Return an iterator used to find blobs in the bucket. + + If :attr:`user_project` is set, bills the API request to that project. + + .. note:: + List prefixes (directories) in a bucket using a prefix and delimiter. + See a [code sample](https://cloud.google.com/storage/docs/samples/storage-list-files-with-prefix#storage_list_files_with_prefix-python) + listing objects using a prefix filter. + + Args: + bucket_or_name (Union[ \ + :class:`~google.cloud.storage.bucket.Bucket`, \ + str, \ + ]): + The bucket resource to pass or name to create. + + max_results (int): + (Optional) The maximum number of blobs to return. + + page_token (str): + (Optional) If present, return the next batch of blobs, using the + value, which must correspond to the ``nextPageToken`` value + returned in the previous response. Deprecated: use the ``pages`` + property of the returned iterator instead of manually passing the + token. + + prefix (str): + (Optional) Prefix used to filter blobs. + + delimiter (str): + (Optional) Delimiter, used with ``prefix`` to + emulate hierarchy. + + start_offset (str): + (Optional) Filter results to objects whose names are + lexicographically equal to or after ``startOffset``. If + ``endOffset`` is also set, the objects listed will have names + between ``startOffset`` (inclusive) and ``endOffset`` + (exclusive). + + end_offset (str): + (Optional) Filter results to objects whose names are + lexicographically before ``endOffset``. If ``startOffset`` is + also set, the objects listed will have names between + ``startOffset`` (inclusive) and ``endOffset`` (exclusive). + + include_trailing_delimiter (boolean): + (Optional) If true, objects that end in exactly one instance of + ``delimiter`` will have their metadata included in ``items`` in + addition to ``prefixes``. + + versions (bool): + (Optional) Whether object versions should be returned + as separate blobs. + + projection (str): + (Optional) If used, must be 'full' or 'noAcl'. + Defaults to ``'noAcl'``. Specifies the set of + properties to return. + + fields (str): + (Optional) Selector specifying which fields to include + in a partial response. Must be a list of fields. For + example to get a partial response with just the next + page token and the name and language of each blob returned: + ``'items(name,contentLanguage),nextPageToken'``. + See: https://cloud.google.com/storage/docs/json_api/v1/parameters#fields + + page_size (int): + (Optional) Maximum number of blobs to return in each page. + Defaults to a value set by the API. + + timeout (Optional[Union[float, Tuple[float, float]]]): + The amount of time, in seconds, to wait for the server response. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + retry (Optional[Union[google.api_core.retry.Retry, google.cloud.storage.retry.ConditionalRetryPolicy]]): + How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + match_glob (str): + (Optional) A glob pattern used to filter results (for example, foo*bar). + The string value must be UTF-8 encoded. See: + https://cloud.google.com/storage/docs/json_api/v1/objects/list#list-object-glob + + include_folders_as_prefixes (bool): + (Optional) If true, includes Folders and Managed Folders in the set of + ``prefixes`` returned by the query. Only applicable if ``delimiter`` is set to /. + See: https://cloud.google.com/storage/docs/managed-folders + + soft_deleted (bool): + (Optional) If true, only soft-deleted objects will be listed as distinct results in order of increasing + generation number. This parameter can only be used successfully if the bucket has a soft delete policy. + Note ``soft_deleted`` and ``versions`` cannot be set to True simultaneously. See: + https://cloud.google.com/storage/docs/soft-delete + + Returns: + Iterator of all :class:`~google.cloud.storage.blob.Blob` + in this bucket matching the arguments. The RPC call + returns a response when the iterator is consumed. + + As part of the response, you'll also get back an iterator.prefixes entity that lists object names + up to and including the requested delimiter. Duplicate entries are omitted from this list. + """ + with create_trace_span(name="Storage.Client.listBlobs"): + bucket = self._bucket_arg_to_bucket(bucket_or_name) + + extra_params = {"projection": projection} + + if prefix is not None: + extra_params["prefix"] = prefix + + if delimiter is not None: + extra_params["delimiter"] = delimiter + + if match_glob is not None: + extra_params["matchGlob"] = match_glob + + if start_offset is not None: + extra_params["startOffset"] = start_offset + + if end_offset is not None: + extra_params["endOffset"] = end_offset + + if include_trailing_delimiter is not None: + extra_params["includeTrailingDelimiter"] = include_trailing_delimiter + + if versions is not None: + extra_params["versions"] = versions + + if fields is not None: + extra_params["fields"] = fields + + if include_folders_as_prefixes is not None: + extra_params["includeFoldersAsPrefixes"] = include_folders_as_prefixes + + if soft_deleted is not None: + extra_params["softDeleted"] = soft_deleted + + if bucket.user_project is not None: + extra_params["userProject"] = bucket.user_project + + path = bucket.path + "/o" + iterator = self._list_resource( + path, + _item_to_blob, + page_token=page_token, + max_results=max_results, + extra_params=extra_params, + page_start=_blobs_page_start, + page_size=page_size, + timeout=timeout, + retry=retry, + ) + iterator.bucket = bucket + iterator.prefixes = set() + return iterator + + def list_buckets( + self, + max_results=None, + page_token=None, + prefix=None, + projection="noAcl", + fields=None, + project=None, + page_size=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + *, + soft_deleted=None, + return_partial_success=None, + ): + """Get all buckets in the project associated to the client. + + This will not populate the list of blobs available in each + bucket. + + See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/buckets/list) and a [code sample](https://cloud.google.com/storage/docs/samples/storage-list-buckets#storage_list_buckets-python). + + :type max_results: int + :param max_results: (Optional) The maximum number of buckets to return. + + :type page_token: str + :param page_token: + (Optional) If present, return the next batch of buckets, using the + value, which must correspond to the ``nextPageToken`` value + returned in the previous response. Deprecated: use the ``pages`` + property of the returned iterator instead of manually passing the + token. + + :type prefix: str + :param prefix: (Optional) Filter results to buckets whose names begin + with this prefix. + + :type projection: str + :param projection: + (Optional) Specifies the set of properties to return. If used, must + be 'full' or 'noAcl'. Defaults to 'noAcl'. + + :type fields: str + :param fields: + (Optional) Selector specifying which fields to include in a partial + response. Must be a list of fields. For example to get a partial + response with just the next page token and the language of each + bucket returned: 'items/id,nextPageToken' + + :type project: str + :param project: (Optional) The project whose buckets are to be listed. + If not passed, uses the project set on the client. + + :type page_size: int + :param page_size: (Optional) Maximum number of buckets to return in each page. + Defaults to a value set by the API. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :type soft_deleted: bool + :param soft_deleted: + (Optional) If true, only soft-deleted buckets will be listed as distinct results in order of increasing + generation number. This parameter can only be used successfully if the bucket has a soft delete policy. + See: https://cloud.google.com/storage/docs/soft-delete + + :type return_partial_success: bool + :param return_partial_success: + (Optional) If True, the response will also contain a list of + unreachable buckets if the buckets are unavailable. The + unreachable buckets will be available on the ``unreachable`` + attribute of the returned iterator. + + :rtype: :class:`~google.api_core.page_iterator.Iterator` + :raises ValueError: if both ``project`` is ``None`` and the client's + project is also ``None``. + :returns: Iterator of all :class:`~google.cloud.storage.bucket.Bucket` + belonging to this project. + """ + with create_trace_span(name="Storage.Client.listBuckets"): + extra_params = {} + + if project is None: + project = self.project + + # Use no project if STORAGE_EMULATOR_HOST is set + if self._is_emulator_set: + if project is None: + project = _get_environ_project() + if project is None: + project = "" + + # Only include the project parameter if a project is set. + # If a project is not set, falls back to API validation (BadRequest). + if project is not None: + extra_params = {"project": project} + + if prefix is not None: + extra_params["prefix"] = prefix + + extra_params["projection"] = projection + + if fields is not None: + extra_params["fields"] = fields + + if soft_deleted is not None: + extra_params["softDeleted"] = soft_deleted + + if return_partial_success is not None: + extra_params["returnPartialSuccess"] = return_partial_success + + iterator = self._list_resource( + "/b", + _item_to_bucket, + page_token=page_token, + max_results=max_results, + extra_params=extra_params, + page_size=page_size, + timeout=timeout, + retry=retry, + page_start=_buckets_page_start, + ) + return iterator + + def restore_bucket( + self, + bucket_name, + generation, + projection="noAcl", + if_metageneration_match=None, + if_metageneration_not_match=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """Restores a soft-deleted bucket. + + :type bucket_name: str + :param bucket_name: The name of the bucket to be restored. + + :type generation: int + :param generation: Selects the specific revision of the bucket. + + :type projection: str + :param projection: + (Optional) Specifies the set of properties to return. If used, must + be 'full' or 'noAcl'. Defaults to 'noAcl'. + + if_metageneration_match (Optional[int]): + Make the operation conditional on whether the + blob's current metageneration matches the given value. + + if_metageneration_not_match (Optional[int]): + Make the operation conditional on whether the blob's + current metageneration does not match the given value. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. + + Users can configure non-default retry behavior. A ``None`` value will + disable retries. See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout). + + :rtype: :class:`google.cloud.storage.bucket.Bucket` + :returns: The restored Bucket. + """ + query_params = {"generation": generation, "projection": projection} + + _add_generation_match_parameters( + query_params, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + ) + + bucket = self.bucket(bucket_name) + api_response = self._post_resource( + f"{bucket.path}/restore", + None, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + bucket._set_properties(api_response) + return bucket + + def create_hmac_key( + self, + service_account_email, + project_id=None, + user_project=None, + timeout=_DEFAULT_TIMEOUT, + retry=None, + ): + """Create an HMAC key for a service account. + + :type service_account_email: str + :param service_account_email: e-mail address of the service account + + :type project_id: str + :param project_id: (Optional) Explicit project ID for the key. + Defaults to the client's project. + + :type user_project: str + :param user_project: (Optional) This parameter is currently ignored. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: (Optional) How to retry the RPC. A None value will disable retries. + A google.api_core.retry.Retry value will enable retries, and the object will + define retriable response codes and errors and configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a Retry object and + activates it only if certain conditions are met. This class exists to provide safe defaults + for RPC calls that are not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a condition such as + if_metageneration_match is set. + + See the retry.py source code and docstrings in this package (google.cloud.storage.retry) for + information on retry types and how to configure them. + + :rtype: + Tuple[:class:`~google.cloud.storage.hmac_key.HMACKeyMetadata`, str] + :returns: metadata for the created key, plus the bytes of the key's secret, which is an 40-character base64-encoded string. + """ + with create_trace_span(name="Storage.Client.createHmacKey"): + if project_id is None: + project_id = self.project + + path = f"/projects/{project_id}/hmacKeys" + qs_params = {"serviceAccountEmail": service_account_email} + + if user_project is not None: + qs_params["userProject"] = user_project + + api_response = self._post_resource( + path, + None, + query_params=qs_params, + timeout=timeout, + retry=retry, + ) + metadata = HMACKeyMetadata(self) + metadata._properties = api_response["metadata"] + secret = api_response["secret"] + return metadata, secret + + def list_hmac_keys( + self, + max_results=None, + service_account_email=None, + show_deleted_keys=None, + project_id=None, + user_project=None, + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, + ): + """List HMAC keys for a project. + + :type max_results: int + :param max_results: + (Optional) Max number of keys to return in a given page. + + :type service_account_email: str + :param service_account_email: + (Optional) Limit keys to those created by the given service account. + + :type show_deleted_keys: bool + :param show_deleted_keys: + (Optional) Included deleted keys in the list. Default is to + exclude them. + + :type project_id: str + :param project_id: (Optional) Explicit project ID for the key. + Defaults to the client's project. + + :type user_project: str + :param user_project: (Optional) This parameter is currently ignored. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: + Tuple[:class:`~google.cloud.storage.hmac_key.HMACKeyMetadata`, str] + :returns: metadata for the created key, plus the bytes of the key's secret, which is an 40-character base64-encoded string. + """ + with create_trace_span(name="Storage.Client.listHmacKeys"): + if project_id is None: + project_id = self.project + + path = f"/projects/{project_id}/hmacKeys" + extra_params = {} + + if service_account_email is not None: + extra_params["serviceAccountEmail"] = service_account_email + + if show_deleted_keys is not None: + extra_params["showDeletedKeys"] = show_deleted_keys + + if user_project is not None: + extra_params["userProject"] = user_project + + return self._list_resource( + path, + _item_to_hmac_key_metadata, + max_results=max_results, + extra_params=extra_params, + timeout=timeout, + retry=retry, + ) + + def get_hmac_key_metadata( + self, access_id, project_id=None, user_project=None, timeout=_DEFAULT_TIMEOUT + ): + """Return a metadata instance for the given HMAC key. + + :type access_id: str + :param access_id: Unique ID of an existing key. + + :type project_id: str + :param project_id: (Optional) Project ID of an existing key. + Defaults to client's project. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type user_project: str + :param user_project: (Optional) This parameter is currently ignored. + """ + with create_trace_span(name="Storage.Client.getHmacKeyMetadata"): + metadata = HMACKeyMetadata(self, access_id, project_id, user_project) + metadata.reload(timeout=timeout) # raises NotFound for missing key + return metadata + + def generate_signed_post_policy_v4( + self, + bucket_name, + blob_name, + expiration, + conditions=None, + fields=None, + credentials=None, + virtual_hosted_style=False, + bucket_bound_hostname=None, + scheme="http", + service_account_email=None, + access_token=None, + ): + """Generate a V4 signed policy object. Generated policy object allows user to upload objects with a POST request. + + .. note:: + + Assumes ``credentials`` implements the + :class:`google.auth.credentials.Signing` interface. Also assumes + ``credentials`` has a ``service_account_email`` property which + identifies the credentials. + + See a [code sample](https://github.com/googleapis/python-storage/blob/main/samples/snippets/storage_generate_signed_post_policy_v4.py). + + :type bucket_name: str + :param bucket_name: Bucket name. + + :type blob_name: str + :param blob_name: Object name. + + :type expiration: Union[Integer, datetime.datetime, datetime.timedelta] + :param expiration: Policy expiration time. If a ``datetime`` instance is + passed without an explicit ``tzinfo`` set, it will be + assumed to be ``UTC``. + + :type conditions: list + :param conditions: (Optional) List of POST policy conditions, which are + used to restrict what is allowed in the request. + + :type fields: dict + :param fields: (Optional) Additional elements to include into request. + + :type credentials: :class:`google.auth.credentials.Signing` + :param credentials: (Optional) Credentials object with an associated private + key to sign text. + + :type virtual_hosted_style: bool + :param virtual_hosted_style: + (Optional) If True, construct the URL relative to the bucket + virtual hostname, e.g., '.storage.googleapis.com'. + Incompatible with bucket_bound_hostname. + + :type bucket_bound_hostname: str + :param bucket_bound_hostname: + (Optional) If passed, construct the URL relative to the bucket-bound hostname. + Value can be bare or with a scheme, e.g., 'example.com' or 'http://example.com'. + Incompatible with virtual_hosted_style. + See: https://cloud.google.com/storage/docs/request-endpoints#cname + + :type scheme: str + :param scheme: + (Optional) If ``bucket_bound_hostname`` is passed as a bare hostname, use + this value as a scheme. ``https`` will work only when using a CDN. + Defaults to ``"http"``. + + :type service_account_email: str + :param service_account_email: (Optional) E-mail address of the service account. + + :type access_token: str + :param access_token: (Optional) Access token for a service account. + + :raises: :exc:`ValueError` when mutually exclusive arguments are used. + + :rtype: dict + :returns: Signed POST policy. + """ + if virtual_hosted_style and bucket_bound_hostname: + raise ValueError( + "Only one of virtual_hosted_style and bucket_bound_hostname " + "can be specified." + ) + + credentials = self._credentials if credentials is None else credentials + client_email = service_account_email + if not access_token or not service_account_email: + ensure_signed_credentials(credentials) + client_email = credentials.signer_email + + # prepare policy conditions and fields + timestamp, datestamp = get_v4_now_dtstamps() + + x_goog_credential = "{email}/{datestamp}/auto/storage/goog4_request".format( + email=client_email, datestamp=datestamp + ) + required_conditions = [ + {"bucket": bucket_name}, + {"key": blob_name}, + {"x-goog-date": timestamp}, + {"x-goog-credential": x_goog_credential}, + {"x-goog-algorithm": "GOOG4-RSA-SHA256"}, + ] + + conditions = conditions or [] + policy_fields = {} + for key, value in sorted((fields or {}).items()): + if not key.startswith("x-ignore-"): + policy_fields[key] = value + conditions.append({key: value}) + + conditions += required_conditions + + # calculate policy expiration time + now = _NOW(_UTC).replace(tzinfo=None) + if expiration is None: + expiration = now + datetime.timedelta(hours=1) + + policy_expires = now + datetime.timedelta( + seconds=get_expiration_seconds_v4(expiration) + ) + + # encode policy for signing + policy = json.dumps( + collections.OrderedDict( + sorted( + { + "conditions": conditions, + "expiration": policy_expires.isoformat() + "Z", + }.items() + ) + ), + separators=(",", ":"), + ) + str_to_sign = base64.b64encode(policy.encode("utf-8")) + + # sign the policy and get its cryptographic signature + if access_token and service_account_email: + signature = _sign_message(str_to_sign, access_token, service_account_email) + signature_bytes = base64.b64decode(signature) + else: + signature_bytes = credentials.sign_bytes(str_to_sign) + + # get hexadecimal representation of the signature + signature = binascii.hexlify(signature_bytes).decode("utf-8") + + policy_fields.update( + { + "key": blob_name, + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": x_goog_credential, + "x-goog-date": timestamp, + "x-goog-signature": signature, + "policy": str_to_sign.decode("utf-8"), + } + ) + # designate URL + if virtual_hosted_style: + url = _virtual_hosted_style_base_url( + self.api_endpoint, bucket_name, trailing_slash=True + ) + elif bucket_bound_hostname: + url = f"{_bucket_bound_hostname_url(bucket_bound_hostname, scheme)}/" + else: + url = f"{self.api_endpoint}/{bucket_name}/" + + return {"url": url, "fields": policy_fields} + + +def _item_to_bucket(iterator, item): + """Convert a JSON bucket to the native object. + + :type iterator: :class:`~google.api_core.page_iterator.Iterator` + :param iterator: The iterator that has retrieved the item. + + :type item: dict + :param item: An item to be converted to a bucket. + + :rtype: :class:`.Bucket` + :returns: The next bucket in the page. + """ + name = item.get("name") + bucket = Bucket(iterator.client, name) + bucket._set_properties(item) + return bucket + + +def _item_to_hmac_key_metadata(iterator, item): + """Convert a JSON key metadata resource to the native object. + + :type iterator: :class:`~google.api_core.page_iterator.Iterator` + :param iterator: The iterator that has retrieved the item. + + :type item: dict + :param item: An item to be converted to a key metadata instance. + + :rtype: :class:`~google.cloud.storage.hmac_key.HMACKeyMetadata` + :returns: The next key metadata instance in the page. + """ + metadata = HMACKeyMetadata(iterator.client) + metadata._properties = item + return metadata diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/constants.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c1b63c413e90f4c014f041cf606fc59455cd73 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/constants.py @@ -0,0 +1,145 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Constants used across google.cloud.storage modules. + +See [Python Storage Client Constants Page](https://github.com/googleapis/python-storage/blob/main/google/cloud/storage/constants.py) +for constants used across storage classes, location types, public access prevention, etc. + +""" + +# Storage classes + +STANDARD_STORAGE_CLASS = "STANDARD" +"""Storage class for objects accessed more than once per month. + +See: https://cloud.google.com/storage/docs/storage-classes +""" + +NEARLINE_STORAGE_CLASS = "NEARLINE" +"""Storage class for objects accessed at most once per month. + +See: https://cloud.google.com/storage/docs/storage-classes +""" + +COLDLINE_STORAGE_CLASS = "COLDLINE" +"""Storage class for objects accessed at most once per year. + +See: https://cloud.google.com/storage/docs/storage-classes +""" + +ARCHIVE_STORAGE_CLASS = "ARCHIVE" +"""Storage class for objects accessed less frequently than once per year. + +See: https://cloud.google.com/storage/docs/storage-classes +""" + +MULTI_REGIONAL_LEGACY_STORAGE_CLASS = "MULTI_REGIONAL" +"""Legacy storage class. + +Alias for :attr:`STANDARD_STORAGE_CLASS`. + +Can only be used for objects in buckets whose +:attr:`~google.cloud.storage.bucket.Bucket.location_type` is +:attr:`~google.cloud.storage.bucket.Bucket.MULTI_REGION_LOCATION_TYPE`. + +See: https://cloud.google.com/storage/docs/storage-classes +""" + +REGIONAL_LEGACY_STORAGE_CLASS = "REGIONAL" +"""Legacy storage class. + +Alias for :attr:`STANDARD_STORAGE_CLASS`. + +Can only be used for objects in buckets whose +:attr:`~google.cloud.storage.bucket.Bucket.location_type` is +:attr:`~google.cloud.storage.bucket.Bucket.REGION_LOCATION_TYPE`. + +See: https://cloud.google.com/storage/docs/storage-classes +""" + +DURABLE_REDUCED_AVAILABILITY_LEGACY_STORAGE_CLASS = "DURABLE_REDUCED_AVAILABILITY" +"""Legacy storage class. + +Similar to :attr:`NEARLINE_STORAGE_CLASS`. +""" + + +# Location types + +MULTI_REGION_LOCATION_TYPE = "multi-region" +"""Location type: data will be replicated across regions in a multi-region. + +Provides highest availability across largest area. +""" + +REGION_LOCATION_TYPE = "region" +"""Location type: data will be stored within a single region. + +Provides lowest latency within a single region. +""" + +DUAL_REGION_LOCATION_TYPE = "dual-region" +"""Location type: data will be stored within two primary regions. + +Provides high availability and low latency across two regions. +""" + + +# Internal constants + +_DEFAULT_TIMEOUT = 60 # in seconds +"""The default request timeout in seconds if a timeout is not explicitly given. +""" + +# Public Access Prevention +PUBLIC_ACCESS_PREVENTION_ENFORCED = "enforced" +"""Enforced public access prevention value. + +See: https://cloud.google.com/storage/docs/public-access-prevention +""" + +PUBLIC_ACCESS_PREVENTION_UNSPECIFIED = "unspecified" +"""Unspecified public access prevention value. + +DEPRECATED: Use 'PUBLIC_ACCESS_PREVENTION_INHERITED' instead. + +See: https://cloud.google.com/storage/docs/public-access-prevention +""" + +PUBLIC_ACCESS_PREVENTION_INHERITED = "inherited" +"""Inherited public access prevention value. + +See: https://cloud.google.com/storage/docs/public-access-prevention +""" + +RPO_ASYNC_TURBO = "ASYNC_TURBO" +"""The recovery point objective (RPO) indicates how quickly newly written objects are asynchronously replicated to a separate geographic location. +When the RPO value is set to ASYNC_TURBO, the turbo replication feature is enabled. + +See: https://cloud.google.com/storage/docs/managing-turbo-replication +""" + +RPO_DEFAULT = "DEFAULT" +"""The recovery point objective (RPO) indicates how quickly newly written objects are asynchronously replicated to a separate geographic location. +When the RPO value is set to DEFAULT, the default replication behavior is enabled. + +See: https://cloud.google.com/storage/docs/managing-turbo-replication +""" + +ENFORCEMENT_MODE_FULLY_RESTRICTED = "FullyRestricted" +"""Bucket encryption restriction mode where encryption is fully restricted.""" + +ENFORCEMENT_MODE_NOT_RESTRICTED = "NotRestricted" +"""Bucket encryption restriction mode where encryption is not restricted.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/exceptions.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..12f69071b240c0a719c6c4cacfadd62cbe3b74ae --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/exceptions.py @@ -0,0 +1,75 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Exceptions raised by the library.""" + +# These exceptions were originally part of the google-resumable-media library +# but were integrated into python-storage in version 3.0. For backwards +# compatibility with applications which use except blocks with +# google-resumable-media exceptions, if the library google-resumable-media is +# installed, make all exceptions subclasses of the exceptions from that library. +# Note that either way, the classes will subclass Exception, either directly or +# indirectly. +# +# This backwards compatibility feature may be removed in a future major version +# update. Please update application code to use the new exception classes in +# this module. +try: + from google.resumable_media import InvalidResponse as InvalidResponseDynamicParent + from google.resumable_media import DataCorruption as DataCorruptionDynamicParent +except ImportError: + InvalidResponseDynamicParent = Exception + DataCorruptionDynamicParent = Exception + + +class InvalidPathError(Exception): + """Raised when the provided path string is malformed.""" + + pass + + +class InvalidResponse(InvalidResponseDynamicParent): + """Error class for responses which are not in the correct state. + + Args: + response (object): The HTTP response which caused the failure. + args (tuple): The positional arguments typically passed to an + exception class. + """ + + def __init__(self, response, *args): + if InvalidResponseDynamicParent is Exception: + super().__init__(*args) + self.response = response + """object: The HTTP response object that caused the failure.""" + else: + super().__init__(response, *args) + + +class DataCorruption(DataCorruptionDynamicParent): + """Error class for corrupt media transfers. + + Args: + response (object): The HTTP response which caused the failure. + args (tuple): The positional arguments typically passed to an + exception class. + """ + + def __init__(self, response, *args): + if DataCorruptionDynamicParent is Exception: + super().__init__(*args) + self.response = response + """object: The HTTP response object that caused the failure.""" + else: + super().__init__(response, *args) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/fileio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/fileio.py new file mode 100644 index 0000000000000000000000000000000000000000..7c30f39be4996e31dbcda5532008556d1f2f1632 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/fileio.py @@ -0,0 +1,551 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Module for file-like access of blobs, usually invoked via Blob.open().""" + +import io + +from google.api_core.exceptions import RequestRangeNotSatisfiable +from google.cloud.storage.retry import DEFAULT_RETRY +from google.cloud.storage.retry import ConditionalRetryPolicy + + +# Resumable uploads require a chunk size of precisely a multiple of 256 KiB. +CHUNK_SIZE_MULTIPLE = 256 * 1024 # 256 KiB +DEFAULT_CHUNK_SIZE = 40 * 1024 * 1024 # 40 MiB + +# Valid keyword arguments for download methods, and blob.reload() if needed. +# Note: Changes here need to be reflected in the blob.open() docstring. +VALID_DOWNLOAD_KWARGS = { + "if_generation_match", + "if_generation_not_match", + "if_metageneration_match", + "if_metageneration_not_match", + "timeout", + "retry", + "raw_download", + "single_shot_download", +} + +# Valid keyword arguments for upload methods. +# Note: Changes here need to be reflected in the blob.open() docstring. +VALID_UPLOAD_KWARGS = { + "content_type", + "predefined_acl", + "if_generation_match", + "if_generation_not_match", + "if_metageneration_match", + "if_metageneration_not_match", + "timeout", + "checksum", + "retry", +} + + +class BlobReader(io.BufferedIOBase): + """A file-like object that reads from a blob. + + :type blob: 'google.cloud.storage.blob.Blob' + :param blob: + The blob to download. + + :type chunk_size: long + :param chunk_size: + (Optional) The minimum number of bytes to read at a time. If fewer + bytes than the chunk_size are requested, the remainder is buffered. + The default is the chunk_size of the blob, or 40MiB. + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Media operations (downloads and uploads) do not support non-default + predicates in a Retry object. The default will always be used. Other + configuration changes for Retry objects such as delays and deadlines + are respected. + + :type download_kwargs: dict + :param download_kwargs: + Keyword arguments to pass to the underlying API calls. + The following arguments are supported: + + - ``if_generation_match`` + - ``if_generation_not_match`` + - ``if_metageneration_match`` + - ``if_metageneration_not_match`` + - ``timeout`` + - ``raw_download`` + - ``single_shot_download`` + + Note that download_kwargs (excluding ``raw_download`` and ``single_shot_download``) are also applied to blob.reload(), + if a reload is needed during seek(). + """ + + def __init__(self, blob, chunk_size=None, retry=DEFAULT_RETRY, **download_kwargs): + for kwarg in download_kwargs: + if kwarg not in VALID_DOWNLOAD_KWARGS: + raise ValueError( + f"BlobReader does not support keyword argument {kwarg}." + ) + + self._blob = blob + self._pos = 0 + self._buffer = io.BytesIO() + self._chunk_size = chunk_size or blob.chunk_size or DEFAULT_CHUNK_SIZE + self._retry = retry + self._download_kwargs = download_kwargs + + def read(self, size=-1): + self._checkClosed() # Raises ValueError if closed. + + result = self._buffer.read(size) + # If the read request demands more bytes than are buffered, fetch more. + remaining_size = size - len(result) + if remaining_size > 0 or size < 0: + self._pos += self._buffer.tell() + read_size = len(result) + + self._buffer.seek(0) + self._buffer.truncate(0) # Clear the buffer to make way for new data. + fetch_start = self._pos + if size > 0: + # Fetch the larger of self._chunk_size or the remaining_size. + fetch_end = fetch_start + max(remaining_size, self._chunk_size) + else: + fetch_end = None + + # Download the blob. Checksumming must be disabled as we are using + # chunked downloads, and the server only knows the checksum of the + # entire file. + try: + result += self._blob.download_as_bytes( + start=fetch_start, + end=fetch_end, + checksum=None, + retry=self._retry, + **self._download_kwargs, + ) + except RequestRangeNotSatisfiable: + # We've reached the end of the file. Python file objects should + # return an empty response in this case, not raise an error. + pass + + # If more bytes were read than is immediately needed, buffer the + # remainder and then trim the result. + if size > 0 and len(result) > size: + self._buffer.write(result[size:]) + self._buffer.seek(0) + result = result[:size] + # Increment relative offset by true amount read. + self._pos += len(result) - read_size + return result + + def read1(self, size=-1): + return self.read(size) + + def seek(self, pos, whence=0): + """Seek within the blob. + + This implementation of seek() uses knowledge of the blob size to + validate that the reported position does not exceed the blob last byte. + If the blob size is not already known it will call blob.reload(). + """ + self._checkClosed() # Raises ValueError if closed. + + if self._blob.size is None: + reload_kwargs = { + k: v + for k, v in self._download_kwargs.items() + if (k != "raw_download" and k != "single_shot_download") + } + self._blob.reload(**reload_kwargs) + + initial_offset = self._pos + self._buffer.tell() + + if whence == 0: + target_pos = pos + elif whence == 1: + target_pos = initial_offset + pos + elif whence == 2: + target_pos = self._blob.size + pos + if whence not in {0, 1, 2}: + raise ValueError("invalid whence value") + + if target_pos > self._blob.size: + target_pos = self._blob.size + + # Seek or invalidate buffer as needed. + if target_pos < self._pos: + # Target position < relative offset <= true offset. + # As data is not in buffer, invalidate buffer. + self._buffer.seek(0) + self._buffer.truncate(0) + new_pos = target_pos + self._pos = target_pos + else: + # relative offset <= target position <= size of file. + difference = target_pos - initial_offset + new_pos = self._pos + self._buffer.seek(difference, 1) + return new_pos + + def close(self): + self._buffer.close() + + @property + def closed(self): + return self._buffer.closed + + def readable(self): + return True + + def writable(self): + return False + + def seekable(self): + return True + + +class BlobWriter(io.BufferedIOBase): + """A file-like object that writes to a blob. + + :type blob: 'google.cloud.storage.blob.Blob' + :param blob: + The blob to which to write. + + :type chunk_size: long + :param chunk_size: + (Optional) The maximum number of bytes to buffer before sending data + to the server, and the size of each request when data is sent. + Writes are implemented as a "resumable upload", so chunk_size for + writes must be exactly a multiple of 256KiB as with other resumable + uploads. The default is the chunk_size of the blob, or 40 MiB. + + :type ignore_flush: bool + :param ignore_flush: + Makes flush() do nothing instead of raise an error. flush() without + closing is not supported by the remote service and therefore calling it + on this class normally results in io.UnsupportedOperation. However, that + behavior is incompatible with some consumers and wrappers of file + objects in Python, such as zipfile.ZipFile or io.TextIOWrapper. Setting + ignore_flush will cause flush() to successfully do nothing, for + compatibility with those contexts. The correct way to actually flush + data to the remote server is to close() (using this object as a context + manager is recommended). + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. A None value will disable + retries. A google.api_core.retry.Retry value will enable retries, + and the object will define retriable response codes and errors and + configure backoff and timeout options. + + A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a + Retry object and activates it only if certain conditions are met. + This class exists to provide safe defaults for RPC calls that are + not technically safe to retry normally (due to potential data + duplication or other side-effects) but become safe to retry if a + condition such as if_metageneration_match is set. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Media operations (downloads and uploads) do not support non-default + predicates in a Retry object. The default will always be used. Other + configuration changes for Retry objects such as delays and deadlines + are respected. + + :type upload_kwargs: dict + :param upload_kwargs: + Keyword arguments to pass to the underlying API + calls. The following arguments are supported: + + - ``if_generation_match`` + - ``if_generation_not_match`` + - ``if_metageneration_match`` + - ``if_metageneration_not_match`` + - ``timeout`` + - ``content_type`` + - ``predefined_acl`` + - ``checksum`` + """ + + def __init__( + self, + blob, + chunk_size=None, + ignore_flush=False, + retry=DEFAULT_RETRY, + **upload_kwargs, + ): + for kwarg in upload_kwargs: + if kwarg not in VALID_UPLOAD_KWARGS: + raise ValueError( + f"BlobWriter does not support keyword argument {kwarg}." + ) + self._blob = blob + self._buffer = SlidingBuffer() + self._upload_and_transport = None + # Resumable uploads require a chunk size of a multiple of 256KiB. + # self._chunk_size must not be changed after the upload is initiated. + self._chunk_size = chunk_size or blob.chunk_size or DEFAULT_CHUNK_SIZE + self._ignore_flush = ignore_flush + self._retry = retry + self._upload_kwargs = upload_kwargs + + @property + def _chunk_size(self): + """Get the blob's default chunk size. + + :rtype: int or ``NoneType`` + :returns: The current blob's chunk size, if it is set. + """ + return self.__chunk_size + + @_chunk_size.setter + def _chunk_size(self, value): + """Set the blob's default chunk size. + + :type value: int + :param value: (Optional) The current blob's chunk size, if it is set. + + :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a + multiple of 256 KiB. + """ + if value is not None and value > 0 and value % CHUNK_SIZE_MULTIPLE != 0: + raise ValueError( + "Chunk size must be a multiple of %d." % CHUNK_SIZE_MULTIPLE + ) + self.__chunk_size = value + + def write(self, b): + self._checkClosed() # Raises ValueError if closed. + + pos = self._buffer.write(b) + + # If there is enough content, upload chunks. + num_chunks = len(self._buffer) // self._chunk_size + if num_chunks: + self._upload_chunks_from_buffer(num_chunks) + + return pos + + def _initiate_upload(self): + retry = self._retry + content_type = self._upload_kwargs.pop("content_type", None) + + # Handle ConditionalRetryPolicy. + if isinstance(retry, ConditionalRetryPolicy): + # Conditional retries are designed for non-media calls, which change + # arguments into query_params dictionaries. Media operations work + # differently, so here we make a "fake" query_params to feed to the + # ConditionalRetryPolicy. + query_params = { + "ifGenerationMatch": self._upload_kwargs.get("if_generation_match"), + "ifMetagenerationMatch": self._upload_kwargs.get( + "if_metageneration_match" + ), + } + retry = retry.get_retry_policy_if_conditions_met(query_params=query_params) + + self._upload_and_transport = self._blob._initiate_resumable_upload( + self._blob.bucket.client, + self._buffer, + content_type, + None, + chunk_size=self._chunk_size, + retry=retry, + **self._upload_kwargs, + ) + + def _upload_chunks_from_buffer(self, num_chunks): + """Upload a specified number of chunks.""" + + # Initialize the upload if necessary. + if not self._upload_and_transport: + self._initiate_upload() + + upload, transport = self._upload_and_transport + + # Attach timeout if specified in the keyword arguments. + # Otherwise, the default timeout will be used from the media library. + kwargs = {} + if "timeout" in self._upload_kwargs: + kwargs = {"timeout": self._upload_kwargs.get("timeout")} + + # Upload chunks. The SlidingBuffer class will manage seek position. + for _ in range(num_chunks): + upload.transmit_next_chunk(transport, **kwargs) + + # Wipe the buffer of chunks uploaded, preserving any remaining data. + self._buffer.flush() + + def tell(self): + return self._buffer.tell() + len(self._buffer) + + def flush(self): + # flush() is not fully supported by the remote service, so raise an + # error here, unless self._ignore_flush is set. + if not self._ignore_flush: + raise io.UnsupportedOperation( + "Cannot flush without finalizing upload. Use close() instead, " + "or set ignore_flush=True when constructing this class (see " + "docstring)." + ) + + def close(self): + if not self._buffer.closed: + self._upload_chunks_from_buffer(1) + self._buffer.close() + + def terminate(self): + """Cancel the ResumableUpload.""" + if self._upload_and_transport: + upload, transport = self._upload_and_transport + transport.delete(upload.upload_url) + self._buffer.close() + + def __exit__(self, exc_type, exc_val, exc_tb): + if exc_type is not None: + self.terminate() + else: + self.close() + + @property + def closed(self): + return self._buffer.closed + + def readable(self): + return False + + def writable(self): + return True + + def seekable(self): + return False + + +class SlidingBuffer(object): + """A non-rewindable buffer that frees memory of chunks already consumed. + + This class is necessary because `google-resumable-media-python` expects + `tell()` to work relative to the start of the file, not relative to a place + in an intermediate buffer. Using this class, we present an external + interface with consistent seek and tell behavior without having to actually + store bytes already sent. + + Behavior of this class differs from an ordinary BytesIO buffer. `write()` + will always append to the end of the file only and not change the seek + position otherwise. `flush()` will delete all data already read (data to the + left of the seek position). `tell()` will report the seek position of the + buffer including all deleted data. Additionally the class implements + __len__() which will report the size of the actual underlying buffer. + + This class does not attempt to implement the entire Python I/O interface. + """ + + def __init__(self): + self._buffer = io.BytesIO() + self._cursor = 0 + + def write(self, b): + """Append to the end of the buffer without changing the position.""" + self._checkClosed() # Raises ValueError if closed. + + bookmark = self._buffer.tell() + self._buffer.seek(0, io.SEEK_END) + pos = self._buffer.write(b) + self._buffer.seek(bookmark) + return pos + + def read(self, size=-1): + """Read and move the cursor.""" + self._checkClosed() # Raises ValueError if closed. + + data = self._buffer.read(size) + self._cursor += len(data) + return data + + def flush(self): + """Delete already-read data (all data to the left of the position).""" + self._checkClosed() # Raises ValueError if closed. + + # BytesIO can't be deleted from the left, so save any leftover, unread + # data and truncate at 0, then readd leftover data. + leftover = self._buffer.read() + self._buffer.seek(0) + self._buffer.truncate(0) + self._buffer.write(leftover) + self._buffer.seek(0) + + def tell(self): + """Report how many bytes have been read from the buffer in total.""" + return self._cursor + + def seek(self, pos): + """Seek to a position (backwards only) within the internal buffer. + + This implementation of seek() verifies that the seek destination is + contained in _buffer. It will raise ValueError if the destination byte + has already been purged from the buffer. + + The "whence" argument is not supported in this implementation. + """ + self._checkClosed() # Raises ValueError if closed. + + buffer_initial_pos = self._buffer.tell() + difference = pos - self._cursor + buffer_seek_result = self._buffer.seek(difference, io.SEEK_CUR) + if ( + not buffer_seek_result - buffer_initial_pos == difference + or pos > self._cursor + ): + # The seek did not arrive at the expected byte because the internal + # buffer does not (or no longer) contains the byte. Reset and raise. + self._buffer.seek(buffer_initial_pos) + raise ValueError("Cannot seek() to that value.") + + self._cursor = pos + return self._cursor + + def __len__(self): + """Determine the size of the buffer by seeking to the end.""" + bookmark = self._buffer.tell() + length = self._buffer.seek(0, io.SEEK_END) + self._buffer.seek(bookmark) + return length + + def close(self): + return self._buffer.close() + + def _checkClosed(self): + return self._buffer._checkClosed() + + @property + def closed(self): + return self._buffer.closed diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/grpc_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/grpc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..7a739b7b7d366bfc4ee84e4f8dcadd418286a515 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/grpc_client.py @@ -0,0 +1,122 @@ +# 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. + +"""A client for interacting with Google Cloud Storage using the gRPC API.""" + +from google.cloud.client import ClientWithProject +from google.cloud import _storage_v2 as storage_v2 + +_marker = object() + + +class GrpcClient(ClientWithProject): + """A client for interacting with Google Cloud Storage using the gRPC API. + + :type project: str or None + :param project: The project which the client acts on behalf of. If not + passed, falls back to the default inferred from the + environment. + + :type credentials: :class:`~google.auth.credentials.Credentials` + :param credentials: (Optional) The OAuth2 Credentials to use for this + client. If not passed, falls back to the default + inferred from the environment. + + :type client_info: :class:`~google.api_core.client_info.ClientInfo` + :param client_info: + 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 library + or partner tool. + + :type client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict` + :param client_options: (Optional) Client options used to set user options + on the client. A non-default universe domain or API endpoint should be + set through client_options. + + :type api_key: string + :param api_key: + (Optional) An API key. Mutually exclusive with any other credentials. + This parameter is an alias for setting `client_options.api_key` and + will supersede any API key set in the `client_options` parameter. + + :type attempt_direct_path: bool + :param attempt_direct_path: + (Optional) Whether to attempt to use DirectPath for gRPC connections. + This provides a direct, unproxied connection to GCS for lower latency + and higher throughput, and is highly recommended when running on Google + Cloud infrastructure. Defaults to ``True``. + """ + + def __init__( + self, + project=_marker, + credentials=None, + client_info=None, + client_options=None, + *, + api_key=None, + attempt_direct_path=True, + ): + super(GrpcClient, self).__init__(project=project, credentials=credentials) + + if isinstance(client_options, dict): + if api_key: + client_options["api_key"] = api_key + elif client_options is None: + client_options = {} if not api_key else {"api_key": api_key} + elif api_key: + client_options.api_key = api_key + + self._grpc_client = self._create_gapic_client( + credentials=credentials, + client_info=client_info, + client_options=client_options, + attempt_direct_path=attempt_direct_path, + ) + + def _create_gapic_client( + self, + credentials=None, + client_info=None, + client_options=None, + attempt_direct_path=True, + ): + """Creates and configures the low-level GAPIC `storage_v2` client.""" + transport_cls = storage_v2.StorageClient.get_transport_class("grpc") + + channel = transport_cls.create_channel(attempt_direct_path=attempt_direct_path) + + transport = transport_cls(credentials=credentials, channel=channel) + + return storage_v2.StorageClient( + credentials=credentials, + transport=transport, + client_info=client_info, + client_options=client_options, + ) + + @property + def grpc_client(self): + """The underlying gRPC client. + + This property gives users direct access to the `storage_v2.StorageClient` + instance. This can be useful for accessing + newly added or experimental RPCs that are not yet exposed through + the high-level GrpcClient. + + Returns: + google.cloud.storage_v2.StorageClient: The configured GAPIC client. + """ + return self._grpc_client diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/hmac_key.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/hmac_key.py new file mode 100644 index 0000000000000000000000000000000000000000..547650366e1fcc7e3db0269f1f4c9bf5bd33c03c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/hmac_key.py @@ -0,0 +1,306 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Configure HMAC keys that can be used to authenticate requests to Google Cloud Storage. + +See [HMAC keys documentation](https://cloud.google.com/storage/docs/authentication/hmackeys) +""" + +from google.cloud.exceptions import NotFound +from google.cloud._helpers import _rfc3339_nanos_to_datetime + +from google.cloud.storage._opentelemetry_tracing import create_trace_span +from google.cloud.storage.constants import _DEFAULT_TIMEOUT +from google.cloud.storage.retry import DEFAULT_RETRY +from google.cloud.storage.retry import DEFAULT_RETRY_IF_ETAG_IN_JSON + + +class HMACKeyMetadata(object): + """Metadata about an HMAC service account key withn Cloud Storage. + + :type client: :class:`~google.cloud.stoage.client.Client` + :param client: client associated with the key metadata. + + :type access_id: str + :param access_id: (Optional) Unique ID of an existing key. + + :type project_id: str + :param project_id: (Optional) Project ID of an existing key. + Defaults to client's project. + + :type user_project: str + :param user_project: (Optional) This parameter is currently ignored. + """ + + ACTIVE_STATE = "ACTIVE" + """Key is active, and may be used to sign requests.""" + INACTIVE_STATE = "INACTIVE" + """Key is inactive, and may not be used to sign requests. + + It can be re-activated via :meth:`update`. + """ + DELETED_STATE = "DELETED" + """Key is deleted. It cannot be re-activated.""" + + _SETTABLE_STATES = (ACTIVE_STATE, INACTIVE_STATE) + + def __init__(self, client, access_id=None, project_id=None, user_project=None): + self._client = client + self._properties = {} + + if access_id is not None: + self._properties["accessId"] = access_id + + if project_id is not None: + self._properties["projectId"] = project_id + + self._user_project = user_project + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return NotImplemented + + return self._client == other._client and self.access_id == other.access_id + + def __hash__(self): + return hash(self._client) + hash(self.access_id) + + @property + def access_id(self): + """Access ID of the key. + + :rtype: str or None + :returns: unique identifier of the key within a project. + """ + return self._properties.get("accessId") + + @property + def etag(self): + """ETag identifying the version of the key metadata. + + :rtype: str or None + :returns: ETag for the version of the key's metadata. + """ + return self._properties.get("etag") + + @property + def id(self): + """ID of the key, including the Project ID and the Access ID. + + :rtype: str or None + :returns: ID of the key. + """ + return self._properties.get("id") + + @property + def project(self): + """Project ID associated with the key. + + :rtype: str or None + :returns: project identfier for the key. + """ + return self._properties.get("projectId") + + @property + def service_account_email(self): + """Service account e-mail address associated with the key. + + :rtype: str or None + :returns: e-mail address for the service account which created the key. + """ + return self._properties.get("serviceAccountEmail") + + @property + def state(self): + """Get / set key's state. + + One of: + - ``ACTIVE`` + - ``INACTIVE`` + - ``DELETED`` + + :rtype: str or None + :returns: key's current state. + """ + return self._properties.get("state") + + @state.setter + def state(self, value): + self._properties["state"] = value + + @property + def time_created(self): + """Retrieve the timestamp at which the HMAC key was created. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the bucket's resource has not been loaded + from the server. + """ + value = self._properties.get("timeCreated") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def updated(self): + """Retrieve the timestamp at which the HMAC key was created. + + :rtype: :class:`datetime.datetime` or ``NoneType`` + :returns: Datetime object parsed from RFC3339 valid timestamp, or + ``None`` if the bucket's resource has not been loaded + from the server. + """ + value = self._properties.get("updated") + if value is not None: + return _rfc3339_nanos_to_datetime(value) + + @property + def path(self): + """Resource path for the metadata's key.""" + + if self.access_id is None: + raise ValueError("No 'access_id' set.") + + project = self.project + if project is None: + project = self._client.project + + return f"/projects/{project}/hmacKeys/{self.access_id}" + + @property + def user_project(self): + """Project ID to be billed for API requests made via this bucket. + + This property is currently ignored by the server. + + :rtype: str + """ + return self._user_project + + def exists(self, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY): + """Determine whether or not the key for this metadata exists. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: bool + :returns: True if the key exists in Cloud Storage. + """ + with create_trace_span(name="Storage.HmacKey.exists"): + try: + qs_params = {} + + if self.user_project is not None: + qs_params["userProject"] = self.user_project + + self._client._get_resource( + self.path, + query_params=qs_params, + timeout=timeout, + retry=retry, + ) + except NotFound: + return False + else: + return True + + def reload(self, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY): + """Reload properties from Cloud Storage. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises :class:`~google.api_core.exceptions.NotFound`: + if the key does not exist on the back-end. + """ + with create_trace_span(name="Storage.HmacKey.reload"): + qs_params = {} + + if self.user_project is not None: + qs_params["userProject"] = self.user_project + + self._properties = self._client._get_resource( + self.path, + query_params=qs_params, + timeout=timeout, + retry=retry, + ) + + def update(self, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY_IF_ETAG_IN_JSON): + """Save writable properties to Cloud Storage. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises :class:`~google.api_core.exceptions.NotFound`: + if the key does not exist on the back-end. + """ + with create_trace_span(name="Storage.HmacKey.update"): + qs_params = {} + if self.user_project is not None: + qs_params["userProject"] = self.user_project + + payload = {"state": self.state} + self._properties = self._client._put_resource( + self.path, + payload, + query_params=qs_params, + timeout=timeout, + retry=retry, + ) + + def delete(self, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY): + """Delete the key from Cloud Storage. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises :class:`~google.api_core.exceptions.NotFound`: + if the key does not exist on the back-end. + """ + with create_trace_span(name="Storage.HmacKey.delete"): + qs_params = {} + if self.user_project is not None: + qs_params["userProject"] = self.user_project + + self._client._delete_resource( + self.path, + query_params=qs_params, + timeout=timeout, + retry=retry, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/iam.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/iam.py new file mode 100644 index 0000000000000000000000000000000000000000..36c7412b842a4bb4006cb76447ff9a5de4b7dcbd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/iam.py @@ -0,0 +1,86 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Storage API IAM policy definitions + +For allowed roles / permissions, see: +https://cloud.google.com/storage/docs/access-control/iam +""" + +# Storage-specific IAM roles + +STORAGE_OBJECT_CREATOR_ROLE = "roles/storage.objectCreator" +"""Role implying rights to create objects, but not delete or overwrite them.""" + +STORAGE_OBJECT_VIEWER_ROLE = "roles/storage.objectViewer" +"""Role implying rights to view object properties, excluding ACLs.""" + +STORAGE_OBJECT_ADMIN_ROLE = "roles/storage.objectAdmin" +"""Role implying full control of objects.""" + +STORAGE_ADMIN_ROLE = "roles/storage.admin" +"""Role implying full control of objects and buckets.""" + +STORAGE_VIEWER_ROLE = "Viewer" +"""Can list buckets.""" + +STORAGE_EDITOR_ROLE = "Editor" +"""Can create, list, and delete buckets.""" + +STORAGE_OWNER_ROLE = "Owners" +"""Can create, list, and delete buckets.""" + + +# Storage-specific permissions + +STORAGE_BUCKETS_CREATE = "storage.buckets.create" +"""Permission: create buckets.""" + +STORAGE_BUCKETS_DELETE = "storage.buckets.delete" +"""Permission: delete buckets.""" + +STORAGE_BUCKETS_GET = "storage.buckets.get" +"""Permission: read bucket metadata, excluding ACLs.""" + +STORAGE_BUCKETS_GET_IAM_POLICY = "storage.buckets.getIamPolicy" +"""Permission: read bucket ACLs.""" + +STORAGE_BUCKETS_LIST = "storage.buckets.list" +"""Permission: list buckets.""" + +STORAGE_BUCKETS_SET_IAM_POLICY = "storage.buckets.setIamPolicy" +"""Permission: update bucket ACLs.""" + +STORAGE_BUCKETS_UPDATE = "storage.buckets.list" +"""Permission: update buckets, excluding ACLS.""" + +STORAGE_OBJECTS_CREATE = "storage.objects.create" +"""Permission: add new objects to a bucket.""" + +STORAGE_OBJECTS_DELETE = "storage.objects.delete" +"""Permission: delete objects.""" + +STORAGE_OBJECTS_GET = "storage.objects.get" +"""Permission: read object data / metadata, excluding ACLs.""" + +STORAGE_OBJECTS_GET_IAM_POLICY = "storage.objects.getIamPolicy" +"""Permission: read object ACLs.""" + +STORAGE_OBJECTS_LIST = "storage.objects.list" +"""Permission: list objects in a bucket.""" + +STORAGE_OBJECTS_SET_IAM_POLICY = "storage.objects.setIamPolicy" +"""Permission: update object ACLs.""" + +STORAGE_OBJECTS_UPDATE = "storage.objects.update" +"""Permission: update object metadat, excluding ACLs.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/ip_filter.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/ip_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b2318bfd8144e7d72272ed28e27d45215b6b8b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/ip_filter.py @@ -0,0 +1,143 @@ +# Copyright 2014 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""IP Filter configuration for Google Cloud Storage Buckets.""" + +from typing import Dict, Any, Optional, List + +_MODE = "mode" +_PUBLIC_NETWORK_SOURCE = "publicNetworkSource" +_VPC_NETWORK_SOURCES = "vpcNetworkSources" +_ALLOWED_IP_CIDR_RANGES = "allowedIpCidrRanges" +_NETWORK = "network" +_ALLOW_ALL_SERVICE_AGENT_ACCESS = "allowAllServiceAgentAccess" +_ALLOW_CROSS_ORG_VPCS = "allowCrossOrgVpcs" + + +class PublicNetworkSource: + """Represents a public network source for a GCS Bucket IP Filter. + + :type allowed_ip_cidr_ranges: list(str) or None + :param allowed_ip_cidr_ranges: A list of public IPv4 or IPv6 ranges in + CIDR notation that are allowed to access + the bucket. + """ + + def __init__(self, allowed_ip_cidr_ranges: Optional[List[str]] = None): + self.allowed_ip_cidr_ranges = allowed_ip_cidr_ranges or [] + + def _to_api_resource(self) -> Dict[str, Any]: + """Serializes this object to a dictionary for API requests.""" + return {_ALLOWED_IP_CIDR_RANGES: self.allowed_ip_cidr_ranges} + + +class VpcNetworkSource: + """Represents a VPC network source for a GCS Bucket IP Filter. + + :type network: str + :param network: The resource name of the VPC network. + + :type allowed_ip_cidr_ranges: list(str) or None + :param allowed_ip_cidr_ranges: A list of IPv4 or IPv6 ranges in CIDR + notation allowed to access the bucket + from this VPC. + """ + + def __init__( + self, network: str, allowed_ip_cidr_ranges: Optional[List[str]] = None + ): + self.network = network + self.allowed_ip_cidr_ranges = allowed_ip_cidr_ranges or [] + + def _to_api_resource(self) -> Dict[str, Any]: + """Serializes this object to a dictionary for API requests.""" + return { + _NETWORK: self.network, + _ALLOWED_IP_CIDR_RANGES: self.allowed_ip_cidr_ranges, + } + + +class IPFilter: + """Represents a GCS Bucket IP Filter configuration. + + This class is a helper for constructing the IP Filter dictionary to be + assigned to a bucket's ``ip_filter`` property. + """ + + """ + Attributes: + mode (str): Required. The mode of the IP filter. Can be "Enabled" or "Disabled". + allow_all_service_agent_access (bool): Required. If True, allows Google + Cloud service agents to bypass the IP filter. + public_network_source (PublicNetworkSource): (Optional) The configuration + for requests from the public internet. + vpc_network_sources (list(VpcNetworkSource)): (Optional) A list of + configurations for requests from VPC networks. + allow_cross_org_vpcs (bool): (Optional) If True, allows VPCs from + other organizations to be used in the configuration. + """ + + def __init__(self): + self.mode: Optional[str] = None + self.public_network_source: Optional[PublicNetworkSource] = None + self.vpc_network_sources: List[VpcNetworkSource] = [] + self.allow_all_service_agent_access: Optional[bool] = None + self.allow_cross_org_vpcs: Optional[bool] = None + + @classmethod + def _from_api_resource(cls, resource: Dict[str, Any]) -> "IPFilter": + """Factory: creates an IPFilter instance from a server response.""" + ip_filter = cls() + ip_filter.mode = resource.get(_MODE) + ip_filter.allow_all_service_agent_access = resource.get( + _ALLOW_ALL_SERVICE_AGENT_ACCESS, None + ) + + public_network_source_data = resource.get(_PUBLIC_NETWORK_SOURCE, None) + if public_network_source_data: + ip_filter.public_network_source = PublicNetworkSource( + allowed_ip_cidr_ranges=public_network_source_data.get( + _ALLOWED_IP_CIDR_RANGES, [] + ) + ) + + vns_res_list = resource.get(_VPC_NETWORK_SOURCES, []) + ip_filter.vpc_network_sources = [ + VpcNetworkSource( + network=vns.get(_NETWORK), + allowed_ip_cidr_ranges=vns.get(_ALLOWED_IP_CIDR_RANGES, []), + ) + for vns in vns_res_list + ] + ip_filter.allow_cross_org_vpcs = resource.get(_ALLOW_CROSS_ORG_VPCS, None) + return ip_filter + + def _to_api_resource(self) -> Dict[str, Any]: + """Serializes this object to a dictionary for API requests.""" + resource = { + _MODE: self.mode, + _ALLOW_ALL_SERVICE_AGENT_ACCESS: self.allow_all_service_agent_access, + } + + if self.public_network_source: + resource[ + _PUBLIC_NETWORK_SOURCE + ] = self.public_network_source._to_api_resource() + if self.vpc_network_sources is not None: + resource[_VPC_NETWORK_SOURCES] = [ + vns._to_api_resource() for vns in self.vpc_network_sources + ] + if self.allow_cross_org_vpcs is not None: + resource[_ALLOW_CROSS_ORG_VPCS] = self.allow_cross_org_vpcs + return resource diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/notification.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/notification.py new file mode 100644 index 0000000000000000000000000000000000000000..2dddbcee44903b80c3c9850d35041a69ff7b4403 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/notification.py @@ -0,0 +1,457 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Configure bucket notification resources to interact with Google Cloud Pub/Sub. + +See [Cloud Pub/Sub Notifications for Google Cloud Storage](https://cloud.google.com/storage/docs/pubsub-notifications) +""" + +import re + +from google.api_core.exceptions import NotFound + +from google.cloud.storage._opentelemetry_tracing import create_trace_span +from google.cloud.storage.constants import _DEFAULT_TIMEOUT +from google.cloud.storage.retry import DEFAULT_RETRY + + +OBJECT_FINALIZE_EVENT_TYPE = "OBJECT_FINALIZE" +OBJECT_METADATA_UPDATE_EVENT_TYPE = "OBJECT_METADATA_UPDATE" +OBJECT_DELETE_EVENT_TYPE = "OBJECT_DELETE" +OBJECT_ARCHIVE_EVENT_TYPE = "OBJECT_ARCHIVE" + +JSON_API_V1_PAYLOAD_FORMAT = "JSON_API_V1" +NONE_PAYLOAD_FORMAT = "NONE" + +_TOPIC_REF_FMT = "//pubsub.googleapis.com/projects/{}/topics/{}" +_PROJECT_PATTERN = r"(?P[a-z][a-z0-9-]{4,28}[a-z0-9])" +_TOPIC_NAME_PATTERN = r"(?P[A-Za-z](\w|[-_.~+%])+)" +_TOPIC_REF_PATTERN = _TOPIC_REF_FMT.format(_PROJECT_PATTERN, _TOPIC_NAME_PATTERN) +_TOPIC_REF_RE = re.compile(_TOPIC_REF_PATTERN) +_BAD_TOPIC = ( + "Resource has invalid topic: {}; see " + "https://cloud.google.com/storage/docs/json_api/v1/" + "notifications/insert#topic" +) + + +class BucketNotification(object): + """Represent a single notification resource for a bucket. + + See: https://cloud.google.com/storage/docs/json_api/v1/notifications + + :type bucket: :class:`google.cloud.storage.bucket.Bucket` + :param bucket: Bucket to which the notification is bound. + + :type topic_name: str + :param topic_name: + (Optional) Topic name to which notifications are published. + + :type topic_project: str + :param topic_project: + (Optional) Project ID of topic to which notifications are published. + If not passed, uses the project ID of the bucket's client. + + :type custom_attributes: dict + :param custom_attributes: + (Optional) Additional attributes passed with notification events. + + :type event_types: list(str) + :param event_types: + (Optional) Event types for which notification events are published. + + :type blob_name_prefix: str + :param blob_name_prefix: + (Optional) Prefix of blob names for which notification events are + published. + + :type payload_format: str + :param payload_format: + (Optional) Format of payload for notification events. + + :type notification_id: str + :param notification_id: + (Optional) The ID of the notification. + """ + + def __init__( + self, + bucket, + topic_name=None, + topic_project=None, + custom_attributes=None, + event_types=None, + blob_name_prefix=None, + payload_format=NONE_PAYLOAD_FORMAT, + notification_id=None, + ): + self._bucket = bucket + self._topic_name = topic_name + + if topic_project is None: + topic_project = bucket.client.project + + if topic_project is None: + raise ValueError("Client project not set: pass an explicit topic_project.") + + self._topic_project = topic_project + + self._properties = {} + + if custom_attributes is not None: + self._properties["custom_attributes"] = custom_attributes + + if event_types is not None: + self._properties["event_types"] = event_types + + if blob_name_prefix is not None: + self._properties["object_name_prefix"] = blob_name_prefix + + if notification_id is not None: + self._properties["id"] = notification_id + + self._properties["payload_format"] = payload_format + + @classmethod + def from_api_repr(cls, resource, bucket): + """Construct an instance from the JSON repr returned by the server. + + See: https://cloud.google.com/storage/docs/json_api/v1/notifications + + :type resource: dict + :param resource: JSON repr of the notification + + :type bucket: :class:`google.cloud.storage.bucket.Bucket` + :param bucket: Bucket to which the notification is bound. + + :rtype: :class:`BucketNotification` + :returns: the new notification instance + """ + topic_path = resource.get("topic") + if topic_path is None: + raise ValueError("Resource has no topic") + + name, project = _parse_topic_path(topic_path) + instance = cls(bucket, name, topic_project=project) + instance._properties = resource + + return instance + + @property + def bucket(self): + """Bucket to which the notification is bound.""" + return self._bucket + + @property + def topic_name(self): + """Topic name to which notifications are published.""" + return self._topic_name + + @property + def topic_project(self): + """Project ID of topic to which notifications are published.""" + return self._topic_project + + @property + def custom_attributes(self): + """Custom attributes passed with notification events.""" + return self._properties.get("custom_attributes") + + @property + def event_types(self): + """Event types for which notification events are published.""" + return self._properties.get("event_types") + + @property + def blob_name_prefix(self): + """Prefix of blob names for which notification events are published.""" + return self._properties.get("object_name_prefix") + + @property + def payload_format(self): + """Format of payload of notification events.""" + return self._properties.get("payload_format") + + @property + def notification_id(self): + """Server-set ID of notification resource.""" + return self._properties.get("id") + + @property + def etag(self): + """Server-set ETag of notification resource.""" + return self._properties.get("etag") + + @property + def self_link(self): + """Server-set ETag of notification resource.""" + return self._properties.get("selfLink") + + @property + def client(self): + """The client bound to this notfication.""" + return self.bucket.client + + @property + def path(self): + """The URL path for this notification.""" + return f"/b/{self.bucket.name}/notificationConfigs/{self.notification_id}" + + def _require_client(self, client): + """Check client or verify over-ride. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: the client to use. + + :rtype: :class:`google.cloud.storage.client.Client` + :returns: The client passed in or the bucket's client. + """ + if client is None: + client = self.client + return client + + def _set_properties(self, response): + """Helper for :meth:`reload`. + + :type response: dict + :param response: resource mapping from server + """ + self._properties.clear() + self._properties.update(response) + + def create(self, client=None, timeout=_DEFAULT_TIMEOUT, retry=None): + """API wrapper: create the notification. + + See: + https://cloud.google.com/storage/docs/json_api/v1/notifications/insert + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the notification's bucket. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises ValueError: if the notification already exists. + """ + with create_trace_span(name="Storage.BucketNotification.create"): + if self.notification_id is not None: + raise ValueError( + f"notification_id already set to {self.notification_id}; must be None to create a Notification." # noqa: E702 + ) + + client = self._require_client(client) + + query_params = {} + if self.bucket.user_project is not None: + query_params["userProject"] = self.bucket.user_project + + path = f"/b/{self.bucket.name}/notificationConfigs" + properties = self._properties.copy() + + if self.topic_name is None: + properties["topic"] = _TOPIC_REF_FMT.format(self.topic_project, "") + else: + properties["topic"] = _TOPIC_REF_FMT.format( + self.topic_project, self.topic_name + ) + + self._properties = client._post_resource( + path, + properties, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + + def exists(self, client=None, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY): + """Test whether this notification exists. + + See: + https://cloud.google.com/storage/docs/json_api/v1/notifications/get + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :rtype: bool + :returns: True, if the notification exists, else False. + :raises ValueError: if the notification has no ID. + """ + with create_trace_span(name="Storage.BucketNotification.exists"): + if self.notification_id is None: + raise ValueError( + "Notification ID not set: set an explicit notification_id" + ) + + client = self._require_client(client) + + query_params = {} + if self.bucket.user_project is not None: + query_params["userProject"] = self.bucket.user_project + + try: + client._get_resource( + self.path, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + except NotFound: + return False + else: + return True + + def reload(self, client=None, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY): + """Update this notification from the server configuration. + + See: + https://cloud.google.com/storage/docs/json_api/v1/notifications/get + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + + :raises ValueError: if the notification has no ID. + """ + with create_trace_span(name="Storage.BucketNotification.reload"): + if self.notification_id is None: + raise ValueError( + "Notification ID not set: set an explicit notification_id" + ) + + client = self._require_client(client) + + query_params = {} + if self.bucket.user_project is not None: + query_params["userProject"] = self.bucket.user_project + + response = client._get_resource( + self.path, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + self._set_properties(response) + + def delete(self, client=None, timeout=_DEFAULT_TIMEOUT, retry=DEFAULT_RETRY): + """Delete this notification. + + See: + https://cloud.google.com/storage/docs/json_api/v1/notifications/delete + + If :attr:`user_project` is set on the bucket, bills the API request + to that project. + + :type client: :class:`~google.cloud.storage.client.Client` or + ``NoneType`` + :param client: (Optional) The client to use. If not passed, falls back + to the ``client`` stored on the current bucket. + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy + :param retry: + (Optional) How to retry the RPC. See: :ref:`configuring_retries` + + :raises: :class:`google.api_core.exceptions.NotFound`: + if the notification does not exist. + :raises ValueError: if the notification has no ID. + """ + with create_trace_span(name="Storage.BucketNotification.delete"): + if self.notification_id is None: + raise ValueError( + "Notification ID not set: set an explicit notification_id" + ) + + client = self._require_client(client) + + query_params = {} + if self.bucket.user_project is not None: + query_params["userProject"] = self.bucket.user_project + + client._delete_resource( + self.path, + query_params=query_params, + timeout=timeout, + retry=retry, + ) + + +def _parse_topic_path(topic_path): + """Verify that a topic path is in the correct format. + + Expected to be of the form: + + //pubsub.googleapis.com/projects/{project}/topics/{topic} + + where the ``project`` value must be "6 to 30 lowercase letters, digits, + or hyphens. It must start with a letter. Trailing hyphens are prohibited." + (see [`resource manager docs`](https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects#Project.FIELDS.project_id)) + and ``topic`` must have length at least two, + must start with a letter and may only contain alphanumeric characters or + ``-``, ``_``, ``.``, ``~``, ``+`` or ``%`` (i.e characters used for URL + encoding, see [`topic spec`](https://cloud.google.com/storage/docs/json_api/v1/notifications/insert#topic)). + + Args: + topic_path (str): The topic path to be verified. + + Returns: + Tuple[str, str]: The ``project`` and ``topic`` parsed from the + ``topic_path``. + + Raises: + ValueError: If the topic path is invalid. + """ + match = _TOPIC_REF_RE.match(topic_path) + if match is None: + raise ValueError(_BAD_TOPIC.format(topic_path)) + + return match.group("name"), match.group("project") diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/retry.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d5a768616d1fd147547f11472a5a7163eabe6e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/retry.py @@ -0,0 +1,188 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helpers for configuring retries with exponential back-off. + +See [Retry Strategy for Google Cloud Storage](https://cloud.google.com/storage/docs/retry-strategy#client-libraries) +""" + +import http + +import requests +import requests.exceptions as requests_exceptions +import urllib3 + +from google.api_core import exceptions as api_exceptions +from google.api_core import retry +from google.auth import exceptions as auth_exceptions +from google.cloud.storage.exceptions import InvalidResponse + + +_RETRYABLE_TYPES = ( + api_exceptions.TooManyRequests, # 429 + api_exceptions.InternalServerError, # 500 + api_exceptions.BadGateway, # 502 + api_exceptions.ServiceUnavailable, # 503 + api_exceptions.GatewayTimeout, # 504 + ConnectionError, + requests.ConnectionError, + requests_exceptions.ChunkedEncodingError, + requests_exceptions.Timeout, + http.client.BadStatusLine, + http.client.IncompleteRead, + http.client.ResponseNotReady, + urllib3.exceptions.PoolError, + urllib3.exceptions.ProtocolError, + urllib3.exceptions.SSLError, + urllib3.exceptions.TimeoutError, +) + + +_RETRYABLE_STATUS_CODES = ( + http.client.TOO_MANY_REQUESTS, # 429 + http.client.REQUEST_TIMEOUT, # 408 + http.client.INTERNAL_SERVER_ERROR, # 500 + http.client.BAD_GATEWAY, # 502 + http.client.SERVICE_UNAVAILABLE, # 503 + http.client.GATEWAY_TIMEOUT, # 504 +) + + +def _should_retry(exc): + """Predicate for determining when to retry.""" + if isinstance(exc, _RETRYABLE_TYPES): + return True + elif isinstance(exc, api_exceptions.GoogleAPICallError): + return exc.code in _RETRYABLE_STATUS_CODES + elif isinstance(exc, InvalidResponse): + return exc.response.status_code in _RETRYABLE_STATUS_CODES + elif isinstance(exc, auth_exceptions.TransportError): + return _should_retry(exc.args[0]) + else: + return False + + +DEFAULT_RETRY = retry.Retry(predicate=_should_retry) +"""The default retry object. + +This retry setting will retry all _RETRYABLE_TYPES and any status codes from +_ADDITIONAL_RETRYABLE_STATUS_CODES. + +To modify the default retry behavior, create a new retry object modeled after +this one by calling it a ``with_XXX`` method. For example, to create a copy of +DEFAULT_RETRY with a deadline of 30 seconds, pass +``retry=DEFAULT_RETRY.with_deadline(30)``. See google-api-core reference +(https://googleapis.dev/python/google-api-core/latest/retry.html) for details. +""" + + +class ConditionalRetryPolicy(object): + """A class for use when an API call is only conditionally safe to retry. + + This class is intended for use in inspecting the API call parameters of an + API call to verify that any flags necessary to make the API call idempotent + (such as specifying an ``if_generation_match`` or related flag) are present. + + It can be used in place of a ``retry.Retry`` object, in which case + ``_http.Connection.api_request`` will pass the requested api call keyword + arguments into the ``conditional_predicate`` and return the ``retry_policy`` + if the conditions are met. + + :type retry_policy: class:`google.api_core.retry.Retry` + :param retry_policy: A retry object defining timeouts, persistence and which + exceptions to retry. + + :type conditional_predicate: callable + :param conditional_predicate: A callable that accepts exactly the number of + arguments in ``required_kwargs``, in order, and returns True if the + arguments have sufficient data to determine that the call is safe to + retry (idempotent). + + :type required_kwargs: list(str) + :param required_kwargs: + A list of keyword argument keys that will be extracted from the API call + and passed into the ``conditional predicate`` in order. For example, + ``["query_params"]`` is commmonly used for preconditions in query_params. + """ + + def __init__(self, retry_policy, conditional_predicate, required_kwargs): + self.retry_policy = retry_policy + self.conditional_predicate = conditional_predicate + self.required_kwargs = required_kwargs + + def get_retry_policy_if_conditions_met(self, **kwargs): + if self.conditional_predicate(*[kwargs[key] for key in self.required_kwargs]): + return self.retry_policy + return None + + +def is_generation_specified(query_params): + """Return True if generation or if_generation_match is specified.""" + generation = query_params.get("generation") is not None + if_generation_match = query_params.get("ifGenerationMatch") is not None + return generation or if_generation_match + + +def is_metageneration_specified(query_params): + """Return True if if_metageneration_match is specified.""" + if_metageneration_match = query_params.get("ifMetagenerationMatch") is not None + return if_metageneration_match + + +def is_etag_in_data(data): + """Return True if an etag is contained in the request body. + + :type data: dict or None + :param data: A dict representing the request JSON body. If not passed, returns False. + """ + return data is not None and "etag" in data + + +def is_etag_in_json(data): + """ + ``is_etag_in_json`` is supported for backwards-compatibility reasons only; + please use ``is_etag_in_data`` instead. + """ + return is_etag_in_data(data) + + +DEFAULT_RETRY_IF_GENERATION_SPECIFIED = ConditionalRetryPolicy( + DEFAULT_RETRY, is_generation_specified, ["query_params"] +) +"""Conditional wrapper for the default retry object. + +This retry setting will retry all _RETRYABLE_TYPES and any status codes from +_ADDITIONAL_RETRYABLE_STATUS_CODES, but only if the request included an +``ifGenerationMatch`` header. +""" + +DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED = ConditionalRetryPolicy( + DEFAULT_RETRY, is_metageneration_specified, ["query_params"] +) +"""Conditional wrapper for the default retry object. + +This retry setting will retry all _RETRYABLE_TYPES and any status codes from +_ADDITIONAL_RETRYABLE_STATUS_CODES, but only if the request included an +``ifMetagenerationMatch`` header. +""" + +DEFAULT_RETRY_IF_ETAG_IN_JSON = ConditionalRetryPolicy( + DEFAULT_RETRY, is_etag_in_json, ["data"] +) +"""Conditional wrapper for the default retry object. + +This retry setting will retry all _RETRYABLE_TYPES and any status codes from +_ADDITIONAL_RETRYABLE_STATUS_CODES, but only if the request included an +``ETAG`` entry in its payload. +""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/transfer_manager.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/transfer_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..7f4173690343791e36a0b9d2858257e4c139c405 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/transfer_manager.py @@ -0,0 +1,1471 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Concurrent media operations.""" + +import concurrent.futures + +import io +import inspect +import os +import warnings +import pickle +import copyreg +import struct +import base64 +import functools +from pathlib import Path + +from google.api_core import exceptions +from google.cloud.storage import Client +from google.cloud.storage import Blob +from google.cloud.storage.blob import _get_host_name +from google.cloud.storage.blob import _quote +from google.cloud.storage.constants import _DEFAULT_TIMEOUT +from google.cloud.storage.retry import DEFAULT_RETRY + +import google_crc32c + +from google.cloud.storage._media.requests.upload import XMLMPUContainer +from google.cloud.storage._media.requests.upload import XMLMPUPart +from google.cloud.storage.exceptions import DataCorruption, InvalidPathError + +TM_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024 +DEFAULT_MAX_WORKERS = 8 +MAX_CRC32C_ZERO_ARRAY_SIZE = 4 * 1024 * 1024 +METADATA_HEADER_TRANSLATION = { + "cacheControl": "Cache-Control", + "contentDisposition": "Content-Disposition", + "contentEncoding": "Content-Encoding", + "contentLanguage": "Content-Language", + "customTime": "x-goog-custom-time", + "storageClass": "x-goog-storage-class", +} + +# Constants to be passed in as `worker_type`. +PROCESS = "process" +THREAD = "thread" + +DOWNLOAD_CRC32C_MISMATCH_TEMPLATE = """\ +Checksum mismatch while downloading: + + {} + +The object metadata indicated a crc32c checksum of: + + {} + +but the actual crc32c checksum of the downloaded contents was: + + {} +""" + + +_cached_clients = {} + + +def _deprecate_threads_param(func): + @functools.wraps(func) + def convert_threads_or_raise(*args, **kwargs): + binding = inspect.signature(func).bind(*args, **kwargs) + threads = binding.arguments.get("threads") + if threads: + worker_type = binding.arguments.get("worker_type") + max_workers = binding.arguments.get("max_workers") + if worker_type or max_workers: # Parameter conflict + raise ValueError( + "The `threads` parameter is deprecated and conflicts with its replacement parameters, `worker_type` and `max_workers`." + ) + # No conflict, so issue a warning and set worker_type and max_workers. + warnings.warn( + "The `threads` parameter is deprecated. Please use `worker_type` and `max_workers` parameters instead." + ) + args = binding.args + kwargs = binding.kwargs + kwargs["worker_type"] = THREAD + kwargs["max_workers"] = threads + return func(*args, **kwargs) + else: + return func(*args, **kwargs) + + return convert_threads_or_raise + + +@_deprecate_threads_param +def upload_many( + file_blob_pairs, + skip_if_exists=False, + upload_kwargs=None, + threads=None, + deadline=None, + raise_exception=False, + worker_type=PROCESS, + max_workers=DEFAULT_MAX_WORKERS, +): + """Upload many files concurrently via a worker pool. + + :type file_blob_pairs: List(Tuple(IOBase or str, 'google.cloud.storage.blob.Blob')) + :param file_blob_pairs: + A list of tuples of a file or filename and a blob. Each file will be + uploaded to the corresponding blob by using APIs identical to + `blob.upload_from_file()` or `blob.upload_from_filename()` as + appropriate. + + File handlers are only supported if worker_type is set to THREAD. + If worker_type is set to PROCESS, please use filenames only. + + :type skip_if_exists: bool + :param skip_if_exists: + If True, blobs that already have a live version will not be overwritten. + This is accomplished by setting `if_generation_match = 0` on uploads. + Uploads so skipped will result in a 412 Precondition Failed response + code, which will be included in the return value but not raised + as an exception regardless of the value of raise_exception. + + :type upload_kwargs: dict + :param upload_kwargs: + A dictionary of keyword arguments to pass to the upload method. Refer + to the documentation for `blob.upload_from_file()` or + `blob.upload_from_filename()` for more information. The dict is directly + passed into the upload methods and is not validated by this function. + + :type threads: int + :param threads: + ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the + number specified. If `worker_type` or `max_workers` are set explicitly, + this parameter should be set to None. Please use `worker_type` and + `max_workers` instead of this parameter. + + :type deadline: int + :param deadline: + The number of seconds to wait for all threads to resolve. If the + deadline is reached, all threads will be terminated regardless of their + progress and `concurrent.futures.TimeoutError` will be raised. This can + be left as the default of `None` (no deadline) for most use cases. + + :type raise_exception: bool + :param raise_exception: + If True, instead of adding exceptions to the list of return values, + instead they will be raised. Note that encountering an exception on one + operation will not prevent other operations from starting. Exceptions + are only processed and potentially raised after all operations are + complete in success or failure. + + If skip_if_exists is True, 412 Precondition Failed responses are + considered part of normal operation and are not raised as an exception. + + :type worker_type: str + :param worker_type: + The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS` + or `google.cloud.storage.transfer_manager.THREAD`. + + Although the exact performance impact depends on the use case, in most + situations the PROCESS worker type will use more system resources (both + memory and CPU) and result in faster operations than THREAD workers. + + Because the subprocesses of the PROCESS worker type can't access memory + from the main process, Client objects have to be serialized and then + recreated in each subprocess. The serialization of the Client object + for use in subprocesses is an approximation and may not capture every + detail of the Client object, especially if the Client was modified after + its initial creation or if `Client._http` was modified in any way. + + THREAD worker types are observed to be relatively efficient for + operations with many small files, but not for operations with large + files. PROCESS workers are recommended for large file operations. + + PROCESS workers do not support writing to file handlers. Please refer + to files by filename only when using PROCESS workers. + + :type max_workers: int + :param max_workers: + The maximum number of workers to create to handle the workload. + + With PROCESS workers, a larger number of workers will consume more + system resources (memory and CPU) at once. + + How many workers is optimal depends heavily on the specific use case, + and the default is a conservative number that should work okay in most + cases without consuming excessive resources. + + :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded. + + :rtype: list + :returns: A list of results corresponding to, in order, each item in the + input list. If an exception was received, it will be the result + for that operation. Otherwise, the return value from the successful + upload method is used (which will be None). + """ + if upload_kwargs is None: + upload_kwargs = {} + + if skip_if_exists: + upload_kwargs = upload_kwargs.copy() + upload_kwargs["if_generation_match"] = 0 + + upload_kwargs["command"] = "tm.upload_many" + + pool_class, needs_pickling = _get_pool_class_and_requirements(worker_type) + + with pool_class(max_workers=max_workers) as executor: + futures = [] + for path_or_file, blob in file_blob_pairs: + # File objects are only supported by the THREAD worker because they can't + # be pickled. + if needs_pickling and not isinstance(path_or_file, str): + raise ValueError( + "Passing in a file object is only supported by the THREAD worker type. Please either select THREAD workers, or pass in filenames only." + ) + + futures.append( + executor.submit( + _call_method_on_maybe_pickled_blob, + _pickle_client(blob) if needs_pickling else blob, + ( + "_handle_filename_and_upload" + if isinstance(path_or_file, str) + else "_prep_and_do_upload" + ), + path_or_file, + **upload_kwargs, + ) + ) + concurrent.futures.wait( + futures, timeout=deadline, return_when=concurrent.futures.ALL_COMPLETED + ) + + results = [] + for future in futures: + exp = future.exception() + + # If raise_exception is False, don't call future.result() + if exp and not raise_exception: + results.append(exp) + # If skip_if_exists and the exception is PreconditionFailed, do same. + elif exp and skip_if_exists and isinstance(exp, exceptions.PreconditionFailed): + results.append(exp) + # Get the real result. If there was an exception not handled above, + # this will raise it. + else: + results.append(future.result()) + return results + + +def _resolve_path(target_dir, blob_path): + if os.name == "nt" and ":" in blob_path: + raise InvalidPathError(f"{blob_path} cannot be downloaded into {target_dir}") + target_dir = Path(target_dir) + blob_path = Path(blob_path) + # blob_path.anchor will be '/' if `blob_path` is full path else it'll empty. + # This is useful to concatnate target_dir = /local/target , and blob_path = + # /usr/local/mybin into /local/target/usr/local/mybin + concatenated_path = target_dir / blob_path.relative_to(blob_path.anchor) + return concatenated_path.resolve() + + +@_deprecate_threads_param +def download_many( + blob_file_pairs, + download_kwargs=None, + threads=None, + deadline=None, + raise_exception=False, + worker_type=PROCESS, + max_workers=DEFAULT_MAX_WORKERS, + *, + skip_if_exists=False, +): + """Download many blobs concurrently via a worker pool. + + :type blob_file_pairs: List(Tuple('google.cloud.storage.blob.Blob', IOBase or str)) + :param blob_file_pairs: + A list of tuples of blob and a file or filename. Each blob will be downloaded to the corresponding blob by using APIs identical to blob.download_to_file() or blob.download_to_filename() as appropriate. + + Note that blob.download_to_filename() does not delete the destination file if the download fails. + + File handlers are only supported if worker_type is set to THREAD. + If worker_type is set to PROCESS, please use filenames only. + + :type download_kwargs: dict + :param download_kwargs: + A dictionary of keyword arguments to pass to the download method. Refer + to the documentation for `blob.download_to_file()` or + `blob.download_to_filename()` for more information. The dict is directly + passed into the download methods and is not validated by this function. + + :type threads: int + :param threads: + ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the + number specified. If `worker_type` or `max_workers` are set explicitly, + this parameter should be set to None. Please use `worker_type` and + `max_workers` instead of this parameter. + + :type deadline: int + :param deadline: + The number of seconds to wait for all threads to resolve. If the + deadline is reached, all threads will be terminated regardless of their + progress and `concurrent.futures.TimeoutError` will be raised. This can + be left as the default of `None` (no deadline) for most use cases. + + :type raise_exception: bool + :param raise_exception: + If True, instead of adding exceptions to the list of return values, + instead they will be raised. Note that encountering an exception on one + operation will not prevent other operations from starting. Exceptions + are only processed and potentially raised after all operations are + complete in success or failure. + + :type worker_type: str + :param worker_type: + The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS` + or `google.cloud.storage.transfer_manager.THREAD`. + + Although the exact performance impact depends on the use case, in most + situations the PROCESS worker type will use more system resources (both + memory and CPU) and result in faster operations than THREAD workers. + + Because the subprocesses of the PROCESS worker type can't access memory + from the main process, Client objects have to be serialized and then + recreated in each subprocess. The serialization of the Client object + for use in subprocesses is an approximation and may not capture every + detail of the Client object, especially if the Client was modified after + its initial creation or if `Client._http` was modified in any way. + + THREAD worker types are observed to be relatively efficient for + operations with many small files, but not for operations with large + files. PROCESS workers are recommended for large file operations. + + PROCESS workers do not support writing to file handlers. Please refer + to files by filename only when using PROCESS workers. + + :type max_workers: int + :param max_workers: + The maximum number of workers to create to handle the workload. + + With PROCESS workers, a larger number of workers will consume more + system resources (memory and CPU) at once. + + How many workers is optimal depends heavily on the specific use case, + and the default is a conservative number that should work okay in most + cases without consuming excessive resources. + + :type skip_if_exists: bool + :param skip_if_exists: + Before downloading each blob, check if the file for the filename exists; + if it does, skip that blob. + + :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded. + + :rtype: list + :returns: A list of results corresponding to, in order, each item in the + input list. If an exception was received, it will be the result + for that operation. Otherwise, the return value from the successful + download method is used (which will be None). + """ + + if download_kwargs is None: + download_kwargs = {} + + download_kwargs["command"] = "tm.download_many" + + pool_class, needs_pickling = _get_pool_class_and_requirements(worker_type) + + with pool_class(max_workers=max_workers) as executor: + futures = [] + for blob, path_or_file in blob_file_pairs: + # File objects are only supported by the THREAD worker because they can't + # be pickled. + if needs_pickling and not isinstance(path_or_file, str): + raise ValueError( + "Passing in a file object is only supported by the THREAD worker type. Please either select THREAD workers, or pass in filenames only." + ) + + if skip_if_exists and isinstance(path_or_file, str): + if os.path.isfile(path_or_file): + continue + + futures.append( + executor.submit( + _call_method_on_maybe_pickled_blob, + _pickle_client(blob) if needs_pickling else blob, + ( + "_handle_filename_and_download" + if isinstance(path_or_file, str) + else "_prep_and_do_download" + ), + path_or_file, + **download_kwargs, + ) + ) + concurrent.futures.wait( + futures, timeout=deadline, return_when=concurrent.futures.ALL_COMPLETED + ) + + results = [] + for future in futures: + # If raise_exception is False, don't call future.result() + if not raise_exception: + exp = future.exception() + if exp: + results.append(exp) + continue + # Get the real result. If there was an exception, this will raise it. + results.append(future.result()) + return results + + +@_deprecate_threads_param +def upload_many_from_filenames( + bucket, + filenames, + source_directory="", + blob_name_prefix="", + skip_if_exists=False, + blob_constructor_kwargs=None, + upload_kwargs=None, + threads=None, + deadline=None, + raise_exception=False, + worker_type=PROCESS, + max_workers=DEFAULT_MAX_WORKERS, + *, + additional_blob_attributes=None, +): + """Upload many files concurrently by their filenames. + + The destination blobs are automatically created, with blob names based on + the source filenames and the blob_name_prefix. + + For example, if the `filenames` include "images/icon.jpg", + `source_directory` is "/home/myuser/", and `blob_name_prefix` is "myfiles/", + then the file at "/home/myuser/images/icon.jpg" will be uploaded to a blob + named "myfiles/images/icon.jpg". + + :type bucket: :class:`google.cloud.storage.bucket.Bucket` + :param bucket: + The bucket which will contain the uploaded blobs. + + :type filenames: list(str) + :param filenames: + A list of filenames to be uploaded. This may include part of the path. + The file will be accessed at the full path of `source_directory` + + `filename`. + + :type source_directory: str + :param source_directory: + A string that will be prepended (with `os.path.join()`) to each filename + in the input list, in order to find the source file for each blob. + Unlike the filename itself, the source_directory does not affect the + name of the uploaded blob. + + For instance, if the source_directory is "/tmp/img/" and a filename is + "0001.jpg", with an empty blob_name_prefix, then the file uploaded will + be "/tmp/img/0001.jpg" and the destination blob will be "0001.jpg". + + This parameter can be an empty string. + + Note that this parameter allows directory traversal (e.g. "/", "../") + and is not intended for unsanitized end user input. + + :type blob_name_prefix: str + :param blob_name_prefix: + A string that will be prepended to each filename in the input list, in + order to determine the name of the destination blob. Unlike the filename + itself, the prefix string does not affect the location the library will + look for the source data on the local filesystem. + + For instance, if the source_directory is "/tmp/img/", the + blob_name_prefix is "myuser/mystuff-" and a filename is "0001.jpg" then + the file uploaded will be "/tmp/img/0001.jpg" and the destination blob + will be "myuser/mystuff-0001.jpg". + + The blob_name_prefix can be blank (an empty string). + + :type skip_if_exists: bool + :param skip_if_exists: + If True, blobs that already have a live version will not be overwritten. + This is accomplished by setting `if_generation_match = 0` on uploads. + Uploads so skipped will result in a 412 Precondition Failed response + code, which will be included in the return value, but not raised + as an exception regardless of the value of raise_exception. + + :type blob_constructor_kwargs: dict + :param blob_constructor_kwargs: + A dictionary of keyword arguments to pass to the blob constructor. Refer + to the documentation for `blob.Blob()` for more information. The dict is + directly passed into the constructor and is not validated by this + function. `name` and `bucket` keyword arguments are reserved by this + function and will result in an error if passed in here. + + :type upload_kwargs: dict + :param upload_kwargs: + A dictionary of keyword arguments to pass to the upload method. Refer + to the documentation for `blob.upload_from_file()` or + `blob.upload_from_filename()` for more information. The dict is directly + passed into the upload methods and is not validated by this function. + + :type threads: int + :param threads: + ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the + number specified. If `worker_type` or `max_workers` are set explicitly, + this parameter should be set to None. Please use `worker_type` and + `max_workers` instead of this parameter. + + :type deadline: int + :param deadline: + The number of seconds to wait for all threads to resolve. If the + deadline is reached, all threads will be terminated regardless of their + progress and `concurrent.futures.TimeoutError` will be raised. This can + be left as the default of `None` (no deadline) for most use cases. + + :type raise_exception: bool + :param raise_exception: + If True, instead of adding exceptions to the list of return values, + instead they will be raised. Note that encountering an exception on one + operation will not prevent other operations from starting. Exceptions + are only processed and potentially raised after all operations are + complete in success or failure. + + If skip_if_exists is True, 412 Precondition Failed responses are + considered part of normal operation and are not raised as an exception. + + :type worker_type: str + :param worker_type: + The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS` + or `google.cloud.storage.transfer_manager.THREAD`. + + Although the exact performance impact depends on the use case, in most + situations the PROCESS worker type will use more system resources (both + memory and CPU) and result in faster operations than THREAD workers. + + Because the subprocesses of the PROCESS worker type can't access memory + from the main process, Client objects have to be serialized and then + recreated in each subprocess. The serialization of the Client object + for use in subprocesses is an approximation and may not capture every + detail of the Client object, especially if the Client was modified after + its initial creation or if `Client._http` was modified in any way. + + THREAD worker types are observed to be relatively efficient for + operations with many small files, but not for operations with large + files. PROCESS workers are recommended for large file operations. + + :type max_workers: int + :param max_workers: + The maximum number of workers to create to handle the workload. + + With PROCESS workers, a larger number of workers will consume more + system resources (memory and CPU) at once. + + How many workers is optimal depends heavily on the specific use case, + and the default is a conservative number that should work okay in most + cases without consuming excessive resources. + + :type additional_blob_attributes: dict + :param additional_blob_attributes: + A dictionary of blob attribute names and values. This allows the + configuration of blobs beyond what is possible with + blob_constructor_kwargs. For instance, {"cache_control": "no-cache"} + would set the cache_control attribute of each blob to "no-cache". + + As with blob_constructor_kwargs, this affects the creation of every + blob identically. To fine-tune each blob individually, use `upload_many` + and create the blobs as desired before passing them in. + + :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded. + + :rtype: list + :returns: A list of results corresponding to, in order, each item in the + input list. If an exception was received, it will be the result + for that operation. Otherwise, the return value from the successful + upload method is used (which will be None). + """ + if blob_constructor_kwargs is None: + blob_constructor_kwargs = {} + if additional_blob_attributes is None: + additional_blob_attributes = {} + + file_blob_pairs = [] + + for filename in filenames: + path = os.path.join(source_directory, filename) + blob_name = blob_name_prefix + filename + blob = bucket.blob(blob_name, **blob_constructor_kwargs) + for prop, value in additional_blob_attributes.items(): + setattr(blob, prop, value) + file_blob_pairs.append((path, blob)) + + return upload_many( + file_blob_pairs, + skip_if_exists=skip_if_exists, + upload_kwargs=upload_kwargs, + deadline=deadline, + raise_exception=raise_exception, + worker_type=worker_type, + max_workers=max_workers, + ) + + +@_deprecate_threads_param +def download_many_to_path( + bucket, + blob_names, + destination_directory="", + blob_name_prefix="", + download_kwargs=None, + threads=None, + deadline=None, + create_directories=True, + raise_exception=False, + worker_type=PROCESS, + max_workers=DEFAULT_MAX_WORKERS, + *, + skip_if_exists=False, +): + """Download many files concurrently by their blob names. + + The destination files are automatically created, with paths based on the + source `blob_names` and the `destination_directory`. + + + The destination files are not automatically deleted if their downloads fail, + so please check the return value of this function for any exceptions, or + enable `raise_exception=True`, and process the files accordingly. + + For example, if the `blob_names` include "icon.jpg", `destination_directory` + is "/home/myuser/", and `blob_name_prefix` is "images/", then the blob named + "images/icon.jpg" will be downloaded to a file named + "/home/myuser/icon.jpg". + + + Note1: if the path after combining `blob_name` and `destination_directory` + resolves outside `destination_directory` a warning will be issued and the + that particular blob will NOT be downloaded. This may happen in scenarios + where `blob_name` contains "../" + + For example, + consider `destination_directory` is "downloads/gcs_blobs" and + `blob_name` is '../hello.blob'. This blob will not be downloaded + because the final resolved path would be "downloads/hello.blob" + + + To give further examples, the following blobs will not be downloaded because + it "escapes" the "destination_directory" + + "../../local/target", # skips download + "../escape.txt", # skips download + "go/four/levels/deep/../../../../../somefile1", # skips download + "go/four/levels/deep/../some_dir/../../../../../invalid/path1" # skips download + + however the following blobs will be downloaded because the final resolved + destination_directory is still child of given destination_directory + + "data/../sibling.txt", + "dir/./file.txt", + "go/four/levels/deep/../somefile2", + "go/four/levels/deep/../some_dir/valid/path1", + "go/four/levels/deep/../some_dir/../../../../valid/path2", + + It is adviced to use other APIs such as `transfer_manager.download_many` or + `Blob.download_to_filename` or `Blob.download_to_file` to download such blobs. + + + Note2: + The resolved download_directory will always be relative to user provided + `destination_directory`. For example, + + a `blob_name` "/etc/passwd" will be downloaded into + "destination_directory/etc/passwd" instead of "/etc/passwd" + Similarly, + "/tmp/my_fav_blob" downloads to "destination_directory/tmp/my_fav_blob" + + + + :type bucket: :class:`google.cloud.storage.bucket.Bucket` + :param bucket: + The bucket which contains the blobs to be downloaded + + :type blob_names: list(str) + :param blob_names: + A list of blobs to be downloaded. The blob name in this string will be + used to determine the destination file path as well. + + The full name to the blob must be blob_name_prefix + blob_name. The + blob_name is separate from the blob_name_prefix because the blob_name + will also determine the name of the destination blob. Any shared part of + the blob names that need not be part of the destination path should be + included in the blob_name_prefix. + + :type destination_directory: str + :param destination_directory: + A string that will be prepended to each blob_name in the input list, in + order to determine the destination path for that blob. + + For instance, if the destination_directory string is "/tmp/img" and a + blob_name is "0001.jpg", with an empty blob_name_prefix, then the source + blob "0001.jpg" will be downloaded to destination "/tmp/img/0001.jpg" . + + This parameter can be an empty string. + + Note directory traversal may be possible as long as the final + (e.g. "/", "../") resolved path is inside "destination_directory". + See examples above. + + :type blob_name_prefix: str + :param blob_name_prefix: + A string that will be prepended to each blob_name in the input list, in + order to determine the name of the source blob. Unlike the blob_name + itself, the prefix string does not affect the destination path on the + local filesystem. For instance, if the destination_directory is + "/tmp/img/", the blob_name_prefix is "myuser/mystuff-" and a blob_name + is "0001.jpg" then the source blob "myuser/mystuff-0001.jpg" will be + downloaded to "/tmp/img/0001.jpg". The blob_name_prefix can be blank + (an empty string). + + :type download_kwargs: dict + :param download_kwargs: + A dictionary of keyword arguments to pass to the download method. Refer + to the documentation for `blob.download_to_file()` or + `blob.download_to_filename()` for more information. The dict is directly + passed into the download methods and is not validated by this function. + + :type threads: int + :param threads: + ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the + number specified. If `worker_type` or `max_workers` are set explicitly, + this parameter should be set to None. Please use `worker_type` and + `max_workers` instead of this parameter. + + :type deadline: int + :param deadline: + The number of seconds to wait for all threads to resolve. If the + deadline is reached, all threads will be terminated regardless of their + progress and `concurrent.futures.TimeoutError` will be raised. This can + be left as the default of `None` (no deadline) for most use cases. + + :type create_directories: bool + :param create_directories: + If True, recursively create any directories that do not exist. For + instance, if downloading object "images/img001.png", create the + directory "images" before downloading. + + :type raise_exception: bool + :param raise_exception: + If True, instead of adding exceptions to the list of return values, + instead they will be raised. Note that encountering an exception on one + operation will not prevent other operations from starting. Exceptions + are only processed and potentially raised after all operations are + complete in success or failure. If skip_if_exists is True, 412 + Precondition Failed responses are considered part of normal operation + and are not raised as an exception. + + :type worker_type: str + :param worker_type: + The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS` + or `google.cloud.storage.transfer_manager.THREAD`. + + Although the exact performance impact depends on the use case, in most + situations the PROCESS worker type will use more system resources (both + memory and CPU) and result in faster operations than THREAD workers. + + Because the subprocesses of the PROCESS worker type can't access memory + from the main process, Client objects have to be serialized and then + recreated in each subprocess. The serialization of the Client object + for use in subprocesses is an approximation and may not capture every + detail of the Client object, especially if the Client was modified after + its initial creation or if `Client._http` was modified in any way. + + THREAD worker types are observed to be relatively efficient for + operations with many small files, but not for operations with large + files. PROCESS workers are recommended for large file operations. + + :type max_workers: int + :param max_workers: + The maximum number of workers to create to handle the workload. + + With PROCESS workers, a larger number of workers will consume more + system resources (memory and CPU) at once. + + How many workers is optimal depends heavily on the specific use case, + and the default is a conservative number that should work okay in most + cases without consuming excessive resources. + + :type skip_if_exists: bool + :param skip_if_exists: + Before downloading each blob, check if the file for the filename exists; + if it does, skip that blob. This only works for filenames. + + :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded. + + :rtype: List[None|Exception|UserWarning] + :returns: A list of results corresponding to, in order, each item in the + input list. If an exception was received or a download was skipped + (e.g., due to existing file or path traversal), it will be the result + for that operation (as an Exception or UserWarning, respectively). + Otherwise, the result will be None for a successful download. + """ + results = [None] * len(blob_names) + blob_file_pairs = [] + indices_to_process = [] + + for i, blob_name in enumerate(blob_names): + full_blob_name = blob_name_prefix + blob_name + try: + resolved_path = _resolve_path(destination_directory, blob_name) + except InvalidPathError as e: + msg = f"The blob {blob_name} will **NOT** be downloaded. {e}" + warnings.warn(msg) + results[i] = UserWarning(msg) + continue + if not resolved_path.parent.is_relative_to( + Path(destination_directory).resolve() + ): + msg = ( + f"The blob {blob_name} will **NOT** be downloaded. " + f"The resolved destination_directory - {resolved_path.parent} - is either invalid or " + f"escapes user provided {Path(destination_directory).resolve()} . Please download this file separately using `download_to_filename`" + ) + warnings.warn(msg) + results[i] = UserWarning(msg) + continue + + resolved_path = str(resolved_path) + if skip_if_exists and os.path.isfile(resolved_path): + msg = f"The blob {blob_name} is skipped because destination file already exists" + results[i] = UserWarning(msg) + continue + + if create_directories: + directory, _ = os.path.split(resolved_path) + os.makedirs(directory, exist_ok=True) + blob_file_pairs.append((bucket.blob(full_blob_name), resolved_path)) + indices_to_process.append(i) + + many_results = download_many( + blob_file_pairs, + download_kwargs=download_kwargs, + deadline=deadline, + raise_exception=raise_exception, + worker_type=worker_type, + max_workers=max_workers, + skip_if_exists=False, # skip_if_exists is handled in the loop above + ) + + for meta_index, result in zip(indices_to_process, many_results): + results[meta_index] = result + + return results + + +def download_chunks_concurrently( + blob, + filename, + chunk_size=TM_DEFAULT_CHUNK_SIZE, + download_kwargs=None, + deadline=None, + worker_type=PROCESS, + max_workers=DEFAULT_MAX_WORKERS, + *, + crc32c_checksum=True, +): + """Download a single file in chunks, concurrently. + + In some environments, using this feature with mutiple processes will result + in faster downloads of large files. + + Using this feature with multiple threads is unlikely to improve download + performance under normal circumstances due to Python interpreter threading + behavior. The default is therefore to use processes instead of threads. + + :type blob: :class:`google.cloud.storage.blob.Blob` + :param blob: + The blob to be downloaded. + + :type filename: str + :param filename: + The destination filename or path. + + :type chunk_size: int + :param chunk_size: + The size in bytes of each chunk to send. The optimal chunk size for + maximum throughput may vary depending on the exact network environment + and size of the blob. + + :type download_kwargs: dict + :param download_kwargs: + A dictionary of keyword arguments to pass to the download method. Refer + to the documentation for `blob.download_to_file()` or + `blob.download_to_filename()` for more information. The dict is directly + passed into the download methods and is not validated by this function. + + Keyword arguments "start" and "end" which are not supported and will + cause a ValueError if present. The key "checksum" is also not supported + in `download_kwargs`, but see the argument `crc32c_checksum` (which does + not go in `download_kwargs`) below. + + :type deadline: int + :param deadline: + The number of seconds to wait for all threads to resolve. If the + deadline is reached, all threads will be terminated regardless of their + progress and `concurrent.futures.TimeoutError` will be raised. This can + be left as the default of `None` (no deadline) for most use cases. + + :type worker_type: str + :param worker_type: + The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS` + or `google.cloud.storage.transfer_manager.THREAD`. + + Although the exact performance impact depends on the use case, in most + situations the PROCESS worker type will use more system resources (both + memory and CPU) and result in faster operations than THREAD workers. + + Because the subprocesses of the PROCESS worker type can't access memory + from the main process, Client objects have to be serialized and then + recreated in each subprocess. The serialization of the Client object + for use in subprocesses is an approximation and may not capture every + detail of the Client object, especially if the Client was modified after + its initial creation or if `Client._http` was modified in any way. + + THREAD worker types are observed to be relatively efficient for + operations with many small files, but not for operations with large + files. PROCESS workers are recommended for large file operations. + + :type max_workers: int + :param max_workers: + The maximum number of workers to create to handle the workload. + + With PROCESS workers, a larger number of workers will consume more + system resources (memory and CPU) at once. + + How many workers is optimal depends heavily on the specific use case, + and the default is a conservative number that should work okay in most + cases without consuming excessive resources. + + :type crc32c_checksum: bool + :param crc32c_checksum: + Whether to compute a checksum for the resulting object, using the crc32c + algorithm. As the checksums for each chunk must be combined using a + feature of crc32c that is not available for md5, md5 is not supported. + + :raises: + :exc:`concurrent.futures.TimeoutError` + if deadline is exceeded. + :exc:`google.cloud.storage._media.common.DataCorruption` + if the download's checksum doesn't agree with server-computed + checksum. The `google.cloud.storage._media` exception is used here for + consistency with other download methods despite the exception + originating elsewhere. + """ + client = blob.client + + if download_kwargs is None: + download_kwargs = {} + if "start" in download_kwargs or "end" in download_kwargs: + raise ValueError( + "Download arguments 'start' and 'end' are not supported by download_chunks_concurrently." + ) + if "checksum" in download_kwargs: + raise ValueError( + "'checksum' is in download_kwargs, but is not supported because sliced downloads have a different checksum mechanism from regular downloads. Use the 'crc32c_checksum' argument on download_chunks_concurrently instead." + ) + + download_kwargs = download_kwargs.copy() + download_kwargs["checksum"] = None + download_kwargs["command"] = "tm.download_sharded" + + # We must know the size and the generation of the blob. + if not blob.size or not blob.generation: + blob.reload() + + pool_class, needs_pickling = _get_pool_class_and_requirements(worker_type) + # Pickle the blob ahead of time (just once, not once per chunk) if needed. + maybe_pickled_blob = _pickle_client(blob) if needs_pickling else blob + + futures = [] + + # Create and/or truncate the destination file to prepare for sparse writing. + with open(filename, "wb") as _: + pass + + with pool_class(max_workers=max_workers) as executor: + cursor = 0 + end = blob.size + while cursor < end: + start = cursor + cursor = min(cursor + chunk_size, end) + futures.append( + executor.submit( + _download_and_write_chunk_in_place, + maybe_pickled_blob, + filename, + start=start, + end=cursor - 1, + download_kwargs=download_kwargs, + crc32c_checksum=crc32c_checksum, + ) + ) + + concurrent.futures.wait( + futures, timeout=deadline, return_when=concurrent.futures.ALL_COMPLETED + ) + + # Raise any exceptions; combine checksums. + results = [] + for future in futures: + results.append(future.result()) + + if crc32c_checksum and results: + crc_digest = _digest_ordered_checksum_and_size_pairs(results) + actual_checksum = base64.b64encode(crc_digest).decode("utf-8") + expected_checksum = blob.crc32c + if actual_checksum != expected_checksum: + # For consistency with other download methods we will use + # "google.cloud.storage._media.common.DataCorruption" despite the error + # not originating inside google.cloud.storage._media. + download_url = blob._get_download_url( + client, + if_generation_match=download_kwargs.get("if_generation_match"), + if_generation_not_match=download_kwargs.get("if_generation_not_match"), + if_metageneration_match=download_kwargs.get("if_metageneration_match"), + if_metageneration_not_match=download_kwargs.get( + "if_metageneration_not_match" + ), + ) + raise DataCorruption( + None, + DOWNLOAD_CRC32C_MISMATCH_TEMPLATE.format( + download_url, expected_checksum, actual_checksum + ), + ) + return None + + +def upload_chunks_concurrently( + filename, + blob, + content_type=None, + chunk_size=TM_DEFAULT_CHUNK_SIZE, + deadline=None, + worker_type=PROCESS, + max_workers=DEFAULT_MAX_WORKERS, + *, + checksum="auto", + timeout=_DEFAULT_TIMEOUT, + retry=DEFAULT_RETRY, +): + """Upload a single file in chunks, concurrently. + + This function uses the XML MPU API to initialize an upload and upload a + file in chunks, concurrently with a worker pool. + + The XML MPU API is significantly different from other uploads; please review + the documentation at `https://cloud.google.com/storage/docs/multipart-uploads` + before using this feature. + + The library will attempt to cancel uploads that fail due to an exception. + If the upload fails in a way that precludes cancellation, such as a + hardware failure, process termination, or power outage, then the incomplete + upload may persist indefinitely. To mitigate this, set the + `AbortIncompleteMultipartUpload` with a nonzero `Age` in bucket lifecycle + rules, or refer to the XML API documentation linked above to learn more + about how to list and delete individual downloads. + + Using this feature with multiple threads is unlikely to improve upload + performance under normal circumstances due to Python interpreter threading + behavior. The default is therefore to use processes instead of threads. + + ACL information cannot be sent with this function and should be set + separately with :class:`ObjectACL` methods. + + :type filename: str + :param filename: + The path to the file to upload. File-like objects are not supported. + + :type blob: :class:`google.cloud.storage.blob.Blob` + :param blob: + The blob to which to upload. + + :type content_type: str + :param content_type: (Optional) Type of content being uploaded. + + :type chunk_size: int + :param chunk_size: + The size in bytes of each chunk to send. The optimal chunk size for + maximum throughput may vary depending on the exact network environment + and size of the blob. The remote API has restrictions on the minimum + and maximum size allowable, see: `https://cloud.google.com/storage/quotas#requests` + + :type deadline: int + :param deadline: + The number of seconds to wait for all threads to resolve. If the + deadline is reached, all threads will be terminated regardless of their + progress and `concurrent.futures.TimeoutError` will be raised. This can + be left as the default of `None` (no deadline) for most use cases. + + :type worker_type: str + :param worker_type: + The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS` + or `google.cloud.storage.transfer_manager.THREAD`. + + Although the exact performance impact depends on the use case, in most + situations the PROCESS worker type will use more system resources (both + memory and CPU) and result in faster operations than THREAD workers. + + Because the subprocesses of the PROCESS worker type can't access memory + from the main process, Client objects have to be serialized and then + recreated in each subprocess. The serialization of the Client object + for use in subprocesses is an approximation and may not capture every + detail of the Client object, especially if the Client was modified after + its initial creation or if `Client._http` was modified in any way. + + THREAD worker types are observed to be relatively efficient for + operations with many small files, but not for operations with large + files. PROCESS workers are recommended for large file operations. + + :type max_workers: int + :param max_workers: + The maximum number of workers to create to handle the workload. + + With PROCESS workers, a larger number of workers will consume more + system resources (memory and CPU) at once. + + How many workers is optimal depends heavily on the specific use case, + and the default is a conservative number that should work okay in most + cases without consuming excessive resources. + + :type checksum: str + :param checksum: + (Optional) The checksum scheme to use: either "md5", "crc32c", "auto" + or None. The default is "auto", which will try to detect if the C + extension for crc32c is installed and fall back to md5 otherwise. + Each individual part is checksummed. At present, the selected + checksum rule is only applied to parts and a separate checksum of the + entire resulting blob is not computed. Please compute and compare the + checksum of the file to the resulting blob separately if needed, using + the "crc32c" algorithm as per the XML MPU documentation. + + :type timeout: float or tuple + :param timeout: + (Optional) The amount of time, in seconds, to wait + for the server response. See: :ref:`configuring_timeouts` + + :type retry: google.api_core.retry.Retry + :param retry: (Optional) How to retry the RPC. A None value will disable + retries. A `google.api_core.retry.Retry` value will enable retries, + and the object will configure backoff and timeout options. Custom + predicates (customizable error codes) are not supported for media + operations such as this one. + + This function does not accept `ConditionalRetryPolicy` values because + preconditions are not supported by the underlying API call. + + See the retry.py source code and docstrings in this package + (`google.cloud.storage.retry`) for information on retry types and how + to configure them. + + :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded. + """ + + bucket = blob.bucket + client = blob.client + transport = blob._get_transport(client) + + hostname = _get_host_name(client._connection) + url = "{hostname}/{bucket}/{blob}".format( + hostname=hostname, bucket=bucket.name, blob=_quote(blob.name) + ) + + base_headers, object_metadata, content_type = blob._get_upload_arguments( + client, content_type, filename=filename, command="tm.upload_sharded" + ) + headers = {**base_headers, **_headers_from_metadata(object_metadata)} + + if blob.user_project is not None: + headers["x-goog-user-project"] = blob.user_project + + # When a Customer Managed Encryption Key is used to encrypt Cloud Storage object + # at rest, object resource metadata will store the version of the Key Management + # Service cryptographic material. If a Blob instance with KMS Key metadata set is + # used to upload a new version of the object then the existing kmsKeyName version + # value can't be used in the upload request and the client instead ignores it. + if blob.kms_key_name is not None and "cryptoKeyVersions" not in blob.kms_key_name: + headers["x-goog-encryption-kms-key-name"] = blob.kms_key_name + + container = XMLMPUContainer(url, filename, headers=headers, retry=retry) + + container.initiate(transport=transport, content_type=content_type) + upload_id = container.upload_id + + size = os.path.getsize(filename) + num_of_parts = -(size // -chunk_size) # Ceiling division + + pool_class, needs_pickling = _get_pool_class_and_requirements(worker_type) + # Pickle the blob ahead of time (just once, not once per chunk) if needed. + maybe_pickled_client = _pickle_client(client) if needs_pickling else client + + futures = [] + + with pool_class(max_workers=max_workers) as executor: + for part_number in range(1, num_of_parts + 1): + start = (part_number - 1) * chunk_size + end = min(part_number * chunk_size, size) + + futures.append( + executor.submit( + _upload_part, + maybe_pickled_client, + url, + upload_id, + filename, + start=start, + end=end, + part_number=part_number, + checksum=checksum, + headers=headers.copy(), + retry=retry, + ) + ) + + concurrent.futures.wait( + futures, timeout=deadline, return_when=concurrent.futures.ALL_COMPLETED + ) + + try: + # Harvest results and raise exceptions. + for future in futures: + part_number, etag = future.result() + container.register_part(part_number, etag) + + container.finalize(blob._get_transport(client)) + except Exception: + container.cancel(blob._get_transport(client)) + raise + + +def _upload_part( + maybe_pickled_client, + url, + upload_id, + filename, + start, + end, + part_number, + checksum, + headers, + retry, +): + """Helper function that runs inside a thread or subprocess to upload a part. + + `maybe_pickled_client` is either a Client (for threads) or a specially + pickled Client (for processes) because the default pickling mangles Client + objects.""" + + if isinstance(maybe_pickled_client, Client): + client = maybe_pickled_client + else: + client = pickle.loads(maybe_pickled_client) + part = XMLMPUPart( + url, + upload_id, + filename, + start=start, + end=end, + part_number=part_number, + checksum=checksum, + headers=headers, + retry=retry, + ) + part.upload(client._http) + return (part_number, part.etag) + + +def _headers_from_metadata(metadata): + """Helper function to translate object metadata into a header dictionary.""" + + headers = {} + # Handle standard writable metadata + for key, value in metadata.items(): + if key in METADATA_HEADER_TRANSLATION: + headers[METADATA_HEADER_TRANSLATION[key]] = value + # Handle custom metadata + if "metadata" in metadata: + for key, value in metadata["metadata"].items(): + headers["x-goog-meta-" + key] = value + return headers + + +def _download_and_write_chunk_in_place( + maybe_pickled_blob, filename, start, end, download_kwargs, crc32c_checksum +): + """Helper function that runs inside a thread or subprocess. + + `maybe_pickled_blob` is either a Blob (for threads) or a specially pickled + Blob (for processes) because the default pickling mangles Client objects + which are attached to Blobs. + + Returns a crc if configured (or None) and the size written. + """ + + if isinstance(maybe_pickled_blob, Blob): + blob = maybe_pickled_blob + else: + blob = pickle.loads(maybe_pickled_blob) + + with _ChecksummingSparseFileWrapper(filename, start, crc32c_checksum) as f: + blob._prep_and_do_download(f, start=start, end=end, **download_kwargs) + return (f.crc, (end - start) + 1) + + +class _ChecksummingSparseFileWrapper: + """A file wrapper that writes to a sparse file and optionally checksums. + + This wrapper only implements write() and does not inherit from `io` module + base classes. + """ + + def __init__(self, filename, start_position, crc32c_enabled): + # Open in mixed read/write mode to avoid truncating or appending + self.f = open(filename, "rb+") + self.f.seek(start_position) + self._crc = None + self._crc32c_enabled = crc32c_enabled + + def write(self, chunk): + if self._crc32c_enabled: + if self._crc is None: + self._crc = google_crc32c.value(chunk) + else: + self._crc = google_crc32c.extend(self._crc, chunk) + self.f.write(chunk) + + @property + def crc(self): + return self._crc + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, tb): + self.f.close() + + +def _call_method_on_maybe_pickled_blob( + maybe_pickled_blob, method_name, *args, **kwargs +): + """Helper function that runs inside a thread or subprocess. + + `maybe_pickled_blob` is either a Blob (for threads) or a specially pickled + Blob (for processes) because the default pickling mangles Client objects + which are attached to Blobs.""" + + if isinstance(maybe_pickled_blob, Blob): + blob = maybe_pickled_blob + else: + blob = pickle.loads(maybe_pickled_blob) + return getattr(blob, method_name)(*args, **kwargs) + + +def _reduce_client(cl): + """Replicate a Client by constructing a new one with the same params. + + LazyClient performs transparent caching for when the same client is needed + on the same process multiple times.""" + + client_object_id = id(cl) + project = cl.project + credentials = cl._credentials + _http = None # Can't carry this over + client_info = cl._initial_client_info + client_options = cl._initial_client_options + extra_headers = cl._extra_headers + + return _LazyClient, ( + client_object_id, + project, + credentials, + _http, + client_info, + client_options, + extra_headers, + ) + + +def _pickle_client(obj): + """Pickle a Client or an object that owns a Client (like a Blob)""" + + # We need a custom pickler to process Client objects, which are attached to + # Buckets (and therefore to Blobs in turn). Unfortunately, the Python + # multiprocessing library doesn't seem to have a good way to use a custom + # pickler, and using copyreg will mutate global state and affect code + # outside of the client library. Instead, we'll pre-pickle the object and + # pass the bytestring in. + f = io.BytesIO() + p = pickle.Pickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[Client] = _reduce_client + p.dump(obj) + return f.getvalue() + + +def _get_pool_class_and_requirements(worker_type): + """Returns the pool class, and whether the pool requires pickled Blobs.""" + + if worker_type == PROCESS: + # Use processes. Pickle blobs with custom logic to handle the client. + return (concurrent.futures.ProcessPoolExecutor, True) + elif worker_type == THREAD: + # Use threads. Pass blobs through unpickled. + return (concurrent.futures.ThreadPoolExecutor, False) + else: + raise ValueError( + "The worker_type must be google.cloud.storage.transfer_manager.PROCESS or google.cloud.storage.transfer_manager.THREAD" + ) + + +def _digest_ordered_checksum_and_size_pairs(checksum_and_size_pairs): + base_crc = None + zeroes = bytes(MAX_CRC32C_ZERO_ARRAY_SIZE) + for part_crc, size in checksum_and_size_pairs: + if not base_crc: + base_crc = part_crc + else: + base_crc ^= 0xFFFFFFFF # precondition + + # Zero pad base_crc32c. To conserve memory, do so with only + # MAX_CRC32C_ZERO_ARRAY_SIZE at a time. Reuse the zeroes array where + # possible. + padded = 0 + while padded < size: + desired_zeroes_size = min((size - padded), MAX_CRC32C_ZERO_ARRAY_SIZE) + base_crc = google_crc32c.extend(base_crc, zeroes[:desired_zeroes_size]) + padded += desired_zeroes_size + + base_crc ^= 0xFFFFFFFF # postcondition + base_crc ^= part_crc + crc_digest = struct.pack( + ">L", base_crc + ) # https://cloud.google.com/storage/docs/json_api/v1/objects#crc32c + return crc_digest + + +class _LazyClient: + """An object that will transform into either a cached or a new Client""" + + def __new__(cls, id, *args, **kwargs): + cached_client = _cached_clients.get(id) + if cached_client: + return cached_client + else: + cached_client = Client(*args, **kwargs) + _cached_clients[id] = cached_client + return cached_client diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/version.py new file mode 100644 index 0000000000000000000000000000000000000000..8afb5b22c7a9517c50658e3cb1b5be4015103cfc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/version.py @@ -0,0 +1,15 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "3.10.1" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..518488969c6856a0ad29119bdf42b0a50ed201d4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/__init__.py @@ -0,0 +1,109 @@ +# -*- 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.storage_control import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.storage_control_v2.services.storage_control.async_client import ( + StorageControlAsyncClient, +) +from google.cloud.storage_control_v2.services.storage_control.client import ( + StorageControlClient, +) +from google.cloud.storage_control_v2.types.storage_control import ( + AnywhereCache, + CommonLongRunningOperationMetadata, + CreateAnywhereCacheMetadata, + CreateAnywhereCacheRequest, + CreateFolderRequest, + CreateManagedFolderRequest, + DeleteFolderRecursiveMetadata, + DeleteFolderRecursiveRequest, + DeleteFolderRequest, + DeleteManagedFolderRequest, + DisableAnywhereCacheRequest, + Folder, + GetAnywhereCacheRequest, + GetFolderIntelligenceConfigRequest, + GetFolderRequest, + GetManagedFolderRequest, + GetOrganizationIntelligenceConfigRequest, + GetProjectIntelligenceConfigRequest, + GetStorageLayoutRequest, + IntelligenceConfig, + ListAnywhereCachesRequest, + ListAnywhereCachesResponse, + ListFoldersRequest, + ListFoldersResponse, + ListManagedFoldersRequest, + ListManagedFoldersResponse, + ManagedFolder, + PauseAnywhereCacheRequest, + PendingRenameInfo, + RenameFolderMetadata, + RenameFolderRequest, + ResumeAnywhereCacheRequest, + StorageLayout, + UpdateAnywhereCacheMetadata, + UpdateAnywhereCacheRequest, + UpdateFolderIntelligenceConfigRequest, + UpdateOrganizationIntelligenceConfigRequest, + UpdateProjectIntelligenceConfigRequest, +) + +__all__ = ( + "StorageControlClient", + "StorageControlAsyncClient", + "AnywhereCache", + "CommonLongRunningOperationMetadata", + "CreateAnywhereCacheMetadata", + "CreateAnywhereCacheRequest", + "CreateFolderRequest", + "CreateManagedFolderRequest", + "DeleteFolderRecursiveMetadata", + "DeleteFolderRecursiveRequest", + "DeleteFolderRequest", + "DeleteManagedFolderRequest", + "DisableAnywhereCacheRequest", + "Folder", + "GetAnywhereCacheRequest", + "GetFolderIntelligenceConfigRequest", + "GetFolderRequest", + "GetManagedFolderRequest", + "GetOrganizationIntelligenceConfigRequest", + "GetProjectIntelligenceConfigRequest", + "GetStorageLayoutRequest", + "IntelligenceConfig", + "ListAnywhereCachesRequest", + "ListAnywhereCachesResponse", + "ListFoldersRequest", + "ListFoldersResponse", + "ListManagedFoldersRequest", + "ListManagedFoldersResponse", + "ManagedFolder", + "PauseAnywhereCacheRequest", + "PendingRenameInfo", + "RenameFolderMetadata", + "RenameFolderRequest", + "ResumeAnywhereCacheRequest", + "StorageLayout", + "UpdateAnywhereCacheMetadata", + "UpdateAnywhereCacheRequest", + "UpdateFolderIntelligenceConfigRequest", + "UpdateOrganizationIntelligenceConfigRequest", + "UpdateProjectIntelligenceConfigRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..073a79a684792db0ba1d524867d5509069eae4de --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/gapic_version.py @@ -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__ = "1.11.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..cee2f5ac8a9245a0f3fc45366085bc9d4e227940 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-storage-control package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f6369f7d792a7db44fccb530093ab618765d6ab --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/__init__.py @@ -0,0 +1,209 @@ +# -*- 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 sys + +import google.api_core as api_core + +from google.cloud.storage_control_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.storage_control import StorageControlAsyncClient, StorageControlClient +from .types.storage_control import ( + AnywhereCache, + CommonLongRunningOperationMetadata, + CreateAnywhereCacheMetadata, + CreateAnywhereCacheRequest, + CreateFolderRequest, + CreateManagedFolderRequest, + DeleteFolderRecursiveMetadata, + DeleteFolderRecursiveRequest, + DeleteFolderRequest, + DeleteManagedFolderRequest, + DisableAnywhereCacheRequest, + Folder, + GetAnywhereCacheRequest, + GetFolderIntelligenceConfigRequest, + GetFolderRequest, + GetManagedFolderRequest, + GetOrganizationIntelligenceConfigRequest, + GetProjectIntelligenceConfigRequest, + GetStorageLayoutRequest, + IntelligenceConfig, + ListAnywhereCachesRequest, + ListAnywhereCachesResponse, + ListFoldersRequest, + ListFoldersResponse, + ListManagedFoldersRequest, + ListManagedFoldersResponse, + ManagedFolder, + PauseAnywhereCacheRequest, + PendingRenameInfo, + RenameFolderMetadata, + RenameFolderRequest, + ResumeAnywhereCacheRequest, + StorageLayout, + UpdateAnywhereCacheMetadata, + UpdateAnywhereCacheRequest, + UpdateFolderIntelligenceConfigRequest, + UpdateOrganizationIntelligenceConfigRequest, + UpdateProjectIntelligenceConfigRequest, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.storage_control_v2") # type: ignore + api_core.check_dependency_versions("google.cloud.storage_control_v2") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.storage_control_v2" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "StorageControlAsyncClient", + "AnywhereCache", + "CommonLongRunningOperationMetadata", + "CreateAnywhereCacheMetadata", + "CreateAnywhereCacheRequest", + "CreateFolderRequest", + "CreateManagedFolderRequest", + "DeleteFolderRecursiveMetadata", + "DeleteFolderRecursiveRequest", + "DeleteFolderRequest", + "DeleteManagedFolderRequest", + "DisableAnywhereCacheRequest", + "Folder", + "GetAnywhereCacheRequest", + "GetFolderIntelligenceConfigRequest", + "GetFolderRequest", + "GetManagedFolderRequest", + "GetOrganizationIntelligenceConfigRequest", + "GetProjectIntelligenceConfigRequest", + "GetStorageLayoutRequest", + "IntelligenceConfig", + "ListAnywhereCachesRequest", + "ListAnywhereCachesResponse", + "ListFoldersRequest", + "ListFoldersResponse", + "ListManagedFoldersRequest", + "ListManagedFoldersResponse", + "ManagedFolder", + "PauseAnywhereCacheRequest", + "PendingRenameInfo", + "RenameFolderMetadata", + "RenameFolderRequest", + "ResumeAnywhereCacheRequest", + "StorageControlClient", + "StorageLayout", + "UpdateAnywhereCacheMetadata", + "UpdateAnywhereCacheRequest", + "UpdateFolderIntelligenceConfigRequest", + "UpdateOrganizationIntelligenceConfigRequest", + "UpdateProjectIntelligenceConfigRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..765d658a2b1a83403a9e6c94d111b65314df1c05 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/gapic_metadata.json @@ -0,0 +1,433 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.storage_control_v2", + "protoPackage": "google.storage.control.v2", + "schema": "1.0", + "services": { + "StorageControl": { + "clients": { + "grpc": { + "libraryClient": "StorageControlClient", + "rpcs": { + "CreateAnywhereCache": { + "methods": [ + "create_anywhere_cache" + ] + }, + "CreateFolder": { + "methods": [ + "create_folder" + ] + }, + "CreateManagedFolder": { + "methods": [ + "create_managed_folder" + ] + }, + "DeleteFolder": { + "methods": [ + "delete_folder" + ] + }, + "DeleteFolderRecursive": { + "methods": [ + "delete_folder_recursive" + ] + }, + "DeleteManagedFolder": { + "methods": [ + "delete_managed_folder" + ] + }, + "DisableAnywhereCache": { + "methods": [ + "disable_anywhere_cache" + ] + }, + "GetAnywhereCache": { + "methods": [ + "get_anywhere_cache" + ] + }, + "GetFolder": { + "methods": [ + "get_folder" + ] + }, + "GetFolderIntelligenceConfig": { + "methods": [ + "get_folder_intelligence_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetManagedFolder": { + "methods": [ + "get_managed_folder" + ] + }, + "GetOrganizationIntelligenceConfig": { + "methods": [ + "get_organization_intelligence_config" + ] + }, + "GetProjectIntelligenceConfig": { + "methods": [ + "get_project_intelligence_config" + ] + }, + "GetStorageLayout": { + "methods": [ + "get_storage_layout" + ] + }, + "ListAnywhereCaches": { + "methods": [ + "list_anywhere_caches" + ] + }, + "ListFolders": { + "methods": [ + "list_folders" + ] + }, + "ListManagedFolders": { + "methods": [ + "list_managed_folders" + ] + }, + "PauseAnywhereCache": { + "methods": [ + "pause_anywhere_cache" + ] + }, + "RenameFolder": { + "methods": [ + "rename_folder" + ] + }, + "ResumeAnywhereCache": { + "methods": [ + "resume_anywhere_cache" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateAnywhereCache": { + "methods": [ + "update_anywhere_cache" + ] + }, + "UpdateFolderIntelligenceConfig": { + "methods": [ + "update_folder_intelligence_config" + ] + }, + "UpdateOrganizationIntelligenceConfig": { + "methods": [ + "update_organization_intelligence_config" + ] + }, + "UpdateProjectIntelligenceConfig": { + "methods": [ + "update_project_intelligence_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StorageControlAsyncClient", + "rpcs": { + "CreateAnywhereCache": { + "methods": [ + "create_anywhere_cache" + ] + }, + "CreateFolder": { + "methods": [ + "create_folder" + ] + }, + "CreateManagedFolder": { + "methods": [ + "create_managed_folder" + ] + }, + "DeleteFolder": { + "methods": [ + "delete_folder" + ] + }, + "DeleteFolderRecursive": { + "methods": [ + "delete_folder_recursive" + ] + }, + "DeleteManagedFolder": { + "methods": [ + "delete_managed_folder" + ] + }, + "DisableAnywhereCache": { + "methods": [ + "disable_anywhere_cache" + ] + }, + "GetAnywhereCache": { + "methods": [ + "get_anywhere_cache" + ] + }, + "GetFolder": { + "methods": [ + "get_folder" + ] + }, + "GetFolderIntelligenceConfig": { + "methods": [ + "get_folder_intelligence_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetManagedFolder": { + "methods": [ + "get_managed_folder" + ] + }, + "GetOrganizationIntelligenceConfig": { + "methods": [ + "get_organization_intelligence_config" + ] + }, + "GetProjectIntelligenceConfig": { + "methods": [ + "get_project_intelligence_config" + ] + }, + "GetStorageLayout": { + "methods": [ + "get_storage_layout" + ] + }, + "ListAnywhereCaches": { + "methods": [ + "list_anywhere_caches" + ] + }, + "ListFolders": { + "methods": [ + "list_folders" + ] + }, + "ListManagedFolders": { + "methods": [ + "list_managed_folders" + ] + }, + "PauseAnywhereCache": { + "methods": [ + "pause_anywhere_cache" + ] + }, + "RenameFolder": { + "methods": [ + "rename_folder" + ] + }, + "ResumeAnywhereCache": { + "methods": [ + "resume_anywhere_cache" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateAnywhereCache": { + "methods": [ + "update_anywhere_cache" + ] + }, + "UpdateFolderIntelligenceConfig": { + "methods": [ + "update_folder_intelligence_config" + ] + }, + "UpdateOrganizationIntelligenceConfig": { + "methods": [ + "update_organization_intelligence_config" + ] + }, + "UpdateProjectIntelligenceConfig": { + "methods": [ + "update_project_intelligence_config" + ] + } + } + }, + "rest": { + "libraryClient": "StorageControlClient", + "rpcs": { + "CreateAnywhereCache": { + "methods": [ + "create_anywhere_cache" + ] + }, + "CreateFolder": { + "methods": [ + "create_folder" + ] + }, + "CreateManagedFolder": { + "methods": [ + "create_managed_folder" + ] + }, + "DeleteFolder": { + "methods": [ + "delete_folder" + ] + }, + "DeleteFolderRecursive": { + "methods": [ + "delete_folder_recursive" + ] + }, + "DeleteManagedFolder": { + "methods": [ + "delete_managed_folder" + ] + }, + "DisableAnywhereCache": { + "methods": [ + "disable_anywhere_cache" + ] + }, + "GetAnywhereCache": { + "methods": [ + "get_anywhere_cache" + ] + }, + "GetFolder": { + "methods": [ + "get_folder" + ] + }, + "GetFolderIntelligenceConfig": { + "methods": [ + "get_folder_intelligence_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetManagedFolder": { + "methods": [ + "get_managed_folder" + ] + }, + "GetOrganizationIntelligenceConfig": { + "methods": [ + "get_organization_intelligence_config" + ] + }, + "GetProjectIntelligenceConfig": { + "methods": [ + "get_project_intelligence_config" + ] + }, + "GetStorageLayout": { + "methods": [ + "get_storage_layout" + ] + }, + "ListAnywhereCaches": { + "methods": [ + "list_anywhere_caches" + ] + }, + "ListFolders": { + "methods": [ + "list_folders" + ] + }, + "ListManagedFolders": { + "methods": [ + "list_managed_folders" + ] + }, + "PauseAnywhereCache": { + "methods": [ + "pause_anywhere_cache" + ] + }, + "RenameFolder": { + "methods": [ + "rename_folder" + ] + }, + "ResumeAnywhereCache": { + "methods": [ + "resume_anywhere_cache" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateAnywhereCache": { + "methods": [ + "update_anywhere_cache" + ] + }, + "UpdateFolderIntelligenceConfig": { + "methods": [ + "update_folder_intelligence_config" + ] + }, + "UpdateOrganizationIntelligenceConfig": { + "methods": [ + "update_organization_intelligence_config" + ] + }, + "UpdateProjectIntelligenceConfig": { + "methods": [ + "update_project_intelligence_config" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..073a79a684792db0ba1d524867d5509069eae4de --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/gapic_version.py @@ -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__ = "1.11.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..cee2f5ac8a9245a0f3fc45366085bc9d4e227940 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-storage-control package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/__init__.py @@ -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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..28991b09a2264245ec55a2bc590d87d96560f965 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/__init__.py @@ -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 StorageControlAsyncClient +from .client import StorageControlClient + +__all__ = ( + "StorageControlClient", + "StorageControlAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..293882df0bbff731e39522bbf754a21b76c7ce65 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/async_client.py @@ -0,0 +1,3974 @@ +# -*- 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 logging as std_logging +import re +import uuid +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +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.storage_control_v2 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 + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.storage_control_v2.services.storage_control import pagers +from google.cloud.storage_control_v2.types import storage_control + +from .client import StorageControlClient +from .transports.base import DEFAULT_CLIENT_INFO, StorageControlTransport +from .transports.grpc_asyncio import StorageControlGrpcAsyncIOTransport + +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 StorageControlAsyncClient: + """StorageControl service includes selected control plane + operations. + """ + + _client: StorageControlClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = StorageControlClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StorageControlClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = StorageControlClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = StorageControlClient._DEFAULT_UNIVERSE + + anywhere_cache_path = staticmethod(StorageControlClient.anywhere_cache_path) + parse_anywhere_cache_path = staticmethod( + StorageControlClient.parse_anywhere_cache_path + ) + folder_path = staticmethod(StorageControlClient.folder_path) + parse_folder_path = staticmethod(StorageControlClient.parse_folder_path) + intelligence_config_path = staticmethod( + StorageControlClient.intelligence_config_path + ) + parse_intelligence_config_path = staticmethod( + StorageControlClient.parse_intelligence_config_path + ) + managed_folder_path = staticmethod(StorageControlClient.managed_folder_path) + parse_managed_folder_path = staticmethod( + StorageControlClient.parse_managed_folder_path + ) + storage_layout_path = staticmethod(StorageControlClient.storage_layout_path) + parse_storage_layout_path = staticmethod( + StorageControlClient.parse_storage_layout_path + ) + common_billing_account_path = staticmethod( + StorageControlClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + StorageControlClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(StorageControlClient.common_folder_path) + parse_common_folder_path = staticmethod( + StorageControlClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + StorageControlClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + StorageControlClient.parse_common_organization_path + ) + common_project_path = staticmethod(StorageControlClient.common_project_path) + parse_common_project_path = staticmethod( + StorageControlClient.parse_common_project_path + ) + common_location_path = staticmethod(StorageControlClient.common_location_path) + parse_common_location_path = staticmethod( + StorageControlClient.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: + StorageControlAsyncClient: The constructed client. + """ + sa_info_func = ( + StorageControlClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(StorageControlAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + StorageControlAsyncClient: The constructed client. + """ + sa_file_func = ( + StorageControlClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(StorageControlAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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 StorageControlClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> StorageControlTransport: + """Returns the transport used by the client instance. + + Returns: + StorageControlTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = StorageControlClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, StorageControlTransport, Callable[..., StorageControlTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the storage control 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,StorageControlTransport,Callable[..., StorageControlTransport]]]): + 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 StorageControlTransport 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 = StorageControlClient( + 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.storage.control_v2.StorageControlAsyncClient`.", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "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.storage.control.v2.StorageControl", + "credentialsType": None, + }, + ) + + async def create_folder( + self, + request: Optional[Union[storage_control.CreateFolderRequest, dict]] = None, + *, + parent: Optional[str] = None, + folder: Optional[storage_control.Folder] = None, + folder_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.Folder: + r"""Creates a new folder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + .. 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 storage_control_v2 + + async def sample_create_folder(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.CreateFolderRequest( + parent="parent_value", + folder_id="folder_id_value", + ) + + # Make the request + response = await client.create_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.CreateFolderRequest, dict]]): + The request object. Request message for CreateFolder. + This operation is only applicable to a + hierarchical namespace enabled bucket. + parent (:class:`str`): + Required. Name of the bucket in which + the folder will reside. The bucket must + be a hierarchical namespace enabled + bucket. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + folder (:class:`google.cloud.storage_control_v2.types.Folder`): + Required. Properties of the new folder being created. + The bucket and name of the folder are specified in the + parent and folder_id fields, respectively. Populating + those fields in ``folder`` will result in an error. + + This corresponds to the ``folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + folder_id (:class:`str`): + Required. The full name of a folder, including all its + parent folders. Folders use single '/' characters as a + delimiter. The folder_id must end with a slash. For + example, the folder_id of "books/biographies/" would + create a new "biographies/" folder under the "books/" + folder. + + This corresponds to the ``folder_id`` 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.storage_control_v2.types.Folder: + A folder resource. This resource can + only exist in a hierarchical namespace + enabled bucket. + + """ + # 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 = [parent, folder, folder_id] + 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, storage_control.CreateFolderRequest): + request = storage_control.CreateFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if folder is not None: + request.folder = folder + if folder_id is not None: + request.folder_id = folder_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_folder + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 delete_folder( + self, + request: Optional[Union[storage_control.DeleteFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Permanently deletes an empty folder. This operation + is only applicable to a hierarchical namespace enabled + bucket. + + .. 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 storage_control_v2 + + async def sample_delete_folder(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.DeleteFolderRequest( + name="name_value", + ) + + # Make the request + await client.delete_folder(request=request) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.DeleteFolderRequest, dict]]): + The request object. Request message for DeleteFolder. + This operation is only applicable to a + hierarchical namespace enabled bucket. + name (:class:`str`): + Required. Name of the folder. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` 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`. + """ + # 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 = [name] + 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, storage_control.DeleteFolderRequest): + request = storage_control.DeleteFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_folder + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_folder( + self, + request: Optional[Union[storage_control.GetFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.Folder: + r"""Returns metadata for the specified folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. + + .. 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 storage_control_v2 + + async def sample_get_folder(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetFolderRequest( + name="name_value", + ) + + # Make the request + response = await client.get_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetFolderRequest, dict]]): + The request object. Request message for GetFolder. This + operation is only applicable to a + hierarchical namespace enabled bucket. + name (:class:`str`): + Required. Name of the folder. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` 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.storage_control_v2.types.Folder: + A folder resource. This resource can + only exist in a hierarchical namespace + enabled bucket. + + """ + # 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 = [name] + 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, storage_control.GetFolderRequest): + request = storage_control.GetFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_folder + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 list_folders( + self, + request: Optional[Union[storage_control.ListFoldersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListFoldersAsyncPager: + r"""Retrieves a list of folders. This operation is only + applicable to a hierarchical namespace enabled bucket. + + .. 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 storage_control_v2 + + async def sample_list_folders(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ListFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_folders(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.ListFoldersRequest, dict]]): + The request object. Request message for ListFolders. This + operation is only applicable to a + hierarchical namespace enabled bucket. + parent (:class:`str`): + Required. Name of the bucket in which + to look for folders. The bucket must be + a hierarchical namespace enabled bucket. + + This corresponds to the ``parent`` 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.storage_control_v2.services.storage_control.pagers.ListFoldersAsyncPager: + Response message for ListFolders. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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 = [parent] + 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, storage_control.ListFoldersRequest): + request = storage_control.ListFoldersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_folders + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFoldersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def rename_folder( + self, + request: Optional[Union[storage_control.RenameFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + destination_folder_id: Optional[str] = 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"""Renames a source folder to a destination folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. During a rename, the source and + destination folders are locked until the long running + operation completes. + + .. 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 storage_control_v2 + + async def sample_rename_folder(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.RenameFolderRequest( + name="name_value", + destination_folder_id="destination_folder_id_value", + ) + + # Make the request + operation = client.rename_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.RenameFolderRequest, dict]]): + The request object. Request message for RenameFolder. + This operation is only applicable to a + hierarchical namespace enabled bucket. + name (:class:`str`): + Required. Name of the source folder being renamed. + Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + destination_folder_id (:class:`str`): + Required. The destination folder ID, e.g. ``foo/bar/``. + This corresponds to the ``destination_folder_id`` 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.storage_control_v2.types.Folder` A folder resource. This resource can only exist in a hierarchical namespace + enabled bucket. + + """ + # 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 = [name, destination_folder_id] + 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, storage_control.RenameFolderRequest): + request = storage_control.RenameFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if destination_folder_id is not None: + request.destination_folder_id = destination_folder_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.rename_folder + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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, + storage_control.Folder, + metadata_type=storage_control.RenameFolderMetadata, + ) + + # Done; return the response. + return response + + async def delete_folder_recursive( + self, + request: Optional[ + Union[storage_control.DeleteFolderRecursiveRequest, dict] + ] = None, + *, + name: Optional[str] = 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"""Deletes a folder recursively. This operation is only + applicable to a hierarchical namespace enabled bucket. + + .. 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 storage_control_v2 + + async def sample_delete_folder_recursive(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.DeleteFolderRecursiveRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_folder_recursive(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.DeleteFolderRecursiveRequest, dict]]): + The request object. Request message for + DeleteFolderRecursive. + name (:class:`str`): + Required. Name of the folder being deleted, however all + of its contents will be deleted too. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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 = [name] + 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, storage_control.DeleteFolderRecursiveRequest): + request = storage_control.DeleteFolderRecursiveRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_folder_recursive + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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, + empty_pb2.Empty, + metadata_type=storage_control.DeleteFolderRecursiveMetadata, + ) + + # Done; return the response. + return response + + async def get_storage_layout( + self, + request: Optional[Union[storage_control.GetStorageLayoutRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.StorageLayout: + r"""Returns the storage layout configuration for a given + bucket. + + .. 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 storage_control_v2 + + async def sample_get_storage_layout(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetStorageLayoutRequest( + name="name_value", + ) + + # Make the request + response = await client.get_storage_layout(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetStorageLayoutRequest, dict]]): + The request object. Request message for GetStorageLayout. + name (:class:`str`): + Required. The name of the StorageLayout resource. + Format: + ``projects/{project}/buckets/{bucket}/storageLayout`` + + This corresponds to the ``name`` 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.storage_control_v2.types.StorageLayout: + The storage layout configuration of a + bucket. + + """ + # 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 = [name] + 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, storage_control.GetStorageLayoutRequest): + request = storage_control.GetStorageLayoutRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_storage_layout + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 create_managed_folder( + self, + request: Optional[ + Union[storage_control.CreateManagedFolderRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + managed_folder: Optional[storage_control.ManagedFolder] = None, + managed_folder_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ManagedFolder: + r"""Creates a new managed folder. + + .. 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 storage_control_v2 + + async def sample_create_managed_folder(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.CreateManagedFolderRequest( + parent="parent_value", + managed_folder_id="managed_folder_id_value", + ) + + # Make the request + response = await client.create_managed_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.CreateManagedFolderRequest, dict]]): + The request object. Request message for + CreateManagedFolder. + parent (:class:`str`): + Required. Name of the bucket this + managed folder belongs to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + managed_folder (:class:`google.cloud.storage_control_v2.types.ManagedFolder`): + Required. Properties of the managed folder being + created. The bucket and managed folder names are + specified in the ``parent`` and ``managed_folder_id`` + fields. Populating these fields in ``managed_folder`` + will result in an error. + + This corresponds to the ``managed_folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + managed_folder_id (:class:`str`): + Required. The name of the managed folder. It uses a + single ``/`` as delimiter and leading and trailing ``/`` + are allowed. + + This corresponds to the ``managed_folder_id`` 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.storage_control_v2.types.ManagedFolder: + A managed folder. + """ + # 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 = [parent, managed_folder, managed_folder_id] + 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, storage_control.CreateManagedFolderRequest): + request = storage_control.CreateManagedFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if managed_folder is not None: + request.managed_folder = managed_folder + if managed_folder_id is not None: + request.managed_folder_id = managed_folder_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_managed_folder + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 delete_managed_folder( + self, + request: Optional[ + Union[storage_control.DeleteManagedFolderRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Permanently deletes an empty managed folder. + + .. 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 storage_control_v2 + + async def sample_delete_managed_folder(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.DeleteManagedFolderRequest( + name="name_value", + ) + + # Make the request + await client.delete_managed_folder(request=request) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.DeleteManagedFolderRequest, dict]]): + The request object. DeleteManagedFolder RPC request + message. + name (:class:`str`): + Required. Name of the managed folder. Format: + ``projects/{project}/buckets/{bucket}/managedFolders/{managedFolder}`` + + This corresponds to the ``name`` 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`. + """ + # 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 = [name] + 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, storage_control.DeleteManagedFolderRequest): + request = storage_control.DeleteManagedFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_managed_folder + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_managed_folder( + self, + request: Optional[Union[storage_control.GetManagedFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ManagedFolder: + r"""Returns metadata for the specified managed folder. + + .. 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 storage_control_v2 + + async def sample_get_managed_folder(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetManagedFolderRequest( + name="name_value", + ) + + # Make the request + response = await client.get_managed_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetManagedFolderRequest, dict]]): + The request object. Request message for GetManagedFolder. + name (:class:`str`): + Required. Name of the managed folder. Format: + ``projects/{project}/buckets/{bucket}/managedFolders/{managedFolder}`` + + This corresponds to the ``name`` 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.storage_control_v2.types.ManagedFolder: + A managed folder. + """ + # 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 = [name] + 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, storage_control.GetManagedFolderRequest): + request = storage_control.GetManagedFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_managed_folder + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 list_managed_folders( + self, + request: Optional[ + Union[storage_control.ListManagedFoldersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListManagedFoldersAsyncPager: + r"""Retrieves a list of managed folders for a given + bucket. + + .. 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 storage_control_v2 + + async def sample_list_managed_folders(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ListManagedFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_managed_folders(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.ListManagedFoldersRequest, dict]]): + The request object. Request message for + ListManagedFolders. + parent (:class:`str`): + Required. Name of the bucket this + managed folder belongs to. + + This corresponds to the ``parent`` 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.storage_control_v2.services.storage_control.pagers.ListManagedFoldersAsyncPager: + Response message for + ListManagedFolders. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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 = [parent] + 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, storage_control.ListManagedFoldersRequest): + request = storage_control.ListManagedFoldersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_managed_folders + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListManagedFoldersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_anywhere_cache( + self, + request: Optional[ + Union[storage_control.CreateAnywhereCacheRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + anywhere_cache: Optional[storage_control.AnywhereCache] = 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"""Creates an Anywhere Cache instance. + + .. 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 storage_control_v2 + + async def sample_create_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.CreateAnywhereCacheRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_anywhere_cache(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.CreateAnywhereCacheRequest, dict]]): + The request object. Request message for + CreateAnywhereCache. + parent (:class:`str`): + Required. The bucket to which this cache belongs. + Format: ``projects/{project}/buckets/{bucket}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + anywhere_cache (:class:`google.cloud.storage_control_v2.types.AnywhereCache`): + Required. Properties of the Anywhere Cache instance + being created. The parent bucket name is specified in + the ``parent`` field. Server uses the default value of + ``ttl`` or ``admission_policy`` if not specified in + request. + + This corresponds to the ``anywhere_cache`` 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.storage_control_v2.types.AnywhereCache` + An Anywhere Cache Instance. + + """ + # 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 = [parent, anywhere_cache] + 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, storage_control.CreateAnywhereCacheRequest): + request = storage_control.CreateAnywhereCacheRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if anywhere_cache is not None: + request.anywhere_cache = anywhere_cache + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_anywhere_cache + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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, + storage_control.AnywhereCache, + metadata_type=storage_control.CreateAnywhereCacheMetadata, + ) + + # Done; return the response. + return response + + async def update_anywhere_cache( + self, + request: Optional[ + Union[storage_control.UpdateAnywhereCacheRequest, dict] + ] = None, + *, + anywhere_cache: Optional[storage_control.AnywhereCache] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates an Anywhere Cache instance. Mutable fields include + ``ttl`` and ``admission_policy``. + + .. 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 storage_control_v2 + + async def sample_update_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateAnywhereCacheRequest( + ) + + # Make the request + operation = client.update_anywhere_cache(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.UpdateAnywhereCacheRequest, dict]]): + The request object. Request message for + UpdateAnywhereCache. + anywhere_cache (:class:`google.cloud.storage_control_v2.types.AnywhereCache`): + Required. The Anywhere Cache instance + to be updated. + + This corresponds to the ``anywhere_cache`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be updated. Mutable fields + of AnywhereCache include ``ttl`` and + ``admission_policy``. + + To specify ALL fields, specify a single field with the + value ``*``. Note: We recommend against doing this. If a + new field is introduced at a later time, an older client + updating with the ``*`` may accidentally reset the new + field's value. + + Not specifying any fields is an error. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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.storage_control_v2.types.AnywhereCache` + An Anywhere Cache Instance. + + """ + # 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 = [anywhere_cache, update_mask] + 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, storage_control.UpdateAnywhereCacheRequest): + request = storage_control.UpdateAnywhereCacheRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if anywhere_cache is not None: + request.anywhere_cache = anywhere_cache + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_anywhere_cache + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.anywhere_cache.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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, + storage_control.AnywhereCache, + metadata_type=storage_control.UpdateAnywhereCacheMetadata, + ) + + # Done; return the response. + return response + + async def disable_anywhere_cache( + self, + request: Optional[ + Union[storage_control.DisableAnywhereCacheRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Disables an Anywhere Cache instance. A disabled + instance is read-only. The disablement could be revoked + by calling ResumeAnywhereCache. The cache instance will + be deleted automatically if it remains in the disabled + state for at least one hour. + + .. 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 storage_control_v2 + + async def sample_disable_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.DisableAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = await client.disable_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.DisableAnywhereCacheRequest, dict]]): + The request object. Request message for + DisableAnywhereCache. + name (:class:`str`): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.DisableAnywhereCacheRequest): + request = storage_control.DisableAnywhereCacheRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.disable_anywhere_cache + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 pause_anywhere_cache( + self, + request: Optional[ + Union[storage_control.PauseAnywhereCacheRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Pauses an Anywhere Cache instance. + + .. 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 storage_control_v2 + + async def sample_pause_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.PauseAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = await client.pause_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.PauseAnywhereCacheRequest, dict]]): + The request object. Request message for + PauseAnywhereCache. + name (:class:`str`): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.PauseAnywhereCacheRequest): + request = storage_control.PauseAnywhereCacheRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.pause_anywhere_cache + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 resume_anywhere_cache( + self, + request: Optional[ + Union[storage_control.ResumeAnywhereCacheRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Resumes a disabled or paused Anywhere Cache instance. + + .. 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 storage_control_v2 + + async def sample_resume_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ResumeAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = await client.resume_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.ResumeAnywhereCacheRequest, dict]]): + The request object. Request message for + ResumeAnywhereCache. + name (:class:`str`): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.ResumeAnywhereCacheRequest): + request = storage_control.ResumeAnywhereCacheRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.resume_anywhere_cache + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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_anywhere_cache( + self, + request: Optional[Union[storage_control.GetAnywhereCacheRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Gets an Anywhere Cache instance. + + .. 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 storage_control_v2 + + async def sample_get_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = await client.get_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetAnywhereCacheRequest, dict]]): + The request object. Request message for GetAnywhereCache. + name (:class:`str`): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.GetAnywhereCacheRequest): + request = storage_control.GetAnywhereCacheRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_anywhere_cache + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # 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 list_anywhere_caches( + self, + request: Optional[ + Union[storage_control.ListAnywhereCachesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAnywhereCachesAsyncPager: + r"""Lists Anywhere Cache instances for a given bucket. + + .. 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 storage_control_v2 + + async def sample_list_anywhere_caches(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ListAnywhereCachesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_anywhere_caches(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.ListAnywhereCachesRequest, dict]]): + The request object. Request message for + ListAnywhereCaches. + parent (:class:`str`): + Required. The bucket to which this + cache belongs. + + This corresponds to the ``parent`` 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.storage_control_v2.services.storage_control.pagers.ListAnywhereCachesAsyncPager: + Response message for + ListAnywhereCaches. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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 = [parent] + 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, storage_control.ListAnywhereCachesRequest): + request = storage_control.ListAnywhereCachesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_anywhere_caches + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAnywhereCachesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_project_intelligence_config( + self, + request: Optional[ + Union[storage_control.GetProjectIntelligenceConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Returns the Project scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + async def sample_get_project_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetProjectIntelligenceConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_project_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetProjectIntelligenceConfigRequest, dict]]): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the project. + name (:class:`str`): + Required. The name of the ``IntelligenceConfig`` + resource associated with your project. + + Format: + ``projects/{id}/locations/global/intelligenceConfig`` + + This corresponds to the ``name`` 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [name] + 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, storage_control.GetProjectIntelligenceConfigRequest): + request = storage_control.GetProjectIntelligenceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_project_intelligence_config + ] + + # 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 update_project_intelligence_config( + self, + request: Optional[ + Union[storage_control.UpdateProjectIntelligenceConfigRequest, dict] + ] = None, + *, + intelligence_config: Optional[storage_control.IntelligenceConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Updates the Project scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + async def sample_update_project_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateProjectIntelligenceConfigRequest( + ) + + # Make the request + response = await client.update_project_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.UpdateProjectIntelligenceConfigRequest, dict]]): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + intelligence_config (:class:`google.cloud.storage_control_v2.types.IntelligenceConfig`): + Required. The ``IntelligenceConfig`` resource to be + updated. + + This corresponds to the ``intelligence_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should + be modified by this update. Only the listed fields are + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [intelligence_config, update_mask] + 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, storage_control.UpdateProjectIntelligenceConfigRequest + ): + request = storage_control.UpdateProjectIntelligenceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intelligence_config is not None: + request.intelligence_config = intelligence_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_project_intelligence_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("intelligence_config.name", request.intelligence_config.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_folder_intelligence_config( + self, + request: Optional[ + Union[storage_control.GetFolderIntelligenceConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Returns the Folder scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + async def sample_get_folder_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetFolderIntelligenceConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_folder_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetFolderIntelligenceConfigRequest, dict]]): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your folder. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the folder. + name (:class:`str`): + Required. The name of the ``IntelligenceConfig`` + resource associated with your folder. + + Format: + ``folders/{id}/locations/global/intelligenceConfig`` + + This corresponds to the ``name`` 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [name] + 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, storage_control.GetFolderIntelligenceConfigRequest): + request = storage_control.GetFolderIntelligenceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_folder_intelligence_config + ] + + # 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 update_folder_intelligence_config( + self, + request: Optional[ + Union[storage_control.UpdateFolderIntelligenceConfigRequest, dict] + ] = None, + *, + intelligence_config: Optional[storage_control.IntelligenceConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Updates the Folder scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + async def sample_update_folder_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateFolderIntelligenceConfigRequest( + ) + + # Make the request + response = await client.update_folder_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.UpdateFolderIntelligenceConfigRequest, dict]]): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your folder. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + intelligence_config (:class:`google.cloud.storage_control_v2.types.IntelligenceConfig`): + Required. The ``IntelligenceConfig`` resource to be + updated. + + This corresponds to the ``intelligence_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should + be modified by this update. Only the listed fields are + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [intelligence_config, update_mask] + 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, storage_control.UpdateFolderIntelligenceConfigRequest + ): + request = storage_control.UpdateFolderIntelligenceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intelligence_config is not None: + request.intelligence_config = intelligence_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_folder_intelligence_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("intelligence_config.name", request.intelligence_config.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_organization_intelligence_config( + self, + request: Optional[ + Union[storage_control.GetOrganizationIntelligenceConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Returns the Organization scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + async def sample_get_organization_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetOrganizationIntelligenceConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetOrganizationIntelligenceConfigRequest, dict]]): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your organization. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the organization. + name (:class:`str`): + Required. The name of the ``IntelligenceConfig`` + resource associated with your organization. + + Format: + ``organizations/{org_id}/locations/global/intelligenceConfig`` + + This corresponds to the ``name`` 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [name] + 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, storage_control.GetOrganizationIntelligenceConfigRequest + ): + request = storage_control.GetOrganizationIntelligenceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_organization_intelligence_config + ] + + # 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 update_organization_intelligence_config( + self, + request: Optional[ + Union[storage_control.UpdateOrganizationIntelligenceConfigRequest, dict] + ] = None, + *, + intelligence_config: Optional[storage_control.IntelligenceConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Updates the Organization scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + async def sample_update_organization_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateOrganizationIntelligenceConfigRequest( + ) + + # Make the request + response = await client.update_organization_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.UpdateOrganizationIntelligenceConfigRequest, dict]]): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your organization. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the organization. + intelligence_config (:class:`google.cloud.storage_control_v2.types.IntelligenceConfig`): + Required. The ``IntelligenceConfig`` resource to be + updated. + + This corresponds to the ``intelligence_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should + be modified by this update. Only the listed fields are + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [intelligence_config, update_mask] + 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, storage_control.UpdateOrganizationIntelligenceConfigRequest + ): + request = storage_control.UpdateOrganizationIntelligenceConfigRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intelligence_config is not None: + request.intelligence_config = intelligence_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_organization_intelligence_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("intelligence_config.name", request.intelligence_config.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_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy for a specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + .. 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 storage_control_v2 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # 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 = [resource] + 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." + ) + + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_iam_policy + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Updates an IAM policy for the specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + .. 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 storage_control_v2 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # 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 = [resource] + 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." + ) + + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.set_iam_policy + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests a set of permissions on the given bucket, object, or + managed folder to see which, if any, are held by the caller. The + ``resource`` field in the request should be + ``projects/_/buckets/{bucket}`` for a bucket, + ``projects/_/buckets/{bucket}/objects/{object}`` for an object, + or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + .. 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 storage_control_v2 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # 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 = [resource, permissions] + 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." + ) + + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)/objects(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)/managedFolders(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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) -> "StorageControlAsyncClient": + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("StorageControlAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/client.py new file mode 100644 index 0000000000000000000000000000000000000000..1a92bb7211d46c0497d0968c4b18cfa654fed3d7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/client.py @@ -0,0 +1,4422 @@ +# -*- 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 os +import re +import uuid +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.storage_control_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.storage_control_v2.services.storage_control import pagers +from google.cloud.storage_control_v2.types import storage_control + +from .transports.base import DEFAULT_CLIENT_INFO, StorageControlTransport +from .transports.grpc import StorageControlGrpcTransport +from .transports.grpc_asyncio import StorageControlGrpcAsyncIOTransport +from .transports.rest import StorageControlRestTransport + + +class StorageControlClientMeta(type): + """Metaclass for the StorageControl client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[StorageControlTransport]] + _transport_registry["grpc"] = StorageControlGrpcTransport + _transport_registry["grpc_asyncio"] = StorageControlGrpcAsyncIOTransport + _transport_registry["rest"] = StorageControlRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[StorageControlTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class StorageControlClient(metaclass=StorageControlClientMeta): + """StorageControl service includes selected control plane + operations. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "storage.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "storage.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + StorageControlClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + StorageControlClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> StorageControlTransport: + """Returns the transport used by the client instance. + + Returns: + StorageControlTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def anywhere_cache_path( + project: str, + bucket: str, + anywhere_cache: str, + ) -> str: + """Returns a fully-qualified anywhere_cache string.""" + return "projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}".format( + project=project, + bucket=bucket, + anywhere_cache=anywhere_cache, + ) + + @staticmethod + def parse_anywhere_cache_path(path: str) -> Dict[str, str]: + """Parses a anywhere_cache path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/buckets/(?P.+?)/anywhereCaches/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def folder_path( + project: str, + bucket: str, + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "projects/{project}/buckets/{bucket}/folders/{folder}".format( + project=project, + bucket=bucket, + folder=folder, + ) + + @staticmethod + def parse_folder_path(path: str) -> Dict[str, str]: + """Parses a folder path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/buckets/(?P.+?)/folders/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def intelligence_config_path( + folder: str, + location: str, + ) -> str: + """Returns a fully-qualified intelligence_config string.""" + return "folders/{folder}/locations/{location}/intelligenceConfig".format( + folder=folder, + location=location, + ) + + @staticmethod + def parse_intelligence_config_path(path: str) -> Dict[str, str]: + """Parses a intelligence_config path into its component segments.""" + m = re.match( + r"^folders/(?P.+?)/locations/(?P.+?)/intelligenceConfig$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def managed_folder_path( + project: str, + bucket: str, + managed_folder: str, + ) -> str: + """Returns a fully-qualified managed_folder string.""" + return "projects/{project}/buckets/{bucket}/managedFolders/{managed_folder}".format( + project=project, + bucket=bucket, + managed_folder=managed_folder, + ) + + @staticmethod + def parse_managed_folder_path(path: str) -> Dict[str, str]: + """Parses a managed_folder path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/buckets/(?P.+?)/managedFolders/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def storage_layout_path( + project: str, + bucket: str, + ) -> str: + """Returns a fully-qualified storage_layout string.""" + return "projects/{project}/buckets/{bucket}/storageLayout".format( + project=project, + bucket=bucket, + ) + + @staticmethod + def parse_storage_layout_path(path: str) -> Dict[str, str]: + """Parses a storage_layout path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/buckets/(?P.+?)/storageLayout$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. 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. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = StorageControlClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = StorageControlClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = StorageControlClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = StorageControlClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = StorageControlClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = StorageControlClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._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._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, StorageControlTransport, Callable[..., StorageControlTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the storage control 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,StorageControlTransport,Callable[..., StorageControlTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the StorageControlTransport 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 the ``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_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + StorageControlClient._read_environment_variables() + ) + self._client_cert_source = StorageControlClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = StorageControlClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, StorageControlTransport) + if transport_provided: + # transport is a StorageControlTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(StorageControlTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or StorageControlClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[StorageControlTransport], Callable[..., StorageControlTransport] + ] = ( + StorageControlClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., StorageControlTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.storage.control_v2.StorageControlClient`.", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.storage.control.v2.StorageControl", + "credentialsType": None, + }, + ) + + def create_folder( + self, + request: Optional[Union[storage_control.CreateFolderRequest, dict]] = None, + *, + parent: Optional[str] = None, + folder: Optional[storage_control.Folder] = None, + folder_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.Folder: + r"""Creates a new folder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + .. 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 storage_control_v2 + + def sample_create_folder(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.CreateFolderRequest( + parent="parent_value", + folder_id="folder_id_value", + ) + + # Make the request + response = client.create_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.CreateFolderRequest, dict]): + The request object. Request message for CreateFolder. + This operation is only applicable to a + hierarchical namespace enabled bucket. + parent (str): + Required. Name of the bucket in which + the folder will reside. The bucket must + be a hierarchical namespace enabled + bucket. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + folder (google.cloud.storage_control_v2.types.Folder): + Required. Properties of the new folder being created. + The bucket and name of the folder are specified in the + parent and folder_id fields, respectively. Populating + those fields in ``folder`` will result in an error. + + This corresponds to the ``folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + folder_id (str): + Required. The full name of a folder, including all its + parent folders. Folders use single '/' characters as a + delimiter. The folder_id must end with a slash. For + example, the folder_id of "books/biographies/" would + create a new "biographies/" folder under the "books/" + folder. + + This corresponds to the ``folder_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.Folder: + A folder resource. This resource can + only exist in a hierarchical namespace + enabled bucket. + + """ + # 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 = [parent, folder, folder_id] + 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, storage_control.CreateFolderRequest): + request = storage_control.CreateFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if folder is not None: + request.folder = folder + if folder_id is not None: + request.folder_id = folder_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_folder] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_folder( + self, + request: Optional[Union[storage_control.DeleteFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Permanently deletes an empty folder. This operation + is only applicable to a hierarchical namespace enabled + bucket. + + .. 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 storage_control_v2 + + def sample_delete_folder(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.DeleteFolderRequest( + name="name_value", + ) + + # Make the request + client.delete_folder(request=request) + + Args: + request (Union[google.cloud.storage_control_v2.types.DeleteFolderRequest, dict]): + The request object. Request message for DeleteFolder. + This operation is only applicable to a + hierarchical namespace enabled bucket. + name (str): + Required. Name of the folder. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + # 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 = [name] + 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, storage_control.DeleteFolderRequest): + request = storage_control.DeleteFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_folder] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_folder( + self, + request: Optional[Union[storage_control.GetFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.Folder: + r"""Returns metadata for the specified folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. + + .. 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 storage_control_v2 + + def sample_get_folder(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetFolderRequest( + name="name_value", + ) + + # Make the request + response = client.get_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetFolderRequest, dict]): + The request object. Request message for GetFolder. This + operation is only applicable to a + hierarchical namespace enabled bucket. + name (str): + Required. Name of the folder. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.Folder: + A folder resource. This resource can + only exist in a hierarchical namespace + enabled bucket. + + """ + # 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 = [name] + 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, storage_control.GetFolderRequest): + request = storage_control.GetFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_folder] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_folders( + self, + request: Optional[Union[storage_control.ListFoldersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListFoldersPager: + r"""Retrieves a list of folders. This operation is only + applicable to a hierarchical namespace enabled bucket. + + .. 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 storage_control_v2 + + def sample_list_folders(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ListFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_folders(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.ListFoldersRequest, dict]): + The request object. Request message for ListFolders. This + operation is only applicable to a + hierarchical namespace enabled bucket. + parent (str): + Required. Name of the bucket in which + to look for folders. The bucket must be + a hierarchical namespace enabled bucket. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.services.storage_control.pagers.ListFoldersPager: + Response message for ListFolders. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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 = [parent] + 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, storage_control.ListFoldersRequest): + request = storage_control.ListFoldersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_folders] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFoldersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def rename_folder( + self, + request: Optional[Union[storage_control.RenameFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + destination_folder_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Renames a source folder to a destination folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. During a rename, the source and + destination folders are locked until the long running + operation completes. + + .. 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 storage_control_v2 + + def sample_rename_folder(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.RenameFolderRequest( + name="name_value", + destination_folder_id="destination_folder_id_value", + ) + + # Make the request + operation = client.rename_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.RenameFolderRequest, dict]): + The request object. Request message for RenameFolder. + This operation is only applicable to a + hierarchical namespace enabled bucket. + name (str): + Required. Name of the source folder being renamed. + Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + destination_folder_id (str): + Required. The destination folder ID, e.g. ``foo/bar/``. + This corresponds to the ``destination_folder_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.storage_control_v2.types.Folder` A folder resource. This resource can only exist in a hierarchical namespace + enabled bucket. + + """ + # 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 = [name, destination_folder_id] + 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, storage_control.RenameFolderRequest): + request = storage_control.RenameFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if destination_folder_id is not None: + request.destination_folder_id = destination_folder_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rename_folder] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + storage_control.Folder, + metadata_type=storage_control.RenameFolderMetadata, + ) + + # Done; return the response. + return response + + def delete_folder_recursive( + self, + request: Optional[ + Union[storage_control.DeleteFolderRecursiveRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a folder recursively. This operation is only + applicable to a hierarchical namespace enabled bucket. + + .. 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 storage_control_v2 + + def sample_delete_folder_recursive(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.DeleteFolderRecursiveRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_folder_recursive(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.DeleteFolderRecursiveRequest, dict]): + The request object. Request message for + DeleteFolderRecursive. + name (str): + Required. Name of the folder being deleted, however all + of its contents will be deleted too. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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 = [name] + 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, storage_control.DeleteFolderRecursiveRequest): + request = storage_control.DeleteFolderRecursiveRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_folder_recursive] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=storage_control.DeleteFolderRecursiveMetadata, + ) + + # Done; return the response. + return response + + def get_storage_layout( + self, + request: Optional[Union[storage_control.GetStorageLayoutRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.StorageLayout: + r"""Returns the storage layout configuration for a given + bucket. + + .. 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 storage_control_v2 + + def sample_get_storage_layout(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetStorageLayoutRequest( + name="name_value", + ) + + # Make the request + response = client.get_storage_layout(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetStorageLayoutRequest, dict]): + The request object. Request message for GetStorageLayout. + name (str): + Required. The name of the StorageLayout resource. + Format: + ``projects/{project}/buckets/{bucket}/storageLayout`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.StorageLayout: + The storage layout configuration of a + bucket. + + """ + # 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 = [name] + 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, storage_control.GetStorageLayoutRequest): + request = storage_control.GetStorageLayoutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_storage_layout] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_managed_folder( + self, + request: Optional[ + Union[storage_control.CreateManagedFolderRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + managed_folder: Optional[storage_control.ManagedFolder] = None, + managed_folder_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ManagedFolder: + r"""Creates a new managed folder. + + .. 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 storage_control_v2 + + def sample_create_managed_folder(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.CreateManagedFolderRequest( + parent="parent_value", + managed_folder_id="managed_folder_id_value", + ) + + # Make the request + response = client.create_managed_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.CreateManagedFolderRequest, dict]): + The request object. Request message for + CreateManagedFolder. + parent (str): + Required. Name of the bucket this + managed folder belongs to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + managed_folder (google.cloud.storage_control_v2.types.ManagedFolder): + Required. Properties of the managed folder being + created. The bucket and managed folder names are + specified in the ``parent`` and ``managed_folder_id`` + fields. Populating these fields in ``managed_folder`` + will result in an error. + + This corresponds to the ``managed_folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + managed_folder_id (str): + Required. The name of the managed folder. It uses a + single ``/`` as delimiter and leading and trailing ``/`` + are allowed. + + This corresponds to the ``managed_folder_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.ManagedFolder: + A managed folder. + """ + # 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 = [parent, managed_folder, managed_folder_id] + 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, storage_control.CreateManagedFolderRequest): + request = storage_control.CreateManagedFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if managed_folder is not None: + request.managed_folder = managed_folder + if managed_folder_id is not None: + request.managed_folder_id = managed_folder_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_managed_folder] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_managed_folder( + self, + request: Optional[ + Union[storage_control.DeleteManagedFolderRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Permanently deletes an empty managed folder. + + .. 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 storage_control_v2 + + def sample_delete_managed_folder(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.DeleteManagedFolderRequest( + name="name_value", + ) + + # Make the request + client.delete_managed_folder(request=request) + + Args: + request (Union[google.cloud.storage_control_v2.types.DeleteManagedFolderRequest, dict]): + The request object. DeleteManagedFolder RPC request + message. + name (str): + Required. Name of the managed folder. Format: + ``projects/{project}/buckets/{bucket}/managedFolders/{managedFolder}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + # 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 = [name] + 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, storage_control.DeleteManagedFolderRequest): + request = storage_control.DeleteManagedFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_managed_folder] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_managed_folder( + self, + request: Optional[Union[storage_control.GetManagedFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ManagedFolder: + r"""Returns metadata for the specified managed folder. + + .. 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 storage_control_v2 + + def sample_get_managed_folder(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetManagedFolderRequest( + name="name_value", + ) + + # Make the request + response = client.get_managed_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetManagedFolderRequest, dict]): + The request object. Request message for GetManagedFolder. + name (str): + Required. Name of the managed folder. Format: + ``projects/{project}/buckets/{bucket}/managedFolders/{managedFolder}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.ManagedFolder: + A managed folder. + """ + # 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 = [name] + 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, storage_control.GetManagedFolderRequest): + request = storage_control.GetManagedFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_managed_folder] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_managed_folders( + self, + request: Optional[ + Union[storage_control.ListManagedFoldersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListManagedFoldersPager: + r"""Retrieves a list of managed folders for a given + bucket. + + .. 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 storage_control_v2 + + def sample_list_managed_folders(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ListManagedFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_managed_folders(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.ListManagedFoldersRequest, dict]): + The request object. Request message for + ListManagedFolders. + parent (str): + Required. Name of the bucket this + managed folder belongs to. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.services.storage_control.pagers.ListManagedFoldersPager: + Response message for + ListManagedFolders. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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 = [parent] + 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, storage_control.ListManagedFoldersRequest): + request = storage_control.ListManagedFoldersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_managed_folders] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListManagedFoldersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_anywhere_cache( + self, + request: Optional[ + Union[storage_control.CreateAnywhereCacheRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + anywhere_cache: Optional[storage_control.AnywhereCache] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates an Anywhere Cache instance. + + .. 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 storage_control_v2 + + def sample_create_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.CreateAnywhereCacheRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_anywhere_cache(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.CreateAnywhereCacheRequest, dict]): + The request object. Request message for + CreateAnywhereCache. + parent (str): + Required. The bucket to which this cache belongs. + Format: ``projects/{project}/buckets/{bucket}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + anywhere_cache (google.cloud.storage_control_v2.types.AnywhereCache): + Required. Properties of the Anywhere Cache instance + being created. The parent bucket name is specified in + the ``parent`` field. Server uses the default value of + ``ttl`` or ``admission_policy`` if not specified in + request. + + This corresponds to the ``anywhere_cache`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.storage_control_v2.types.AnywhereCache` + An Anywhere Cache Instance. + + """ + # 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 = [parent, anywhere_cache] + 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, storage_control.CreateAnywhereCacheRequest): + request = storage_control.CreateAnywhereCacheRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if anywhere_cache is not None: + request.anywhere_cache = anywhere_cache + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_anywhere_cache] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + storage_control.AnywhereCache, + metadata_type=storage_control.CreateAnywhereCacheMetadata, + ) + + # Done; return the response. + return response + + def update_anywhere_cache( + self, + request: Optional[ + Union[storage_control.UpdateAnywhereCacheRequest, dict] + ] = None, + *, + anywhere_cache: Optional[storage_control.AnywhereCache] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates an Anywhere Cache instance. Mutable fields include + ``ttl`` and ``admission_policy``. + + .. 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 storage_control_v2 + + def sample_update_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateAnywhereCacheRequest( + ) + + # Make the request + operation = client.update_anywhere_cache(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.UpdateAnywhereCacheRequest, dict]): + The request object. Request message for + UpdateAnywhereCache. + anywhere_cache (google.cloud.storage_control_v2.types.AnywhereCache): + Required. The Anywhere Cache instance + to be updated. + + This corresponds to the ``anywhere_cache`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated. Mutable fields + of AnywhereCache include ``ttl`` and + ``admission_policy``. + + To specify ALL fields, specify a single field with the + value ``*``. Note: We recommend against doing this. If a + new field is introduced at a later time, an older client + updating with the ``*`` may accidentally reset the new + field's value. + + Not specifying any fields is an error. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.storage_control_v2.types.AnywhereCache` + An Anywhere Cache Instance. + + """ + # 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 = [anywhere_cache, update_mask] + 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, storage_control.UpdateAnywhereCacheRequest): + request = storage_control.UpdateAnywhereCacheRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if anywhere_cache is not None: + request.anywhere_cache = anywhere_cache + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_anywhere_cache] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.anywhere_cache.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + storage_control.AnywhereCache, + metadata_type=storage_control.UpdateAnywhereCacheMetadata, + ) + + # Done; return the response. + return response + + def disable_anywhere_cache( + self, + request: Optional[ + Union[storage_control.DisableAnywhereCacheRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Disables an Anywhere Cache instance. A disabled + instance is read-only. The disablement could be revoked + by calling ResumeAnywhereCache. The cache instance will + be deleted automatically if it remains in the disabled + state for at least one hour. + + .. 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 storage_control_v2 + + def sample_disable_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.DisableAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = client.disable_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.DisableAnywhereCacheRequest, dict]): + The request object. Request message for + DisableAnywhereCache. + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.DisableAnywhereCacheRequest): + request = storage_control.DisableAnywhereCacheRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.disable_anywhere_cache] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def pause_anywhere_cache( + self, + request: Optional[ + Union[storage_control.PauseAnywhereCacheRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Pauses an Anywhere Cache instance. + + .. 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 storage_control_v2 + + def sample_pause_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.PauseAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = client.pause_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.PauseAnywhereCacheRequest, dict]): + The request object. Request message for + PauseAnywhereCache. + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.PauseAnywhereCacheRequest): + request = storage_control.PauseAnywhereCacheRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause_anywhere_cache] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def resume_anywhere_cache( + self, + request: Optional[ + Union[storage_control.ResumeAnywhereCacheRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Resumes a disabled or paused Anywhere Cache instance. + + .. 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 storage_control_v2 + + def sample_resume_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ResumeAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = client.resume_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.ResumeAnywhereCacheRequest, dict]): + The request object. Request message for + ResumeAnywhereCache. + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.ResumeAnywhereCacheRequest): + request = storage_control.ResumeAnywhereCacheRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume_anywhere_cache] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_anywhere_cache( + self, + request: Optional[Union[storage_control.GetAnywhereCacheRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + r"""Gets an Anywhere Cache instance. + + .. 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 storage_control_v2 + + def sample_get_anywhere_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetAnywhereCacheRequest( + name="name_value", + ) + + # Make the request + response = client.get_anywhere_cache(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetAnywhereCacheRequest, dict]): + The request object. Request message for GetAnywhereCache. + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.AnywhereCache: + An Anywhere Cache Instance. + """ + # 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 = [name] + 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, storage_control.GetAnywhereCacheRequest): + request = storage_control.GetAnywhereCacheRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_anywhere_cache] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_anywhere_caches( + self, + request: Optional[ + Union[storage_control.ListAnywhereCachesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAnywhereCachesPager: + r"""Lists Anywhere Cache instances for a given bucket. + + .. 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 storage_control_v2 + + def sample_list_anywhere_caches(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ListAnywhereCachesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_anywhere_caches(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.ListAnywhereCachesRequest, dict]): + The request object. Request message for + ListAnywhereCaches. + parent (str): + Required. The bucket to which this + cache belongs. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.services.storage_control.pagers.ListAnywhereCachesPager: + Response message for + ListAnywhereCaches. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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 = [parent] + 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, storage_control.ListAnywhereCachesRequest): + request = storage_control.ListAnywhereCachesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_anywhere_caches] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + if not request.request_id: + request.request_id = str(uuid.uuid4()) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAnywhereCachesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_project_intelligence_config( + self, + request: Optional[ + Union[storage_control.GetProjectIntelligenceConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Returns the Project scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + def sample_get_project_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetProjectIntelligenceConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_project_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetProjectIntelligenceConfigRequest, dict]): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the project. + name (str): + Required. The name of the ``IntelligenceConfig`` + resource associated with your project. + + Format: + ``projects/{id}/locations/global/intelligenceConfig`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [name] + 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, storage_control.GetProjectIntelligenceConfigRequest): + request = storage_control.GetProjectIntelligenceConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_project_intelligence_config + ] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_project_intelligence_config( + self, + request: Optional[ + Union[storage_control.UpdateProjectIntelligenceConfigRequest, dict] + ] = None, + *, + intelligence_config: Optional[storage_control.IntelligenceConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Updates the Project scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + def sample_update_project_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateProjectIntelligenceConfigRequest( + ) + + # Make the request + response = client.update_project_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.UpdateProjectIntelligenceConfigRequest, dict]): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + intelligence_config (google.cloud.storage_control_v2.types.IntelligenceConfig): + Required. The ``IntelligenceConfig`` resource to be + updated. + + This corresponds to the ``intelligence_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should + be modified by this update. Only the listed fields are + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [intelligence_config, update_mask] + 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, storage_control.UpdateProjectIntelligenceConfigRequest + ): + request = storage_control.UpdateProjectIntelligenceConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intelligence_config is not None: + request.intelligence_config = intelligence_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_project_intelligence_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("intelligence_config.name", request.intelligence_config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_folder_intelligence_config( + self, + request: Optional[ + Union[storage_control.GetFolderIntelligenceConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Returns the Folder scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + def sample_get_folder_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetFolderIntelligenceConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_folder_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetFolderIntelligenceConfigRequest, dict]): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your folder. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the folder. + name (str): + Required. The name of the ``IntelligenceConfig`` + resource associated with your folder. + + Format: + ``folders/{id}/locations/global/intelligenceConfig`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [name] + 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, storage_control.GetFolderIntelligenceConfigRequest): + request = storage_control.GetFolderIntelligenceConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_folder_intelligence_config + ] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_folder_intelligence_config( + self, + request: Optional[ + Union[storage_control.UpdateFolderIntelligenceConfigRequest, dict] + ] = None, + *, + intelligence_config: Optional[storage_control.IntelligenceConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Updates the Folder scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + def sample_update_folder_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateFolderIntelligenceConfigRequest( + ) + + # Make the request + response = client.update_folder_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.UpdateFolderIntelligenceConfigRequest, dict]): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your folder. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + intelligence_config (google.cloud.storage_control_v2.types.IntelligenceConfig): + Required. The ``IntelligenceConfig`` resource to be + updated. + + This corresponds to the ``intelligence_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should + be modified by this update. Only the listed fields are + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [intelligence_config, update_mask] + 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, storage_control.UpdateFolderIntelligenceConfigRequest + ): + request = storage_control.UpdateFolderIntelligenceConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intelligence_config is not None: + request.intelligence_config = intelligence_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_folder_intelligence_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("intelligence_config.name", request.intelligence_config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_organization_intelligence_config( + self, + request: Optional[ + Union[storage_control.GetOrganizationIntelligenceConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Returns the Organization scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + def sample_get_organization_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetOrganizationIntelligenceConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetOrganizationIntelligenceConfigRequest, dict]): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your organization. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the organization. + name (str): + Required. The name of the ``IntelligenceConfig`` + resource associated with your organization. + + Format: + ``organizations/{org_id}/locations/global/intelligenceConfig`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [name] + 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, storage_control.GetOrganizationIntelligenceConfigRequest + ): + request = storage_control.GetOrganizationIntelligenceConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_organization_intelligence_config + ] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_organization_intelligence_config( + self, + request: Optional[ + Union[storage_control.UpdateOrganizationIntelligenceConfigRequest, dict] + ] = None, + *, + intelligence_config: Optional[storage_control.IntelligenceConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Updates the Organization scoped singleton + IntelligenceConfig resource. + + .. 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 storage_control_v2 + + def sample_update_organization_intelligence_config(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.UpdateOrganizationIntelligenceConfigRequest( + ) + + # Make the request + response = client.update_organization_intelligence_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.UpdateOrganizationIntelligenceConfigRequest, dict]): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your organization. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the organization. + intelligence_config (google.cloud.storage_control_v2.types.IntelligenceConfig): + Required. The ``IntelligenceConfig`` resource to be + updated. + + This corresponds to the ``intelligence_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should + be modified by this update. Only the listed fields are + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.storage_control_v2.types.IntelligenceConfig: + The IntelligenceConfig resource associated with your organization, folder, + or project. + + """ + # 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 = [intelligence_config, update_mask] + 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, storage_control.UpdateOrganizationIntelligenceConfigRequest + ): + request = storage_control.UpdateOrganizationIntelligenceConfigRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intelligence_config is not None: + request.intelligence_config = intelligence_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_organization_intelligence_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("intelligence_config.name", request.intelligence_config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy for a specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + .. 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 storage_control_v2 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # 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 = [resource] + 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." + ) + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Updates an IAM policy for the specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + .. 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 storage_control_v2 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # 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 = [resource] + 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." + ) + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests a set of permissions on the given bucket, object, or + managed folder to see which, if any, are held by the caller. The + ``resource`` field in the request should be + ``projects/_/buckets/{bucket}`` for a bucket, + ``projects/_/buckets/{bucket}/objects/{object}`` for an object, + or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + .. 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 storage_control_v2 + import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # 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 = [resource, permissions] + 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." + ) + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + header_params = {} + + routing_param_regex = re.compile("^(?P.*)$") + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)/objects(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)/managedFolders(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.resource) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "StorageControlClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("StorageControlClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..a77ad43a57755fdf399e3ba925b2c45204824b48 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/pagers.py @@ -0,0 +1,509 @@ +# -*- 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.storage_control_v2.types import storage_control + + +class ListFoldersPager: + """A pager for iterating through ``list_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListFoldersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``folders`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFolders`` requests and continue to iterate + through the ``folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListFoldersResponse` + 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[..., storage_control.ListFoldersResponse], + request: storage_control.ListFoldersRequest, + response: storage_control.ListFoldersResponse, + *, + 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.storage_control_v2.types.ListFoldersRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListFoldersResponse): + 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 = storage_control.ListFoldersRequest(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[storage_control.ListFoldersResponse]: + 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[storage_control.Folder]: + for page in self.pages: + yield from page.folders + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFoldersAsyncPager: + """A pager for iterating through ``list_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListFoldersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``folders`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFolders`` requests and continue to iterate + through the ``folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListFoldersResponse` + 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[storage_control.ListFoldersResponse]], + request: storage_control.ListFoldersRequest, + response: storage_control.ListFoldersResponse, + *, + 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.storage_control_v2.types.ListFoldersRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListFoldersResponse): + 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 = storage_control.ListFoldersRequest(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[storage_control.ListFoldersResponse]: + 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[storage_control.Folder]: + async def async_generator(): + async for page in self.pages: + for response in page.folders: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListManagedFoldersPager: + """A pager for iterating through ``list_managed_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListManagedFoldersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``managed_folders`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListManagedFolders`` requests and continue to iterate + through the ``managed_folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListManagedFoldersResponse` + 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[..., storage_control.ListManagedFoldersResponse], + request: storage_control.ListManagedFoldersRequest, + response: storage_control.ListManagedFoldersResponse, + *, + 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.storage_control_v2.types.ListManagedFoldersRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListManagedFoldersResponse): + 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 = storage_control.ListManagedFoldersRequest(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[storage_control.ListManagedFoldersResponse]: + 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[storage_control.ManagedFolder]: + for page in self.pages: + yield from page.managed_folders + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListManagedFoldersAsyncPager: + """A pager for iterating through ``list_managed_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListManagedFoldersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``managed_folders`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListManagedFolders`` requests and continue to iterate + through the ``managed_folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListManagedFoldersResponse` + 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[storage_control.ListManagedFoldersResponse]], + request: storage_control.ListManagedFoldersRequest, + response: storage_control.ListManagedFoldersResponse, + *, + 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.storage_control_v2.types.ListManagedFoldersRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListManagedFoldersResponse): + 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 = storage_control.ListManagedFoldersRequest(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[storage_control.ListManagedFoldersResponse]: + 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[storage_control.ManagedFolder]: + async def async_generator(): + async for page in self.pages: + for response in page.managed_folders: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAnywhereCachesPager: + """A pager for iterating through ``list_anywhere_caches`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListAnywhereCachesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``anywhere_caches`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAnywhereCaches`` requests and continue to iterate + through the ``anywhere_caches`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListAnywhereCachesResponse` + 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[..., storage_control.ListAnywhereCachesResponse], + request: storage_control.ListAnywhereCachesRequest, + response: storage_control.ListAnywhereCachesResponse, + *, + 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.storage_control_v2.types.ListAnywhereCachesRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListAnywhereCachesResponse): + 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 = storage_control.ListAnywhereCachesRequest(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[storage_control.ListAnywhereCachesResponse]: + 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[storage_control.AnywhereCache]: + for page in self.pages: + yield from page.anywhere_caches + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAnywhereCachesAsyncPager: + """A pager for iterating through ``list_anywhere_caches`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListAnywhereCachesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``anywhere_caches`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAnywhereCaches`` requests and continue to iterate + through the ``anywhere_caches`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListAnywhereCachesResponse` + 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[storage_control.ListAnywhereCachesResponse]], + request: storage_control.ListAnywhereCachesRequest, + response: storage_control.ListAnywhereCachesResponse, + *, + 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.storage_control_v2.types.ListAnywhereCachesRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListAnywhereCachesResponse): + 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 = storage_control.ListAnywhereCachesRequest(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[storage_control.ListAnywhereCachesResponse]: + 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[storage_control.AnywhereCache]: + async def async_generator(): + async for page in self.pages: + for response in page.anywhere_caches: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3970dcea5737423b473ace65dd52b53ee2e7e16a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/__init__.py @@ -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 StorageControlTransport +from .grpc import StorageControlGrpcTransport +from .grpc_asyncio import StorageControlGrpcAsyncIOTransport +from .rest import StorageControlRestInterceptor, StorageControlRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StorageControlTransport]] +_transport_registry["grpc"] = StorageControlGrpcTransport +_transport_registry["grpc_asyncio"] = StorageControlGrpcAsyncIOTransport +_transport_registry["rest"] = StorageControlRestTransport + +__all__ = ( + "StorageControlTransport", + "StorageControlGrpcTransport", + "StorageControlGrpcAsyncIOTransport", + "StorageControlRestTransport", + "StorageControlRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..23c6ffef2be88a298b647354c9ea591812bbd37b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/base.py @@ -0,0 +1,857 @@ +# -*- 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 +import google.auth # type: ignore +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +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 +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.storage_control_v2 import gapic_version as package_version +from google.cloud.storage_control_v2.types import storage_control + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class StorageControlTransport(abc.ABC): + """Abstract transport class for StorageControl.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/devstorage.full_control", + "https://www.googleapis.com/auth/devstorage.read_only", + "https://www.googleapis.com/auth/devstorage.read_write", + ) + + DEFAULT_HOST: str = "storage.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: 'storage.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_folder: gapic_v1.method.wrap_method( + self.create_folder, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_folder: gapic_v1.method.wrap_method( + self.delete_folder, + default_timeout=None, + client_info=client_info, + ), + self.get_folder: gapic_v1.method.wrap_method( + self.get_folder, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_folders: gapic_v1.method.wrap_method( + self.list_folders, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.rename_folder: gapic_v1.method.wrap_method( + self.rename_folder, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_folder_recursive: gapic_v1.method.wrap_method( + self.delete_folder_recursive, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_storage_layout: gapic_v1.method.wrap_method( + self.get_storage_layout, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_managed_folder: gapic_v1.method.wrap_method( + self.create_managed_folder, + default_timeout=None, + client_info=client_info, + ), + self.delete_managed_folder: gapic_v1.method.wrap_method( + self.delete_managed_folder, + default_timeout=None, + client_info=client_info, + ), + self.get_managed_folder: gapic_v1.method.wrap_method( + self.get_managed_folder, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_managed_folders: gapic_v1.method.wrap_method( + self.list_managed_folders, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_anywhere_cache: gapic_v1.method.wrap_method( + self.create_anywhere_cache, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_anywhere_cache: gapic_v1.method.wrap_method( + self.update_anywhere_cache, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.disable_anywhere_cache: gapic_v1.method.wrap_method( + self.disable_anywhere_cache, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.pause_anywhere_cache: gapic_v1.method.wrap_method( + self.pause_anywhere_cache, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.resume_anywhere_cache: gapic_v1.method.wrap_method( + self.resume_anywhere_cache, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_anywhere_cache: gapic_v1.method.wrap_method( + self.get_anywhere_cache, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_anywhere_caches: gapic_v1.method.wrap_method( + self.list_anywhere_caches, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_project_intelligence_config: gapic_v1.method.wrap_method( + self.get_project_intelligence_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_project_intelligence_config: gapic_v1.method.wrap_method( + self.update_project_intelligence_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_folder_intelligence_config: gapic_v1.method.wrap_method( + self.get_folder_intelligence_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_folder_intelligence_config: gapic_v1.method.wrap_method( + self.update_folder_intelligence_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_intelligence_config: gapic_v1.method.wrap_method( + self.get_organization_intelligence_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_intelligence_config: gapic_v1.method.wrap_method( + self.update_organization_intelligence_config, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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 create_folder( + self, + ) -> Callable[ + [storage_control.CreateFolderRequest], + Union[storage_control.Folder, Awaitable[storage_control.Folder]], + ]: + raise NotImplementedError() + + @property + def delete_folder( + self, + ) -> Callable[ + [storage_control.DeleteFolderRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_folder( + self, + ) -> Callable[ + [storage_control.GetFolderRequest], + Union[storage_control.Folder, Awaitable[storage_control.Folder]], + ]: + raise NotImplementedError() + + @property + def list_folders( + self, + ) -> Callable[ + [storage_control.ListFoldersRequest], + Union[ + storage_control.ListFoldersResponse, + Awaitable[storage_control.ListFoldersResponse], + ], + ]: + raise NotImplementedError() + + @property + def rename_folder( + self, + ) -> Callable[ + [storage_control.RenameFolderRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_folder_recursive( + self, + ) -> Callable[ + [storage_control.DeleteFolderRecursiveRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_storage_layout( + self, + ) -> Callable[ + [storage_control.GetStorageLayoutRequest], + Union[storage_control.StorageLayout, Awaitable[storage_control.StorageLayout]], + ]: + raise NotImplementedError() + + @property + def create_managed_folder( + self, + ) -> Callable[ + [storage_control.CreateManagedFolderRequest], + Union[storage_control.ManagedFolder, Awaitable[storage_control.ManagedFolder]], + ]: + raise NotImplementedError() + + @property + def delete_managed_folder( + self, + ) -> Callable[ + [storage_control.DeleteManagedFolderRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_managed_folder( + self, + ) -> Callable[ + [storage_control.GetManagedFolderRequest], + Union[storage_control.ManagedFolder, Awaitable[storage_control.ManagedFolder]], + ]: + raise NotImplementedError() + + @property + def list_managed_folders( + self, + ) -> Callable[ + [storage_control.ListManagedFoldersRequest], + Union[ + storage_control.ListManagedFoldersResponse, + Awaitable[storage_control.ListManagedFoldersResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_anywhere_cache( + self, + ) -> Callable[ + [storage_control.CreateAnywhereCacheRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_anywhere_cache( + self, + ) -> Callable[ + [storage_control.UpdateAnywhereCacheRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def disable_anywhere_cache( + self, + ) -> Callable[ + [storage_control.DisableAnywhereCacheRequest], + Union[storage_control.AnywhereCache, Awaitable[storage_control.AnywhereCache]], + ]: + raise NotImplementedError() + + @property + def pause_anywhere_cache( + self, + ) -> Callable[ + [storage_control.PauseAnywhereCacheRequest], + Union[storage_control.AnywhereCache, Awaitable[storage_control.AnywhereCache]], + ]: + raise NotImplementedError() + + @property + def resume_anywhere_cache( + self, + ) -> Callable[ + [storage_control.ResumeAnywhereCacheRequest], + Union[storage_control.AnywhereCache, Awaitable[storage_control.AnywhereCache]], + ]: + raise NotImplementedError() + + @property + def get_anywhere_cache( + self, + ) -> Callable[ + [storage_control.GetAnywhereCacheRequest], + Union[storage_control.AnywhereCache, Awaitable[storage_control.AnywhereCache]], + ]: + raise NotImplementedError() + + @property + def list_anywhere_caches( + self, + ) -> Callable[ + [storage_control.ListAnywhereCachesRequest], + Union[ + storage_control.ListAnywhereCachesResponse, + Awaitable[storage_control.ListAnywhereCachesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetProjectIntelligenceConfigRequest], + Union[ + storage_control.IntelligenceConfig, + Awaitable[storage_control.IntelligenceConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateProjectIntelligenceConfigRequest], + Union[ + storage_control.IntelligenceConfig, + Awaitable[storage_control.IntelligenceConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetFolderIntelligenceConfigRequest], + Union[ + storage_control.IntelligenceConfig, + Awaitable[storage_control.IntelligenceConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateFolderIntelligenceConfigRequest], + Union[ + storage_control.IntelligenceConfig, + Awaitable[storage_control.IntelligenceConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetOrganizationIntelligenceConfigRequest], + Union[ + storage_control.IntelligenceConfig, + Awaitable[storage_control.IntelligenceConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateOrganizationIntelligenceConfigRequest], + Union[ + storage_control.IntelligenceConfig, + Awaitable[storage_control.IntelligenceConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("StorageControlTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..b8fe82ca7bd4d1dda8e5b866b9fff0c4f200625d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/grpc.py @@ -0,0 +1,1165 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.storage_control_v2.types import storage_control + +from .base import DEFAULT_CLIENT_INFO, StorageControlTransport + +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)!r}" + + 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.storage.control.v2.StorageControl", + "rpcName": str(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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class StorageControlGrpcTransport(StorageControlTransport): + """gRPC backend transport for StorageControl. + + StorageControl service includes selected control plane + operations. + + 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 = "storage.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: 'storage.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 = "storage.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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 create_folder( + self, + ) -> Callable[[storage_control.CreateFolderRequest], storage_control.Folder]: + r"""Return a callable for the create folder method over gRPC. + + Creates a new folder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Returns: + Callable[[~.CreateFolderRequest], + ~.Folder]: + 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_folder" not in self._stubs: + self._stubs["create_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/CreateFolder", + request_serializer=storage_control.CreateFolderRequest.serialize, + response_deserializer=storage_control.Folder.deserialize, + ) + return self._stubs["create_folder"] + + @property + def delete_folder( + self, + ) -> Callable[[storage_control.DeleteFolderRequest], empty_pb2.Empty]: + r"""Return a callable for the delete folder method over gRPC. + + Permanently deletes an empty folder. This operation + is only applicable to a hierarchical namespace enabled + bucket. + + Returns: + Callable[[~.DeleteFolderRequest], + ~.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_folder" not in self._stubs: + self._stubs["delete_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DeleteFolder", + request_serializer=storage_control.DeleteFolderRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_folder"] + + @property + def get_folder( + self, + ) -> Callable[[storage_control.GetFolderRequest], storage_control.Folder]: + r"""Return a callable for the get folder method over gRPC. + + Returns metadata for the specified folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. + + Returns: + Callable[[~.GetFolderRequest], + ~.Folder]: + 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_folder" not in self._stubs: + self._stubs["get_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetFolder", + request_serializer=storage_control.GetFolderRequest.serialize, + response_deserializer=storage_control.Folder.deserialize, + ) + return self._stubs["get_folder"] + + @property + def list_folders( + self, + ) -> Callable[ + [storage_control.ListFoldersRequest], storage_control.ListFoldersResponse + ]: + r"""Return a callable for the list folders method over gRPC. + + Retrieves a list of folders. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Returns: + Callable[[~.ListFoldersRequest], + ~.ListFoldersResponse]: + 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_folders" not in self._stubs: + self._stubs["list_folders"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListFolders", + request_serializer=storage_control.ListFoldersRequest.serialize, + response_deserializer=storage_control.ListFoldersResponse.deserialize, + ) + return self._stubs["list_folders"] + + @property + def rename_folder( + self, + ) -> Callable[[storage_control.RenameFolderRequest], operations_pb2.Operation]: + r"""Return a callable for the rename folder method over gRPC. + + Renames a source folder to a destination folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. During a rename, the source and + destination folders are locked until the long running + operation completes. + + Returns: + Callable[[~.RenameFolderRequest], + ~.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 "rename_folder" not in self._stubs: + self._stubs["rename_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/RenameFolder", + request_serializer=storage_control.RenameFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["rename_folder"] + + @property + def delete_folder_recursive( + self, + ) -> Callable[ + [storage_control.DeleteFolderRecursiveRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete folder recursive method over gRPC. + + Deletes a folder recursively. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Returns: + Callable[[~.DeleteFolderRecursiveRequest], + ~.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 "delete_folder_recursive" not in self._stubs: + self._stubs["delete_folder_recursive"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DeleteFolderRecursive", + request_serializer=storage_control.DeleteFolderRecursiveRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_folder_recursive"] + + @property + def get_storage_layout( + self, + ) -> Callable[ + [storage_control.GetStorageLayoutRequest], storage_control.StorageLayout + ]: + r"""Return a callable for the get storage layout method over gRPC. + + Returns the storage layout configuration for a given + bucket. + + Returns: + Callable[[~.GetStorageLayoutRequest], + ~.StorageLayout]: + 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_storage_layout" not in self._stubs: + self._stubs["get_storage_layout"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetStorageLayout", + request_serializer=storage_control.GetStorageLayoutRequest.serialize, + response_deserializer=storage_control.StorageLayout.deserialize, + ) + return self._stubs["get_storage_layout"] + + @property + def create_managed_folder( + self, + ) -> Callable[ + [storage_control.CreateManagedFolderRequest], storage_control.ManagedFolder + ]: + r"""Return a callable for the create managed folder method over gRPC. + + Creates a new managed folder. + + Returns: + Callable[[~.CreateManagedFolderRequest], + ~.ManagedFolder]: + 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_managed_folder" not in self._stubs: + self._stubs["create_managed_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/CreateManagedFolder", + request_serializer=storage_control.CreateManagedFolderRequest.serialize, + response_deserializer=storage_control.ManagedFolder.deserialize, + ) + return self._stubs["create_managed_folder"] + + @property + def delete_managed_folder( + self, + ) -> Callable[[storage_control.DeleteManagedFolderRequest], empty_pb2.Empty]: + r"""Return a callable for the delete managed folder method over gRPC. + + Permanently deletes an empty managed folder. + + Returns: + Callable[[~.DeleteManagedFolderRequest], + ~.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_managed_folder" not in self._stubs: + self._stubs["delete_managed_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DeleteManagedFolder", + request_serializer=storage_control.DeleteManagedFolderRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_managed_folder"] + + @property + def get_managed_folder( + self, + ) -> Callable[ + [storage_control.GetManagedFolderRequest], storage_control.ManagedFolder + ]: + r"""Return a callable for the get managed folder method over gRPC. + + Returns metadata for the specified managed folder. + + Returns: + Callable[[~.GetManagedFolderRequest], + ~.ManagedFolder]: + 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_managed_folder" not in self._stubs: + self._stubs["get_managed_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetManagedFolder", + request_serializer=storage_control.GetManagedFolderRequest.serialize, + response_deserializer=storage_control.ManagedFolder.deserialize, + ) + return self._stubs["get_managed_folder"] + + @property + def list_managed_folders( + self, + ) -> Callable[ + [storage_control.ListManagedFoldersRequest], + storage_control.ListManagedFoldersResponse, + ]: + r"""Return a callable for the list managed folders method over gRPC. + + Retrieves a list of managed folders for a given + bucket. + + Returns: + Callable[[~.ListManagedFoldersRequest], + ~.ListManagedFoldersResponse]: + 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_managed_folders" not in self._stubs: + self._stubs["list_managed_folders"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListManagedFolders", + request_serializer=storage_control.ListManagedFoldersRequest.serialize, + response_deserializer=storage_control.ListManagedFoldersResponse.deserialize, + ) + return self._stubs["list_managed_folders"] + + @property + def create_anywhere_cache( + self, + ) -> Callable[ + [storage_control.CreateAnywhereCacheRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create anywhere cache method over gRPC. + + Creates an Anywhere Cache instance. + + Returns: + Callable[[~.CreateAnywhereCacheRequest], + ~.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 "create_anywhere_cache" not in self._stubs: + self._stubs["create_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/CreateAnywhereCache", + request_serializer=storage_control.CreateAnywhereCacheRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_anywhere_cache"] + + @property + def update_anywhere_cache( + self, + ) -> Callable[ + [storage_control.UpdateAnywhereCacheRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update anywhere cache method over gRPC. + + Updates an Anywhere Cache instance. Mutable fields include + ``ttl`` and ``admission_policy``. + + Returns: + Callable[[~.UpdateAnywhereCacheRequest], + ~.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 "update_anywhere_cache" not in self._stubs: + self._stubs["update_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateAnywhereCache", + request_serializer=storage_control.UpdateAnywhereCacheRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_anywhere_cache"] + + @property + def disable_anywhere_cache( + self, + ) -> Callable[ + [storage_control.DisableAnywhereCacheRequest], storage_control.AnywhereCache + ]: + r"""Return a callable for the disable anywhere cache method over gRPC. + + Disables an Anywhere Cache instance. A disabled + instance is read-only. The disablement could be revoked + by calling ResumeAnywhereCache. The cache instance will + be deleted automatically if it remains in the disabled + state for at least one hour. + + Returns: + Callable[[~.DisableAnywhereCacheRequest], + ~.AnywhereCache]: + 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 "disable_anywhere_cache" not in self._stubs: + self._stubs["disable_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DisableAnywhereCache", + request_serializer=storage_control.DisableAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["disable_anywhere_cache"] + + @property + def pause_anywhere_cache( + self, + ) -> Callable[ + [storage_control.PauseAnywhereCacheRequest], storage_control.AnywhereCache + ]: + r"""Return a callable for the pause anywhere cache method over gRPC. + + Pauses an Anywhere Cache instance. + + Returns: + Callable[[~.PauseAnywhereCacheRequest], + ~.AnywhereCache]: + 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 "pause_anywhere_cache" not in self._stubs: + self._stubs["pause_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/PauseAnywhereCache", + request_serializer=storage_control.PauseAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["pause_anywhere_cache"] + + @property + def resume_anywhere_cache( + self, + ) -> Callable[ + [storage_control.ResumeAnywhereCacheRequest], storage_control.AnywhereCache + ]: + r"""Return a callable for the resume anywhere cache method over gRPC. + + Resumes a disabled or paused Anywhere Cache instance. + + Returns: + Callable[[~.ResumeAnywhereCacheRequest], + ~.AnywhereCache]: + 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 "resume_anywhere_cache" not in self._stubs: + self._stubs["resume_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ResumeAnywhereCache", + request_serializer=storage_control.ResumeAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["resume_anywhere_cache"] + + @property + def get_anywhere_cache( + self, + ) -> Callable[ + [storage_control.GetAnywhereCacheRequest], storage_control.AnywhereCache + ]: + r"""Return a callable for the get anywhere cache method over gRPC. + + Gets an Anywhere Cache instance. + + Returns: + Callable[[~.GetAnywhereCacheRequest], + ~.AnywhereCache]: + 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_anywhere_cache" not in self._stubs: + self._stubs["get_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetAnywhereCache", + request_serializer=storage_control.GetAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["get_anywhere_cache"] + + @property + def list_anywhere_caches( + self, + ) -> Callable[ + [storage_control.ListAnywhereCachesRequest], + storage_control.ListAnywhereCachesResponse, + ]: + r"""Return a callable for the list anywhere caches method over gRPC. + + Lists Anywhere Cache instances for a given bucket. + + Returns: + Callable[[~.ListAnywhereCachesRequest], + ~.ListAnywhereCachesResponse]: + 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_anywhere_caches" not in self._stubs: + self._stubs["list_anywhere_caches"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListAnywhereCaches", + request_serializer=storage_control.ListAnywhereCachesRequest.serialize, + response_deserializer=storage_control.ListAnywhereCachesResponse.deserialize, + ) + return self._stubs["list_anywhere_caches"] + + @property + def get_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetProjectIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + r"""Return a callable for the get project intelligence + config method over gRPC. + + Returns the Project scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.GetProjectIntelligenceConfigRequest], + ~.IntelligenceConfig]: + 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_project_intelligence_config" not in self._stubs: + self._stubs["get_project_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetProjectIntelligenceConfig", + request_serializer=storage_control.GetProjectIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["get_project_intelligence_config"] + + @property + def update_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateProjectIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + r"""Return a callable for the update project intelligence + config method over gRPC. + + Updates the Project scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.UpdateProjectIntelligenceConfigRequest], + ~.IntelligenceConfig]: + 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_project_intelligence_config" not in self._stubs: + self._stubs["update_project_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateProjectIntelligenceConfig", + request_serializer=storage_control.UpdateProjectIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["update_project_intelligence_config"] + + @property + def get_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetFolderIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + r"""Return a callable for the get folder intelligence config method over gRPC. + + Returns the Folder scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.GetFolderIntelligenceConfigRequest], + ~.IntelligenceConfig]: + 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_folder_intelligence_config" not in self._stubs: + self._stubs["get_folder_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetFolderIntelligenceConfig", + request_serializer=storage_control.GetFolderIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["get_folder_intelligence_config"] + + @property + def update_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateFolderIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + r"""Return a callable for the update folder intelligence + config method over gRPC. + + Updates the Folder scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.UpdateFolderIntelligenceConfigRequest], + ~.IntelligenceConfig]: + 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_folder_intelligence_config" not in self._stubs: + self._stubs["update_folder_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateFolderIntelligenceConfig", + request_serializer=storage_control.UpdateFolderIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["update_folder_intelligence_config"] + + @property + def get_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetOrganizationIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + r"""Return a callable for the get organization intelligence + config method over gRPC. + + Returns the Organization scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.GetOrganizationIntelligenceConfigRequest], + ~.IntelligenceConfig]: + 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_organization_intelligence_config" not in self._stubs: + self._stubs["get_organization_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetOrganizationIntelligenceConfig", + request_serializer=storage_control.GetOrganizationIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["get_organization_intelligence_config"] + + @property + def update_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateOrganizationIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + r"""Return a callable for the update organization + intelligence config method over gRPC. + + Updates the Organization scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.UpdateOrganizationIntelligenceConfigRequest], + ~.IntelligenceConfig]: + 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_organization_intelligence_config" not in self._stubs: + self._stubs["update_organization_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateOrganizationIntelligenceConfig", + request_serializer=storage_control.UpdateOrganizationIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["update_organization_intelligence_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy for a specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Updates an IAM policy for the specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests a set of permissions on the given bucket, object, or + managed folder to see which, if any, are held by the caller. The + ``resource`` field in the request should be + ``projects/_/buckets/{bucket}`` for a bucket, + ``projects/_/buckets/{bucket}/objects/{object}`` for an object, + or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("StorageControlGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..cba798586fa7706f6a60044779b5e77100b6610f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/grpc_asyncio.py @@ -0,0 +1,1610 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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 +from grpc.experimental import aio # type: ignore + +from google.cloud.storage_control_v2.types import storage_control + +from .base import DEFAULT_CLIENT_INFO, StorageControlTransport +from .grpc import StorageControlGrpcTransport + +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)!r}" + + 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.storage.control.v2.StorageControl", + "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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class StorageControlGrpcAsyncIOTransport(StorageControlTransport): + """gRPC AsyncIO backend transport for StorageControl. + + StorageControl service includes selected control plane + operations. + + 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 = "storage.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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 = "storage.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: 'storage.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 create_folder( + self, + ) -> Callable[ + [storage_control.CreateFolderRequest], Awaitable[storage_control.Folder] + ]: + r"""Return a callable for the create folder method over gRPC. + + Creates a new folder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Returns: + Callable[[~.CreateFolderRequest], + Awaitable[~.Folder]]: + 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_folder" not in self._stubs: + self._stubs["create_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/CreateFolder", + request_serializer=storage_control.CreateFolderRequest.serialize, + response_deserializer=storage_control.Folder.deserialize, + ) + return self._stubs["create_folder"] + + @property + def delete_folder( + self, + ) -> Callable[[storage_control.DeleteFolderRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete folder method over gRPC. + + Permanently deletes an empty folder. This operation + is only applicable to a hierarchical namespace enabled + bucket. + + Returns: + Callable[[~.DeleteFolderRequest], + 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_folder" not in self._stubs: + self._stubs["delete_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DeleteFolder", + request_serializer=storage_control.DeleteFolderRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_folder"] + + @property + def get_folder( + self, + ) -> Callable[ + [storage_control.GetFolderRequest], Awaitable[storage_control.Folder] + ]: + r"""Return a callable for the get folder method over gRPC. + + Returns metadata for the specified folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. + + Returns: + Callable[[~.GetFolderRequest], + Awaitable[~.Folder]]: + 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_folder" not in self._stubs: + self._stubs["get_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetFolder", + request_serializer=storage_control.GetFolderRequest.serialize, + response_deserializer=storage_control.Folder.deserialize, + ) + return self._stubs["get_folder"] + + @property + def list_folders( + self, + ) -> Callable[ + [storage_control.ListFoldersRequest], + Awaitable[storage_control.ListFoldersResponse], + ]: + r"""Return a callable for the list folders method over gRPC. + + Retrieves a list of folders. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Returns: + Callable[[~.ListFoldersRequest], + Awaitable[~.ListFoldersResponse]]: + 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_folders" not in self._stubs: + self._stubs["list_folders"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListFolders", + request_serializer=storage_control.ListFoldersRequest.serialize, + response_deserializer=storage_control.ListFoldersResponse.deserialize, + ) + return self._stubs["list_folders"] + + @property + def rename_folder( + self, + ) -> Callable[ + [storage_control.RenameFolderRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the rename folder method over gRPC. + + Renames a source folder to a destination folder. This + operation is only applicable to a hierarchical namespace + enabled bucket. During a rename, the source and + destination folders are locked until the long running + operation completes. + + Returns: + Callable[[~.RenameFolderRequest], + 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 "rename_folder" not in self._stubs: + self._stubs["rename_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/RenameFolder", + request_serializer=storage_control.RenameFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["rename_folder"] + + @property + def delete_folder_recursive( + self, + ) -> Callable[ + [storage_control.DeleteFolderRecursiveRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete folder recursive method over gRPC. + + Deletes a folder recursively. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Returns: + Callable[[~.DeleteFolderRecursiveRequest], + 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 "delete_folder_recursive" not in self._stubs: + self._stubs["delete_folder_recursive"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DeleteFolderRecursive", + request_serializer=storage_control.DeleteFolderRecursiveRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_folder_recursive"] + + @property + def get_storage_layout( + self, + ) -> Callable[ + [storage_control.GetStorageLayoutRequest], + Awaitable[storage_control.StorageLayout], + ]: + r"""Return a callable for the get storage layout method over gRPC. + + Returns the storage layout configuration for a given + bucket. + + Returns: + Callable[[~.GetStorageLayoutRequest], + Awaitable[~.StorageLayout]]: + 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_storage_layout" not in self._stubs: + self._stubs["get_storage_layout"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetStorageLayout", + request_serializer=storage_control.GetStorageLayoutRequest.serialize, + response_deserializer=storage_control.StorageLayout.deserialize, + ) + return self._stubs["get_storage_layout"] + + @property + def create_managed_folder( + self, + ) -> Callable[ + [storage_control.CreateManagedFolderRequest], + Awaitable[storage_control.ManagedFolder], + ]: + r"""Return a callable for the create managed folder method over gRPC. + + Creates a new managed folder. + + Returns: + Callable[[~.CreateManagedFolderRequest], + Awaitable[~.ManagedFolder]]: + 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_managed_folder" not in self._stubs: + self._stubs["create_managed_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/CreateManagedFolder", + request_serializer=storage_control.CreateManagedFolderRequest.serialize, + response_deserializer=storage_control.ManagedFolder.deserialize, + ) + return self._stubs["create_managed_folder"] + + @property + def delete_managed_folder( + self, + ) -> Callable[ + [storage_control.DeleteManagedFolderRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete managed folder method over gRPC. + + Permanently deletes an empty managed folder. + + Returns: + Callable[[~.DeleteManagedFolderRequest], + 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_managed_folder" not in self._stubs: + self._stubs["delete_managed_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DeleteManagedFolder", + request_serializer=storage_control.DeleteManagedFolderRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_managed_folder"] + + @property + def get_managed_folder( + self, + ) -> Callable[ + [storage_control.GetManagedFolderRequest], + Awaitable[storage_control.ManagedFolder], + ]: + r"""Return a callable for the get managed folder method over gRPC. + + Returns metadata for the specified managed folder. + + Returns: + Callable[[~.GetManagedFolderRequest], + Awaitable[~.ManagedFolder]]: + 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_managed_folder" not in self._stubs: + self._stubs["get_managed_folder"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetManagedFolder", + request_serializer=storage_control.GetManagedFolderRequest.serialize, + response_deserializer=storage_control.ManagedFolder.deserialize, + ) + return self._stubs["get_managed_folder"] + + @property + def list_managed_folders( + self, + ) -> Callable[ + [storage_control.ListManagedFoldersRequest], + Awaitable[storage_control.ListManagedFoldersResponse], + ]: + r"""Return a callable for the list managed folders method over gRPC. + + Retrieves a list of managed folders for a given + bucket. + + Returns: + Callable[[~.ListManagedFoldersRequest], + Awaitable[~.ListManagedFoldersResponse]]: + 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_managed_folders" not in self._stubs: + self._stubs["list_managed_folders"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListManagedFolders", + request_serializer=storage_control.ListManagedFoldersRequest.serialize, + response_deserializer=storage_control.ListManagedFoldersResponse.deserialize, + ) + return self._stubs["list_managed_folders"] + + @property + def create_anywhere_cache( + self, + ) -> Callable[ + [storage_control.CreateAnywhereCacheRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create anywhere cache method over gRPC. + + Creates an Anywhere Cache instance. + + Returns: + Callable[[~.CreateAnywhereCacheRequest], + 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 "create_anywhere_cache" not in self._stubs: + self._stubs["create_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/CreateAnywhereCache", + request_serializer=storage_control.CreateAnywhereCacheRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_anywhere_cache"] + + @property + def update_anywhere_cache( + self, + ) -> Callable[ + [storage_control.UpdateAnywhereCacheRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update anywhere cache method over gRPC. + + Updates an Anywhere Cache instance. Mutable fields include + ``ttl`` and ``admission_policy``. + + Returns: + Callable[[~.UpdateAnywhereCacheRequest], + 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 "update_anywhere_cache" not in self._stubs: + self._stubs["update_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateAnywhereCache", + request_serializer=storage_control.UpdateAnywhereCacheRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_anywhere_cache"] + + @property + def disable_anywhere_cache( + self, + ) -> Callable[ + [storage_control.DisableAnywhereCacheRequest], + Awaitable[storage_control.AnywhereCache], + ]: + r"""Return a callable for the disable anywhere cache method over gRPC. + + Disables an Anywhere Cache instance. A disabled + instance is read-only. The disablement could be revoked + by calling ResumeAnywhereCache. The cache instance will + be deleted automatically if it remains in the disabled + state for at least one hour. + + Returns: + Callable[[~.DisableAnywhereCacheRequest], + Awaitable[~.AnywhereCache]]: + 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 "disable_anywhere_cache" not in self._stubs: + self._stubs["disable_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DisableAnywhereCache", + request_serializer=storage_control.DisableAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["disable_anywhere_cache"] + + @property + def pause_anywhere_cache( + self, + ) -> Callable[ + [storage_control.PauseAnywhereCacheRequest], + Awaitable[storage_control.AnywhereCache], + ]: + r"""Return a callable for the pause anywhere cache method over gRPC. + + Pauses an Anywhere Cache instance. + + Returns: + Callable[[~.PauseAnywhereCacheRequest], + Awaitable[~.AnywhereCache]]: + 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 "pause_anywhere_cache" not in self._stubs: + self._stubs["pause_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/PauseAnywhereCache", + request_serializer=storage_control.PauseAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["pause_anywhere_cache"] + + @property + def resume_anywhere_cache( + self, + ) -> Callable[ + [storage_control.ResumeAnywhereCacheRequest], + Awaitable[storage_control.AnywhereCache], + ]: + r"""Return a callable for the resume anywhere cache method over gRPC. + + Resumes a disabled or paused Anywhere Cache instance. + + Returns: + Callable[[~.ResumeAnywhereCacheRequest], + Awaitable[~.AnywhereCache]]: + 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 "resume_anywhere_cache" not in self._stubs: + self._stubs["resume_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ResumeAnywhereCache", + request_serializer=storage_control.ResumeAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["resume_anywhere_cache"] + + @property + def get_anywhere_cache( + self, + ) -> Callable[ + [storage_control.GetAnywhereCacheRequest], + Awaitable[storage_control.AnywhereCache], + ]: + r"""Return a callable for the get anywhere cache method over gRPC. + + Gets an Anywhere Cache instance. + + Returns: + Callable[[~.GetAnywhereCacheRequest], + Awaitable[~.AnywhereCache]]: + 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_anywhere_cache" not in self._stubs: + self._stubs["get_anywhere_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetAnywhereCache", + request_serializer=storage_control.GetAnywhereCacheRequest.serialize, + response_deserializer=storage_control.AnywhereCache.deserialize, + ) + return self._stubs["get_anywhere_cache"] + + @property + def list_anywhere_caches( + self, + ) -> Callable[ + [storage_control.ListAnywhereCachesRequest], + Awaitable[storage_control.ListAnywhereCachesResponse], + ]: + r"""Return a callable for the list anywhere caches method over gRPC. + + Lists Anywhere Cache instances for a given bucket. + + Returns: + Callable[[~.ListAnywhereCachesRequest], + Awaitable[~.ListAnywhereCachesResponse]]: + 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_anywhere_caches" not in self._stubs: + self._stubs["list_anywhere_caches"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListAnywhereCaches", + request_serializer=storage_control.ListAnywhereCachesRequest.serialize, + response_deserializer=storage_control.ListAnywhereCachesResponse.deserialize, + ) + return self._stubs["list_anywhere_caches"] + + @property + def get_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetProjectIntelligenceConfigRequest], + Awaitable[storage_control.IntelligenceConfig], + ]: + r"""Return a callable for the get project intelligence + config method over gRPC. + + Returns the Project scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.GetProjectIntelligenceConfigRequest], + Awaitable[~.IntelligenceConfig]]: + 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_project_intelligence_config" not in self._stubs: + self._stubs["get_project_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetProjectIntelligenceConfig", + request_serializer=storage_control.GetProjectIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["get_project_intelligence_config"] + + @property + def update_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateProjectIntelligenceConfigRequest], + Awaitable[storage_control.IntelligenceConfig], + ]: + r"""Return a callable for the update project intelligence + config method over gRPC. + + Updates the Project scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.UpdateProjectIntelligenceConfigRequest], + Awaitable[~.IntelligenceConfig]]: + 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_project_intelligence_config" not in self._stubs: + self._stubs["update_project_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateProjectIntelligenceConfig", + request_serializer=storage_control.UpdateProjectIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["update_project_intelligence_config"] + + @property + def get_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetFolderIntelligenceConfigRequest], + Awaitable[storage_control.IntelligenceConfig], + ]: + r"""Return a callable for the get folder intelligence config method over gRPC. + + Returns the Folder scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.GetFolderIntelligenceConfigRequest], + Awaitable[~.IntelligenceConfig]]: + 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_folder_intelligence_config" not in self._stubs: + self._stubs["get_folder_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetFolderIntelligenceConfig", + request_serializer=storage_control.GetFolderIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["get_folder_intelligence_config"] + + @property + def update_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateFolderIntelligenceConfigRequest], + Awaitable[storage_control.IntelligenceConfig], + ]: + r"""Return a callable for the update folder intelligence + config method over gRPC. + + Updates the Folder scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.UpdateFolderIntelligenceConfigRequest], + Awaitable[~.IntelligenceConfig]]: + 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_folder_intelligence_config" not in self._stubs: + self._stubs["update_folder_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateFolderIntelligenceConfig", + request_serializer=storage_control.UpdateFolderIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["update_folder_intelligence_config"] + + @property + def get_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetOrganizationIntelligenceConfigRequest], + Awaitable[storage_control.IntelligenceConfig], + ]: + r"""Return a callable for the get organization intelligence + config method over gRPC. + + Returns the Organization scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.GetOrganizationIntelligenceConfigRequest], + Awaitable[~.IntelligenceConfig]]: + 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_organization_intelligence_config" not in self._stubs: + self._stubs["get_organization_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetOrganizationIntelligenceConfig", + request_serializer=storage_control.GetOrganizationIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["get_organization_intelligence_config"] + + @property + def update_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateOrganizationIntelligenceConfigRequest], + Awaitable[storage_control.IntelligenceConfig], + ]: + r"""Return a callable for the update organization + intelligence config method over gRPC. + + Updates the Organization scoped singleton + IntelligenceConfig resource. + + Returns: + Callable[[~.UpdateOrganizationIntelligenceConfigRequest], + Awaitable[~.IntelligenceConfig]]: + 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_organization_intelligence_config" not in self._stubs: + self._stubs["update_organization_intelligence_config"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/UpdateOrganizationIntelligenceConfig", + request_serializer=storage_control.UpdateOrganizationIntelligenceConfigRequest.serialize, + response_deserializer=storage_control.IntelligenceConfig.deserialize, + ) + ) + return self._stubs["update_organization_intelligence_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy for a specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Updates an IAM policy for the specified bucket. The ``resource`` + field in the request should be ``projects/_/buckets/{bucket}`` + for a bucket, or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests a set of permissions on the given bucket, object, or + managed folder to see which, if any, are held by the caller. The + ``resource`` field in the request should be + ``projects/_/buckets/{bucket}`` for a bucket, + ``projects/_/buckets/{bucket}/objects/{object}`` for an object, + or + ``projects/_/buckets/{bucket}/managedFolders/{managedFolder}`` + for a managed folder. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + 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_folder: self._wrap_method( + self.create_folder, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_folder: self._wrap_method( + self.delete_folder, + default_timeout=None, + client_info=client_info, + ), + self.get_folder: self._wrap_method( + self.get_folder, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_folders: self._wrap_method( + self.list_folders, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.rename_folder: self._wrap_method( + self.rename_folder, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_folder_recursive: self._wrap_method( + self.delete_folder_recursive, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_storage_layout: self._wrap_method( + self.get_storage_layout, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_managed_folder: self._wrap_method( + self.create_managed_folder, + default_timeout=None, + client_info=client_info, + ), + self.delete_managed_folder: self._wrap_method( + self.delete_managed_folder, + default_timeout=None, + client_info=client_info, + ), + self.get_managed_folder: self._wrap_method( + self.get_managed_folder, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_managed_folders: self._wrap_method( + self.list_managed_folders, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_anywhere_cache: self._wrap_method( + self.create_anywhere_cache, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_anywhere_cache: self._wrap_method( + self.update_anywhere_cache, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.disable_anywhere_cache: self._wrap_method( + self.disable_anywhere_cache, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.pause_anywhere_cache: self._wrap_method( + self.pause_anywhere_cache, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.resume_anywhere_cache: self._wrap_method( + self.resume_anywhere_cache, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_anywhere_cache: self._wrap_method( + self.get_anywhere_cache, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_anywhere_caches: self._wrap_method( + self.list_anywhere_caches, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_project_intelligence_config: self._wrap_method( + self.get_project_intelligence_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_project_intelligence_config: self._wrap_method( + self.update_project_intelligence_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_folder_intelligence_config: self._wrap_method( + self.get_folder_intelligence_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_folder_intelligence_config: self._wrap_method( + self.update_folder_intelligence_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_intelligence_config: self._wrap_method( + self.get_organization_intelligence_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_intelligence_config: self._wrap_method( + self.update_organization_intelligence_config, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + 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" + + +__all__ = ("StorageControlGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..95344f108ae4b993273252ad9281b2a585e8ff6c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/rest.py @@ -0,0 +1,2376 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.storage_control_v2.types import storage_control + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseStorageControlRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class StorageControlRestInterceptor: + """Interceptor for StorageControl. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the StorageControlRestTransport. + + .. code-block:: python + class MyCustomStorageControlInterceptor(StorageControlRestInterceptor): + def pre_create_anywhere_cache(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_anywhere_cache(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_managed_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_managed_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_folder_recursive(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_folder_recursive(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_managed_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_disable_anywhere_cache(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_anywhere_cache(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_anywhere_cache(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_anywhere_cache(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_folder_intelligence_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_folder_intelligence_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_managed_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_managed_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization_intelligence_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization_intelligence_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_project_intelligence_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_project_intelligence_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_storage_layout(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_storage_layout(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_anywhere_caches(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_anywhere_caches(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_folders(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_folders(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_managed_folders(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_managed_folders(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_pause_anywhere_cache(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_pause_anywhere_cache(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rename_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rename_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_resume_anywhere_cache(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_resume_anywhere_cache(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_anywhere_cache(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_anywhere_cache(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_folder_intelligence_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_folder_intelligence_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_organization_intelligence_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_organization_intelligence_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_project_intelligence_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_project_intelligence_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = StorageControlRestTransport(interceptor=MyCustomStorageControlInterceptor()) + client = StorageControlClient(transport=transport) + + + """ + + def pre_get_folder_intelligence_config( + self, + request: storage_control.GetFolderIntelligenceConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.GetFolderIntelligenceConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_folder_intelligence_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_get_folder_intelligence_config( + self, response: storage_control.IntelligenceConfig + ) -> storage_control.IntelligenceConfig: + """Post-rpc interceptor for get_folder_intelligence_config + + DEPRECATED. Please use the `post_get_folder_intelligence_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_get_folder_intelligence_config` interceptor runs + before the `post_get_folder_intelligence_config_with_metadata` interceptor. + """ + return response + + def post_get_folder_intelligence_config_with_metadata( + self, + response: storage_control.IntelligenceConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_folder_intelligence_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_get_folder_intelligence_config_with_metadata` + interceptor in new development instead of the `post_get_folder_intelligence_config` interceptor. + When both interceptors are used, this `post_get_folder_intelligence_config_with_metadata` interceptor runs after the + `post_get_folder_intelligence_config` interceptor. The (possibly modified) response returned by + `post_get_folder_intelligence_config` will be passed to + `post_get_folder_intelligence_config_with_metadata`. + """ + return response, metadata + + def pre_get_organization_intelligence_config( + self, + request: storage_control.GetOrganizationIntelligenceConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.GetOrganizationIntelligenceConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_organization_intelligence_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_get_organization_intelligence_config( + self, response: storage_control.IntelligenceConfig + ) -> storage_control.IntelligenceConfig: + """Post-rpc interceptor for get_organization_intelligence_config + + DEPRECATED. Please use the `post_get_organization_intelligence_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_get_organization_intelligence_config` interceptor runs + before the `post_get_organization_intelligence_config_with_metadata` interceptor. + """ + return response + + def post_get_organization_intelligence_config_with_metadata( + self, + response: storage_control.IntelligenceConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_organization_intelligence_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_get_organization_intelligence_config_with_metadata` + interceptor in new development instead of the `post_get_organization_intelligence_config` interceptor. + When both interceptors are used, this `post_get_organization_intelligence_config_with_metadata` interceptor runs after the + `post_get_organization_intelligence_config` interceptor. The (possibly modified) response returned by + `post_get_organization_intelligence_config` will be passed to + `post_get_organization_intelligence_config_with_metadata`. + """ + return response, metadata + + def pre_get_project_intelligence_config( + self, + request: storage_control.GetProjectIntelligenceConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.GetProjectIntelligenceConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_project_intelligence_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_get_project_intelligence_config( + self, response: storage_control.IntelligenceConfig + ) -> storage_control.IntelligenceConfig: + """Post-rpc interceptor for get_project_intelligence_config + + DEPRECATED. Please use the `post_get_project_intelligence_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_get_project_intelligence_config` interceptor runs + before the `post_get_project_intelligence_config_with_metadata` interceptor. + """ + return response + + def post_get_project_intelligence_config_with_metadata( + self, + response: storage_control.IntelligenceConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_project_intelligence_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_get_project_intelligence_config_with_metadata` + interceptor in new development instead of the `post_get_project_intelligence_config` interceptor. + When both interceptors are used, this `post_get_project_intelligence_config_with_metadata` interceptor runs after the + `post_get_project_intelligence_config` interceptor. The (possibly modified) response returned by + `post_get_project_intelligence_config` will be passed to + `post_get_project_intelligence_config_with_metadata`. + """ + return response, metadata + + def pre_update_folder_intelligence_config( + self, + request: storage_control.UpdateFolderIntelligenceConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.UpdateFolderIntelligenceConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_folder_intelligence_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_update_folder_intelligence_config( + self, response: storage_control.IntelligenceConfig + ) -> storage_control.IntelligenceConfig: + """Post-rpc interceptor for update_folder_intelligence_config + + DEPRECATED. Please use the `post_update_folder_intelligence_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_update_folder_intelligence_config` interceptor runs + before the `post_update_folder_intelligence_config_with_metadata` interceptor. + """ + return response + + def post_update_folder_intelligence_config_with_metadata( + self, + response: storage_control.IntelligenceConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_folder_intelligence_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_update_folder_intelligence_config_with_metadata` + interceptor in new development instead of the `post_update_folder_intelligence_config` interceptor. + When both interceptors are used, this `post_update_folder_intelligence_config_with_metadata` interceptor runs after the + `post_update_folder_intelligence_config` interceptor. The (possibly modified) response returned by + `post_update_folder_intelligence_config` will be passed to + `post_update_folder_intelligence_config_with_metadata`. + """ + return response, metadata + + def pre_update_organization_intelligence_config( + self, + request: storage_control.UpdateOrganizationIntelligenceConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.UpdateOrganizationIntelligenceConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_organization_intelligence_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_update_organization_intelligence_config( + self, response: storage_control.IntelligenceConfig + ) -> storage_control.IntelligenceConfig: + """Post-rpc interceptor for update_organization_intelligence_config + + DEPRECATED. Please use the `post_update_organization_intelligence_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_update_organization_intelligence_config` interceptor runs + before the `post_update_organization_intelligence_config_with_metadata` interceptor. + """ + return response + + def post_update_organization_intelligence_config_with_metadata( + self, + response: storage_control.IntelligenceConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_organization_intelligence_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_update_organization_intelligence_config_with_metadata` + interceptor in new development instead of the `post_update_organization_intelligence_config` interceptor. + When both interceptors are used, this `post_update_organization_intelligence_config_with_metadata` interceptor runs after the + `post_update_organization_intelligence_config` interceptor. The (possibly modified) response returned by + `post_update_organization_intelligence_config` will be passed to + `post_update_organization_intelligence_config_with_metadata`. + """ + return response, metadata + + def pre_update_project_intelligence_config( + self, + request: storage_control.UpdateProjectIntelligenceConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.UpdateProjectIntelligenceConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_project_intelligence_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_update_project_intelligence_config( + self, response: storage_control.IntelligenceConfig + ) -> storage_control.IntelligenceConfig: + """Post-rpc interceptor for update_project_intelligence_config + + DEPRECATED. Please use the `post_update_project_intelligence_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_update_project_intelligence_config` interceptor runs + before the `post_update_project_intelligence_config_with_metadata` interceptor. + """ + return response + + def post_update_project_intelligence_config_with_metadata( + self, + response: storage_control.IntelligenceConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_project_intelligence_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_update_project_intelligence_config_with_metadata` + interceptor in new development instead of the `post_update_project_intelligence_config` interceptor. + When both interceptors are used, this `post_update_project_intelligence_config_with_metadata` interceptor runs after the + `post_update_project_intelligence_config` interceptor. The (possibly modified) response returned by + `post_update_project_intelligence_config` will be passed to + `post_update_project_intelligence_config_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class StorageControlRestStub: + _session: AuthorizedSession + _host: str + _interceptor: StorageControlRestInterceptor + + +class StorageControlRestTransport(_BaseStorageControlRestTransport): + """REST backend synchronous transport for StorageControl. + + StorageControl service includes selected control plane + operations. + + 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 = "storage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[StorageControlRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'storage.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[StorageControlRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or StorageControlRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = {} + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateAnywhereCache( + _BaseStorageControlRestTransport._BaseCreateAnywhereCache, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.CreateAnywhereCache") + + def __call__( + self, + request: storage_control.CreateAnywhereCacheRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + raise NotImplementedError( + "Method CreateAnywhereCache is not available over REST transport" + ) + + class _CreateFolder( + _BaseStorageControlRestTransport._BaseCreateFolder, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.CreateFolder") + + def __call__( + self, + request: storage_control.CreateFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.Folder: + raise NotImplementedError( + "Method CreateFolder is not available over REST transport" + ) + + class _CreateManagedFolder( + _BaseStorageControlRestTransport._BaseCreateManagedFolder, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.CreateManagedFolder") + + def __call__( + self, + request: storage_control.CreateManagedFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ManagedFolder: + raise NotImplementedError( + "Method CreateManagedFolder is not available over REST transport" + ) + + class _DeleteFolder( + _BaseStorageControlRestTransport._BaseDeleteFolder, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.DeleteFolder") + + def __call__( + self, + request: storage_control.DeleteFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + raise NotImplementedError( + "Method DeleteFolder is not available over REST transport" + ) + + class _DeleteFolderRecursive( + _BaseStorageControlRestTransport._BaseDeleteFolderRecursive, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.DeleteFolderRecursive") + + def __call__( + self, + request: storage_control.DeleteFolderRecursiveRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + raise NotImplementedError( + "Method DeleteFolderRecursive is not available over REST transport" + ) + + class _DeleteManagedFolder( + _BaseStorageControlRestTransport._BaseDeleteManagedFolder, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.DeleteManagedFolder") + + def __call__( + self, + request: storage_control.DeleteManagedFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + raise NotImplementedError( + "Method DeleteManagedFolder is not available over REST transport" + ) + + class _DisableAnywhereCache( + _BaseStorageControlRestTransport._BaseDisableAnywhereCache, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.DisableAnywhereCache") + + def __call__( + self, + request: storage_control.DisableAnywhereCacheRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + raise NotImplementedError( + "Method DisableAnywhereCache is not available over REST transport" + ) + + class _GetAnywhereCache( + _BaseStorageControlRestTransport._BaseGetAnywhereCache, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetAnywhereCache") + + def __call__( + self, + request: storage_control.GetAnywhereCacheRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + raise NotImplementedError( + "Method GetAnywhereCache is not available over REST transport" + ) + + class _GetFolder( + _BaseStorageControlRestTransport._BaseGetFolder, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetFolder") + + def __call__( + self, + request: storage_control.GetFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.Folder: + raise NotImplementedError( + "Method GetFolder is not available over REST transport" + ) + + class _GetFolderIntelligenceConfig( + _BaseStorageControlRestTransport._BaseGetFolderIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetFolderIntelligenceConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: storage_control.GetFolderIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the get folder intelligence + config method over HTTP. + + Args: + request (~.storage_control.GetFolderIntelligenceConfigRequest): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your folder. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the folder. + 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`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseGetFolderIntelligenceConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_folder_intelligence_config( + request, metadata + ) + transcoded_request = _BaseStorageControlRestTransport._BaseGetFolderIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseGetFolderIntelligenceConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.storage.control_v2.StorageControlClient.GetFolderIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetFolderIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + StorageControlRestTransport._GetFolderIntelligenceConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storage_control.IntelligenceConfig() + pb_resp = storage_control.IntelligenceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_folder_intelligence_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_folder_intelligence_config_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceConfig.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.storage.control_v2.StorageControlClient.get_folder_intelligence_config", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetFolderIntelligenceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetIamPolicy( + _BaseStorageControlRestTransport._BaseGetIamPolicy, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetIamPolicy") + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + raise NotImplementedError( + "Method GetIamPolicy is not available over REST transport" + ) + + class _GetManagedFolder( + _BaseStorageControlRestTransport._BaseGetManagedFolder, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetManagedFolder") + + def __call__( + self, + request: storage_control.GetManagedFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ManagedFolder: + raise NotImplementedError( + "Method GetManagedFolder is not available over REST transport" + ) + + class _GetOrganizationIntelligenceConfig( + _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetOrganizationIntelligenceConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: storage_control.GetOrganizationIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the get organization + intelligence config method over HTTP. + + Args: + request (~.storage_control.GetOrganizationIntelligenceConfigRequest): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your organization. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the organization. + 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`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_organization_intelligence_config( + request, metadata + ) + ) + transcoded_request = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.storage.control_v2.StorageControlClient.GetOrganizationIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetOrganizationIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._GetOrganizationIntelligenceConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storage_control.IntelligenceConfig() + pb_resp = storage_control.IntelligenceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_organization_intelligence_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_organization_intelligence_config_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceConfig.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.storage.control_v2.StorageControlClient.get_organization_intelligence_config", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetOrganizationIntelligenceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetProjectIntelligenceConfig( + _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetProjectIntelligenceConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: storage_control.GetProjectIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the get project intelligence + config method over HTTP. + + Args: + request (~.storage_control.GetProjectIntelligenceConfigRequest): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the project. + 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`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_project_intelligence_config( + request, metadata + ) + transcoded_request = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.storage.control_v2.StorageControlClient.GetProjectIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetProjectIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + StorageControlRestTransport._GetProjectIntelligenceConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storage_control.IntelligenceConfig() + pb_resp = storage_control.IntelligenceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_project_intelligence_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_project_intelligence_config_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceConfig.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.storage.control_v2.StorageControlClient.get_project_intelligence_config", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetProjectIntelligenceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetStorageLayout( + _BaseStorageControlRestTransport._BaseGetStorageLayout, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetStorageLayout") + + def __call__( + self, + request: storage_control.GetStorageLayoutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.StorageLayout: + raise NotImplementedError( + "Method GetStorageLayout is not available over REST transport" + ) + + class _ListAnywhereCaches( + _BaseStorageControlRestTransport._BaseListAnywhereCaches, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.ListAnywhereCaches") + + def __call__( + self, + request: storage_control.ListAnywhereCachesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ListAnywhereCachesResponse: + raise NotImplementedError( + "Method ListAnywhereCaches is not available over REST transport" + ) + + class _ListFolders( + _BaseStorageControlRestTransport._BaseListFolders, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.ListFolders") + + def __call__( + self, + request: storage_control.ListFoldersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ListFoldersResponse: + raise NotImplementedError( + "Method ListFolders is not available over REST transport" + ) + + class _ListManagedFolders( + _BaseStorageControlRestTransport._BaseListManagedFolders, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.ListManagedFolders") + + def __call__( + self, + request: storage_control.ListManagedFoldersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ListManagedFoldersResponse: + raise NotImplementedError( + "Method ListManagedFolders is not available over REST transport" + ) + + class _PauseAnywhereCache( + _BaseStorageControlRestTransport._BasePauseAnywhereCache, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.PauseAnywhereCache") + + def __call__( + self, + request: storage_control.PauseAnywhereCacheRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + raise NotImplementedError( + "Method PauseAnywhereCache is not available over REST transport" + ) + + class _RenameFolder( + _BaseStorageControlRestTransport._BaseRenameFolder, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.RenameFolder") + + def __call__( + self, + request: storage_control.RenameFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + raise NotImplementedError( + "Method RenameFolder is not available over REST transport" + ) + + class _ResumeAnywhereCache( + _BaseStorageControlRestTransport._BaseResumeAnywhereCache, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.ResumeAnywhereCache") + + def __call__( + self, + request: storage_control.ResumeAnywhereCacheRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.AnywhereCache: + raise NotImplementedError( + "Method ResumeAnywhereCache is not available over REST transport" + ) + + class _SetIamPolicy( + _BaseStorageControlRestTransport._BaseSetIamPolicy, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.SetIamPolicy") + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + raise NotImplementedError( + "Method SetIamPolicy is not available over REST transport" + ) + + class _TestIamPermissions( + _BaseStorageControlRestTransport._BaseTestIamPermissions, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.TestIamPermissions") + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + raise NotImplementedError( + "Method TestIamPermissions is not available over REST transport" + ) + + class _UpdateAnywhereCache( + _BaseStorageControlRestTransport._BaseUpdateAnywhereCache, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.UpdateAnywhereCache") + + def __call__( + self, + request: storage_control.UpdateAnywhereCacheRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + raise NotImplementedError( + "Method UpdateAnywhereCache is not available over REST transport" + ) + + class _UpdateFolderIntelligenceConfig( + _BaseStorageControlRestTransport._BaseUpdateFolderIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.UpdateFolderIntelligenceConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: storage_control.UpdateFolderIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the update folder + intelligence config method over HTTP. + + Args: + request (~.storage_control.UpdateFolderIntelligenceConfigRequest): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your folder. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + 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`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseUpdateFolderIntelligenceConfig._get_http_options() + + request, metadata = self._interceptor.pre_update_folder_intelligence_config( + request, metadata + ) + transcoded_request = _BaseStorageControlRestTransport._BaseUpdateFolderIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseStorageControlRestTransport._BaseUpdateFolderIntelligenceConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseUpdateFolderIntelligenceConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.storage.control_v2.StorageControlClient.UpdateFolderIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "UpdateFolderIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._UpdateFolderIntelligenceConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storage_control.IntelligenceConfig() + pb_resp = storage_control.IntelligenceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_folder_intelligence_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_folder_intelligence_config_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceConfig.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.storage.control_v2.StorageControlClient.update_folder_intelligence_config", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "UpdateFolderIntelligenceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateOrganizationIntelligenceConfig( + _BaseStorageControlRestTransport._BaseUpdateOrganizationIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash( + "StorageControlRestTransport.UpdateOrganizationIntelligenceConfig" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: storage_control.UpdateOrganizationIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the update organization + intelligence config method over HTTP. + + Args: + request (~.storage_control.UpdateOrganizationIntelligenceConfigRequest): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your organization. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the organization. + 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`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseUpdateOrganizationIntelligenceConfig._get_http_options() + + request, metadata = ( + self._interceptor.pre_update_organization_intelligence_config( + request, metadata + ) + ) + transcoded_request = _BaseStorageControlRestTransport._BaseUpdateOrganizationIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseStorageControlRestTransport._BaseUpdateOrganizationIntelligenceConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseUpdateOrganizationIntelligenceConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.storage.control_v2.StorageControlClient.UpdateOrganizationIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "UpdateOrganizationIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._UpdateOrganizationIntelligenceConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storage_control.IntelligenceConfig() + pb_resp = storage_control.IntelligenceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_organization_intelligence_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_organization_intelligence_config_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceConfig.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.storage.control_v2.StorageControlClient.update_organization_intelligence_config", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "UpdateOrganizationIntelligenceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateProjectIntelligenceConfig( + _BaseStorageControlRestTransport._BaseUpdateProjectIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.UpdateProjectIntelligenceConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: storage_control.UpdateProjectIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the update project + intelligence config method over HTTP. + + Args: + request (~.storage_control.UpdateProjectIntelligenceConfigRequest): + The request object. Request message to update the ``IntelligenceConfig`` + resource associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + 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`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseUpdateProjectIntelligenceConfig._get_http_options() + + request, metadata = ( + self._interceptor.pre_update_project_intelligence_config( + request, metadata + ) + ) + transcoded_request = _BaseStorageControlRestTransport._BaseUpdateProjectIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseStorageControlRestTransport._BaseUpdateProjectIntelligenceConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseUpdateProjectIntelligenceConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.storage.control_v2.StorageControlClient.UpdateProjectIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "UpdateProjectIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._UpdateProjectIntelligenceConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = storage_control.IntelligenceConfig() + pb_resp = storage_control.IntelligenceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_project_intelligence_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_project_intelligence_config_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceConfig.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.storage.control_v2.StorageControlClient.update_project_intelligence_config", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "UpdateProjectIntelligenceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_anywhere_cache( + self, + ) -> Callable[ + [storage_control.CreateAnywhereCacheRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAnywhereCache(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_folder( + self, + ) -> Callable[[storage_control.CreateFolderRequest], storage_control.Folder]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_managed_folder( + self, + ) -> Callable[ + [storage_control.CreateManagedFolderRequest], storage_control.ManagedFolder + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateManagedFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_folder( + self, + ) -> Callable[[storage_control.DeleteFolderRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_folder_recursive( + self, + ) -> Callable[ + [storage_control.DeleteFolderRecursiveRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFolderRecursive(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_managed_folder( + self, + ) -> Callable[[storage_control.DeleteManagedFolderRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteManagedFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def disable_anywhere_cache( + self, + ) -> Callable[ + [storage_control.DisableAnywhereCacheRequest], storage_control.AnywhereCache + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DisableAnywhereCache(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_anywhere_cache( + self, + ) -> Callable[ + [storage_control.GetAnywhereCacheRequest], storage_control.AnywhereCache + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAnywhereCache(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_folder( + self, + ) -> Callable[[storage_control.GetFolderRequest], storage_control.Folder]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetFolderIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFolderIntelligenceConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_managed_folder( + self, + ) -> Callable[ + [storage_control.GetManagedFolderRequest], storage_control.ManagedFolder + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetManagedFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetOrganizationIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganizationIntelligenceConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.GetProjectIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProjectIntelligenceConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_storage_layout( + self, + ) -> Callable[ + [storage_control.GetStorageLayoutRequest], storage_control.StorageLayout + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetStorageLayout(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_anywhere_caches( + self, + ) -> Callable[ + [storage_control.ListAnywhereCachesRequest], + storage_control.ListAnywhereCachesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAnywhereCaches(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_folders( + self, + ) -> Callable[ + [storage_control.ListFoldersRequest], storage_control.ListFoldersResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFolders(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_managed_folders( + self, + ) -> Callable[ + [storage_control.ListManagedFoldersRequest], + storage_control.ListManagedFoldersResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListManagedFolders(self._session, self._host, self._interceptor) # type: ignore + + @property + def pause_anywhere_cache( + self, + ) -> Callable[ + [storage_control.PauseAnywhereCacheRequest], storage_control.AnywhereCache + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PauseAnywhereCache(self._session, self._host, self._interceptor) # type: ignore + + @property + def rename_folder( + self, + ) -> Callable[[storage_control.RenameFolderRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RenameFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def resume_anywhere_cache( + self, + ) -> Callable[ + [storage_control.ResumeAnywhereCacheRequest], storage_control.AnywhereCache + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ResumeAnywhereCache(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_anywhere_cache( + self, + ) -> Callable[ + [storage_control.UpdateAnywhereCacheRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAnywhereCache(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_folder_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateFolderIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFolderIntelligenceConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_organization_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateOrganizationIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOrganizationIntelligenceConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_project_intelligence_config( + self, + ) -> Callable[ + [storage_control.UpdateProjectIntelligenceConfigRequest], + storage_control.IntelligenceConfig, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateProjectIntelligenceConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("StorageControlRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..db44a569993fbd2091e042446921d881147e57de --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/services/storage_control/transports/rest_base.py @@ -0,0 +1,505 @@ +# -*- 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 + +import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore +import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +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.storage_control_v2.types import storage_control + +from .base import DEFAULT_CLIENT_INFO, StorageControlTransport + + +class _BaseStorageControlRestTransport(StorageControlTransport): + """Base REST backend transport for StorageControl. + + 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 = "storage.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: 'storage.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("^(?Phttp(?:s)?://)?(?P.*)$", 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 _BaseCreateAnywhereCache: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseCreateFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseCreateManagedFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseDeleteFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseDeleteFolderRecursive: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseDeleteManagedFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseDisableAnywhereCache: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseGetAnywhereCache: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseGetFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseGetFolderIntelligenceConfig: + 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": "/v2/{name=folders/*/locations/*/intelligenceConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.GetFolderIntelligenceConfigRequest.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( + _BaseStorageControlRestTransport._BaseGetFolderIntelligenceConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseGetManagedFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseGetOrganizationIntelligenceConfig: + 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": "/v2/{name=organizations/*/locations/*/intelligenceConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.GetOrganizationIntelligenceConfigRequest.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( + _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProjectIntelligenceConfig: + 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": "/v2/{name=projects/*/locations/*/intelligenceConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.GetProjectIntelligenceConfigRequest.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( + _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetStorageLayout: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseListAnywhereCaches: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseListFolders: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseListManagedFolders: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BasePauseAnywhereCache: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseRenameFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseResumeAnywhereCache: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseUpdateAnywhereCache: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseUpdateFolderIntelligenceConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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": "/v2/{intelligence_config.name=folders/*/locations/*/intelligenceConfig}", + "body": "intelligence_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.UpdateFolderIntelligenceConfigRequest.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( + _BaseStorageControlRestTransport._BaseUpdateFolderIntelligenceConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateOrganizationIntelligenceConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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": "/v2/{intelligence_config.name=organizations/*/locations/*/intelligenceConfig}", + "body": "intelligence_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.UpdateOrganizationIntelligenceConfigRequest.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( + _BaseStorageControlRestTransport._BaseUpdateOrganizationIntelligenceConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateProjectIntelligenceConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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": "/v2/{intelligence_config.name=projects/*/locations/*/intelligenceConfig}", + "body": "intelligence_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.UpdateProjectIntelligenceConfigRequest.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( + _BaseStorageControlRestTransport._BaseUpdateProjectIntelligenceConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseStorageControlRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04ae24cb53f4c133d2fc984b0a73898e05917617 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/types/__init__.py @@ -0,0 +1,96 @@ +# -*- 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 .storage_control import ( + AnywhereCache, + CommonLongRunningOperationMetadata, + CreateAnywhereCacheMetadata, + CreateAnywhereCacheRequest, + CreateFolderRequest, + CreateManagedFolderRequest, + DeleteFolderRecursiveMetadata, + DeleteFolderRecursiveRequest, + DeleteFolderRequest, + DeleteManagedFolderRequest, + DisableAnywhereCacheRequest, + Folder, + GetAnywhereCacheRequest, + GetFolderIntelligenceConfigRequest, + GetFolderRequest, + GetManagedFolderRequest, + GetOrganizationIntelligenceConfigRequest, + GetProjectIntelligenceConfigRequest, + GetStorageLayoutRequest, + IntelligenceConfig, + ListAnywhereCachesRequest, + ListAnywhereCachesResponse, + ListFoldersRequest, + ListFoldersResponse, + ListManagedFoldersRequest, + ListManagedFoldersResponse, + ManagedFolder, + PauseAnywhereCacheRequest, + PendingRenameInfo, + RenameFolderMetadata, + RenameFolderRequest, + ResumeAnywhereCacheRequest, + StorageLayout, + UpdateAnywhereCacheMetadata, + UpdateAnywhereCacheRequest, + UpdateFolderIntelligenceConfigRequest, + UpdateOrganizationIntelligenceConfigRequest, + UpdateProjectIntelligenceConfigRequest, +) + +__all__ = ( + "AnywhereCache", + "CommonLongRunningOperationMetadata", + "CreateAnywhereCacheMetadata", + "CreateAnywhereCacheRequest", + "CreateFolderRequest", + "CreateManagedFolderRequest", + "DeleteFolderRecursiveMetadata", + "DeleteFolderRecursiveRequest", + "DeleteFolderRequest", + "DeleteManagedFolderRequest", + "DisableAnywhereCacheRequest", + "Folder", + "GetAnywhereCacheRequest", + "GetFolderIntelligenceConfigRequest", + "GetFolderRequest", + "GetManagedFolderRequest", + "GetOrganizationIntelligenceConfigRequest", + "GetProjectIntelligenceConfigRequest", + "GetStorageLayoutRequest", + "IntelligenceConfig", + "ListAnywhereCachesRequest", + "ListAnywhereCachesResponse", + "ListFoldersRequest", + "ListFoldersResponse", + "ListManagedFoldersRequest", + "ListManagedFoldersResponse", + "ManagedFolder", + "PauseAnywhereCacheRequest", + "PendingRenameInfo", + "RenameFolderMetadata", + "RenameFolderRequest", + "ResumeAnywhereCacheRequest", + "StorageLayout", + "UpdateAnywhereCacheMetadata", + "UpdateAnywhereCacheRequest", + "UpdateFolderIntelligenceConfigRequest", + "UpdateOrganizationIntelligenceConfigRequest", + "UpdateProjectIntelligenceConfigRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/types/storage_control.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/types/storage_control.py new file mode 100644 index 0000000000000000000000000000000000000000..64443f208aafa6ae79f74400c57cc10d4bd3f1e0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage_control_v2/types/storage_control.py @@ -0,0 +1,1849 @@ +# -*- 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 + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.storage.control.v2", + manifest={ + "PendingRenameInfo", + "Folder", + "GetFolderRequest", + "CreateFolderRequest", + "DeleteFolderRequest", + "ListFoldersRequest", + "ListFoldersResponse", + "RenameFolderRequest", + "DeleteFolderRecursiveRequest", + "CommonLongRunningOperationMetadata", + "RenameFolderMetadata", + "DeleteFolderRecursiveMetadata", + "StorageLayout", + "GetStorageLayoutRequest", + "ManagedFolder", + "GetManagedFolderRequest", + "CreateManagedFolderRequest", + "DeleteManagedFolderRequest", + "ListManagedFoldersRequest", + "ListManagedFoldersResponse", + "CreateAnywhereCacheMetadata", + "UpdateAnywhereCacheMetadata", + "AnywhereCache", + "CreateAnywhereCacheRequest", + "UpdateAnywhereCacheRequest", + "DisableAnywhereCacheRequest", + "PauseAnywhereCacheRequest", + "ResumeAnywhereCacheRequest", + "GetAnywhereCacheRequest", + "ListAnywhereCachesRequest", + "ListAnywhereCachesResponse", + "IntelligenceConfig", + "UpdateOrganizationIntelligenceConfigRequest", + "UpdateFolderIntelligenceConfigRequest", + "UpdateProjectIntelligenceConfigRequest", + "GetOrganizationIntelligenceConfigRequest", + "GetFolderIntelligenceConfigRequest", + "GetProjectIntelligenceConfigRequest", + }, +) + + +class PendingRenameInfo(proto.Message): + r"""Contains information about a pending rename operation. + + Attributes: + operation (str): + Output only. The name of the rename + operation. + """ + + operation: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Folder(proto.Message): + r"""A folder resource. This resource can only exist in a + hierarchical namespace enabled bucket. + + Attributes: + name (str): + Identifier. The name of this folder. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + metageneration (int): + Output only. The version of the metadata for + this folder. Used for preconditions and for + detecting changes in metadata. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the folder. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The modification time of the + folder. + pending_rename_info (google.cloud.storage_control_v2.types.PendingRenameInfo): + Output only. Only present if the folder is + part of an ongoing RenameFolder operation. + Contains information which can be used to query + the operation status. The presence of this field + also indicates all write operations are blocked + for this folder, including folder, managed + folder, and object operations. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + metageneration: int = proto.Field( + proto.INT64, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + pending_rename_info: "PendingRenameInfo" = proto.Field( + proto.MESSAGE, + number=7, + message="PendingRenameInfo", + ) + + +class GetFolderRequest(proto.Message): + r"""Request message for GetFolder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the folder. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + if_metageneration_match (int): + Makes the operation only succeed conditional + on whether the folder's current metageneration + matches the given value. + + This field is a member of `oneof`_ ``_if_metageneration_match``. + if_metageneration_not_match (int): + Makes the operation only succeed conditional + on whether the folder's current metageneration + does not match the given value. + + This field is a member of `oneof`_ ``_if_metageneration_not_match``. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + name: str = proto.Field( + proto.STRING, + number=6, + ) + if_metageneration_match: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + if_metageneration_not_match: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +class CreateFolderRequest(proto.Message): + r"""Request message for CreateFolder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Attributes: + parent (str): + Required. Name of the bucket in which the + folder will reside. The bucket must be a + hierarchical namespace enabled bucket. + folder (google.cloud.storage_control_v2.types.Folder): + Required. Properties of the new folder being created. The + bucket and name of the folder are specified in the parent + and folder_id fields, respectively. Populating those fields + in ``folder`` will result in an error. + folder_id (str): + Required. The full name of a folder, including all its + parent folders. Folders use single '/' characters as a + delimiter. The folder_id must end with a slash. For example, + the folder_id of "books/biographies/" would create a new + "biographies/" folder under the "books/" folder. + recursive (bool): + Optional. If true, parent folder doesn't have + to be present and all missing ancestor folders + will be created atomically. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + folder: "Folder" = proto.Field( + proto.MESSAGE, + number=2, + message="Folder", + ) + folder_id: str = proto.Field( + proto.STRING, + number=3, + ) + recursive: bool = proto.Field( + proto.BOOL, + number=4, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +class DeleteFolderRequest(proto.Message): + r"""Request message for DeleteFolder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the folder. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + if_metageneration_match (int): + Makes the operation only succeed conditional + on whether the folder's current metageneration + matches the given value. + + This field is a member of `oneof`_ ``_if_metageneration_match``. + if_metageneration_not_match (int): + Makes the operation only succeed conditional + on whether the folder's current metageneration + does not match the given value. + + This field is a member of `oneof`_ ``_if_metageneration_not_match``. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + name: str = proto.Field( + proto.STRING, + number=6, + ) + if_metageneration_match: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + if_metageneration_not_match: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListFoldersRequest(proto.Message): + r"""Request message for ListFolders. This operation is only + applicable to a hierarchical namespace enabled bucket. + + Attributes: + parent (str): + Required. Name of the bucket in which to look + for folders. The bucket must be a hierarchical + namespace enabled bucket. + page_size (int): + Optional. Maximum number of folders to return + in a single response. The service will use this + parameter or 1,000 items, whichever is smaller. + page_token (str): + Optional. A previously-returned page token + representing part of the larger set of results + to view. + prefix (str): + Optional. Filter results to folders whose + names begin with this prefix. If set, the value + must either be an empty string or end with a + '/'. + delimiter (str): + Optional. If set, returns results in a + directory-like mode. The results will only + include folders that either exactly match the + above prefix, or are one level below the prefix. + The only supported value is '/'. + lexicographic_start (str): + Optional. Filter results to folders whose names are + lexicographically equal to or after lexicographic_start. If + lexicographic_end is also set, the folders listed have names + between lexicographic_start (inclusive) and + lexicographic_end (exclusive). + lexicographic_end (str): + Optional. Filter results to folders whose names are + lexicographically before lexicographic_end. If + lexicographic_start is also set, the folders listed have + names between lexicographic_start (inclusive) and + lexicographic_end (exclusive). + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + 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, + ) + prefix: str = proto.Field( + proto.STRING, + number=4, + ) + delimiter: str = proto.Field( + proto.STRING, + number=8, + ) + lexicographic_start: str = proto.Field( + proto.STRING, + number=6, + ) + lexicographic_end: str = proto.Field( + proto.STRING, + number=7, + ) + request_id: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ListFoldersResponse(proto.Message): + r"""Response message for ListFolders. + + Attributes: + folders (MutableSequence[google.cloud.storage_control_v2.types.Folder]): + The list of child folders + next_page_token (str): + The continuation token, used to page through + large result sets. Provide this value in a + subsequent request to return the next page of + results. + """ + + @property + def raw_page(self): + return self + + folders: MutableSequence["Folder"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Folder", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RenameFolderRequest(proto.Message): + r"""Request message for RenameFolder. This operation is only + applicable to a hierarchical namespace enabled bucket. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the source folder being renamed. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + destination_folder_id (str): + Required. The destination folder ID, e.g. ``foo/bar/``. + if_metageneration_match (int): + Makes the operation only succeed conditional + on whether the source folder's current + metageneration matches the given value. + + This field is a member of `oneof`_ ``_if_metageneration_match``. + if_metageneration_not_match (int): + Makes the operation only succeed conditional + on whether the source folder's current + metageneration does not match the given value. + + This field is a member of `oneof`_ ``_if_metageneration_not_match``. + request_id (str): + Optional. A unique identifier for this request. UUID is the + recommended format, but other formats are still accepted. + This request is only idempotent if a ``request_id`` is + provided. + """ + + name: str = proto.Field( + proto.STRING, + number=7, + ) + destination_folder_id: str = proto.Field( + proto.STRING, + number=8, + ) + if_metageneration_match: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + if_metageneration_not_match: int = proto.Field( + proto.INT64, + number=5, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=6, + ) + + +class DeleteFolderRecursiveRequest(proto.Message): + r"""Request message for DeleteFolderRecursive. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the folder being deleted, however all of + its contents will be deleted too. Format: + ``projects/{project}/buckets/{bucket}/folders/{folder}`` + if_metageneration_match (int): + Optional. Makes the operation only succeed + conditional on whether the root folder's current + metageneration matches the given value. + + This field is a member of `oneof`_ ``_if_metageneration_match``. + if_metageneration_not_match (int): + Optional. Makes the operation only succeed + conditional on whether the root folder's current + metageneration does not match the given value. + + This field is a member of `oneof`_ ``_if_metageneration_not_match``. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + if_metageneration_match: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + if_metageneration_not_match: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CommonLongRunningOperationMetadata(proto.Message): + r"""The message contains metadata that is common to all Storage Control + long-running operations, present in its + ``google.longrunning.Operation`` messages, and accessible via + ``metadata.common_metadata``. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was last + modified. + type_ (str): + Output only. The type of operation invoked. + requested_cancellation (bool): + Output only. Identifies whether the user has + requested cancellation. + progress_percent (int): + Output only. The estimated progress of the operation in + percentage [0, 100]. The value -1 means the progress is + unknown. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + type_: str = proto.Field( + proto.STRING, + number=4, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=5, + ) + progress_percent: int = proto.Field( + proto.INT32, + number=6, + ) + + +class RenameFolderMetadata(proto.Message): + r"""Message returned in the metadata field of the Operation + resource for RenameFolder operations. + + Attributes: + common_metadata (google.cloud.storage_control_v2.types.CommonLongRunningOperationMetadata): + Generic metadata for the long running + operation. + source_folder_id (str): + The path of the source folder. + destination_folder_id (str): + The path of the destination folder. + """ + + common_metadata: "CommonLongRunningOperationMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="CommonLongRunningOperationMetadata", + ) + source_folder_id: str = proto.Field( + proto.STRING, + number=2, + ) + destination_folder_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFolderRecursiveMetadata(proto.Message): + r"""Message returned in the metadata field of the Operation + resource for DeleteFolderRecursive operations. + + Attributes: + common_metadata (google.cloud.storage_control_v2.types.CommonLongRunningOperationMetadata): + Generic metadata for the long running + operation. + folder_id (str): + The path of the folder recursively deleted. + """ + + common_metadata: "CommonLongRunningOperationMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="CommonLongRunningOperationMetadata", + ) + folder_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StorageLayout(proto.Message): + r"""The storage layout configuration of a bucket. + + Attributes: + name (str): + Output only. The name of the StorageLayout resource. Format: + ``projects/{project}/buckets/{bucket}/storageLayout`` + location (str): + Output only. The location of the bucket. + location_type (str): + Output only. The location type of the bucket + (region, dual-region, multi-region, etc). + custom_placement_config (google.cloud.storage_control_v2.types.StorageLayout.CustomPlacementConfig): + Output only. The data placement configuration + for custom dual region. If there is no + configuration, this is not a custom dual region + bucket. + hierarchical_namespace (google.cloud.storage_control_v2.types.StorageLayout.HierarchicalNamespace): + Output only. The bucket's hierarchical + namespace configuration. If there is no + configuration, the hierarchical namespace is + disabled. + """ + + class CustomPlacementConfig(proto.Message): + r"""Configuration for Custom Dual Regions. It should specify precisely + two eligible regions within the same Multiregion. More information + on regions may be found + `here `__. + + Attributes: + data_locations (MutableSequence[str]): + List of locations to use for data placement. + """ + + data_locations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class HierarchicalNamespace(proto.Message): + r"""Configuration for a bucket's hierarchical namespace feature. + + Attributes: + enabled (bool): + Enables the hierarchical namespace feature. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + location_type: str = proto.Field( + proto.STRING, + number=3, + ) + custom_placement_config: CustomPlacementConfig = proto.Field( + proto.MESSAGE, + number=4, + message=CustomPlacementConfig, + ) + hierarchical_namespace: HierarchicalNamespace = proto.Field( + proto.MESSAGE, + number=5, + message=HierarchicalNamespace, + ) + + +class GetStorageLayoutRequest(proto.Message): + r"""Request message for GetStorageLayout. + + Attributes: + name (str): + Required. The name of the StorageLayout resource. Format: + ``projects/{project}/buckets/{bucket}/storageLayout`` + prefix (str): + An optional prefix used for permission check. + It is useful when the caller only has limited + permissions under a specific prefix. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + prefix: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ManagedFolder(proto.Message): + r"""A managed folder. + + Attributes: + name (str): + Identifier. The name of this managed folder. Format: + ``projects/{project}/buckets/{bucket}/managedFolders/{managedFolder}`` + metageneration (int): + Output only. The metadata version of this + managed folder. It increases whenever the + metadata is updated. Used for preconditions and + for detecting changes in metadata. Managed + folders don't have a generation number. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the managed + folder. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The modification time of the + managed folder. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + metageneration: int = proto.Field( + proto.INT64, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class GetManagedFolderRequest(proto.Message): + r"""Request message for GetManagedFolder. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the managed folder. Format: + ``projects/{project}/buckets/{bucket}/managedFolders/{managedFolder}`` + if_metageneration_match (int): + The operation succeeds conditional on the + managed folder's current metageneration matching + the value here specified. + + This field is a member of `oneof`_ ``_if_metageneration_match``. + if_metageneration_not_match (int): + The operation succeeds conditional on the + managed folder's current metageneration NOT + matching the value here specified. + + This field is a member of `oneof`_ ``_if_metageneration_not_match``. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + name: str = proto.Field( + proto.STRING, + number=6, + ) + if_metageneration_match: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + if_metageneration_not_match: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +class CreateManagedFolderRequest(proto.Message): + r"""Request message for CreateManagedFolder. + + Attributes: + parent (str): + Required. Name of the bucket this managed + folder belongs to. + managed_folder (google.cloud.storage_control_v2.types.ManagedFolder): + Required. Properties of the managed folder being created. + The bucket and managed folder names are specified in the + ``parent`` and ``managed_folder_id`` fields. Populating + these fields in ``managed_folder`` will result in an error. + managed_folder_id (str): + Required. The name of the managed folder. It uses a single + ``/`` as delimiter and leading and trailing ``/`` are + allowed. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + managed_folder: "ManagedFolder" = proto.Field( + proto.MESSAGE, + number=2, + message="ManagedFolder", + ) + managed_folder_id: str = proto.Field( + proto.STRING, + number=3, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteManagedFolderRequest(proto.Message): + r"""DeleteManagedFolder RPC request message. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the managed folder. Format: + ``projects/{project}/buckets/{bucket}/managedFolders/{managedFolder}`` + if_metageneration_match (int): + The operation succeeds conditional on the + managed folder's current metageneration matching + the value here specified. + + This field is a member of `oneof`_ ``_if_metageneration_match``. + if_metageneration_not_match (int): + The operation succeeds conditional on the + managed folder's current metageneration NOT + matching the value here specified. + + This field is a member of `oneof`_ ``_if_metageneration_not_match``. + allow_non_empty (bool): + Allows deletion of a managed folder even if + it is not empty. A managed folder is empty if it + manages no child managed folders or objects. + Caller must have permission for + storage.managedFolders.setIamPolicy. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + name: str = proto.Field( + proto.STRING, + number=7, + ) + if_metageneration_match: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + if_metageneration_not_match: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + allow_non_empty: bool = proto.Field( + proto.BOOL, + number=5, + ) + request_id: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListManagedFoldersRequest(proto.Message): + r"""Request message for ListManagedFolders. + + Attributes: + parent (str): + Required. Name of the bucket this managed + folder belongs to. + page_size (int): + Optional. Maximum number of managed folders + to return in a single response. The service will + use this parameter or 1,000 items, whichever is + smaller. + page_token (str): + Optional. A previously-returned page token + representing part of the larger set of results + to view. + prefix (str): + Optional. Filter results to match managed + folders with name starting with this prefix. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + 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, + ) + prefix: str = proto.Field( + proto.STRING, + number=4, + ) + request_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListManagedFoldersResponse(proto.Message): + r"""Response message for ListManagedFolders. + + Attributes: + managed_folders (MutableSequence[google.cloud.storage_control_v2.types.ManagedFolder]): + The list of matching managed folders + next_page_token (str): + The continuation token, used to page through + large result sets. Provide this value in a + subsequent request to return the next page of + results. + """ + + @property + def raw_page(self): + return self + + managed_folders: MutableSequence["ManagedFolder"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ManagedFolder", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAnywhereCacheMetadata(proto.Message): + r"""Message returned in the metadata field of the Operation + resource for CreateAnywhereCache operations. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + common_metadata (google.cloud.storage_control_v2.types.CommonLongRunningOperationMetadata): + Generic metadata for the long running + operation. + anywhere_cache_id (str): + Anywhere Cache ID. + + This field is a member of `oneof`_ ``_anywhere_cache_id``. + zone (str): + The zone in which the cache instance is + running. For example, us-central1-a. + + This field is a member of `oneof`_ ``_zone``. + ttl (google.protobuf.duration_pb2.Duration): + Anywhere Cache entry's TTL. A cache-level + config that is applied to all new cache entries + on admission. Default ttl value (24hrs) is + applied if not specified in the create request. + + This field is a member of `oneof`_ ``_ttl``. + admission_policy (str): + Anywhere Cache entry Admission Policy in + kebab-case (e.g., "admit-on-first-miss"). + Default admission policy (admit-on-first-miss) + is applied if not specified in the create + request. + + This field is a member of `oneof`_ ``_admission_policy``. + """ + + common_metadata: "CommonLongRunningOperationMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="CommonLongRunningOperationMetadata", + ) + anywhere_cache_id: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=duration_pb2.Duration, + ) + admission_policy: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + +class UpdateAnywhereCacheMetadata(proto.Message): + r"""Message returned in the metadata field of the Operation + resource for UpdateAnywhereCache operation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + common_metadata (google.cloud.storage_control_v2.types.CommonLongRunningOperationMetadata): + Generic metadata for the long running + operation. + anywhere_cache_id (str): + Anywhere Cache ID. + + This field is a member of `oneof`_ ``_anywhere_cache_id``. + zone (str): + The zone in which the cache instance is + running. For example, us-central1-a. + + This field is a member of `oneof`_ ``_zone``. + ttl (google.protobuf.duration_pb2.Duration): + Anywhere Cache entry's TTL between 1h and 7days. A + cache-level config that is applied to all new cache entries + on admission. If ``ttl`` is pending update, this field + equals to the new value specified in the Update request. + + This field is a member of `oneof`_ ``_ttl``. + admission_policy (str): + L4 Cache entry Admission Policy in kebab-case (e.g., + "admit-on-first-miss"). If ``admission_policy`` is pending + update, this field equals to the new value specified in the + Update request. + + This field is a member of `oneof`_ ``_admission_policy``. + """ + + common_metadata: "CommonLongRunningOperationMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="CommonLongRunningOperationMetadata", + ) + anywhere_cache_id: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=duration_pb2.Duration, + ) + admission_policy: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + + +class AnywhereCache(proto.Message): + r"""An Anywhere Cache Instance. + + Attributes: + name (str): + Immutable. The resource name of this AnywhereCache. Format: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + zone (str): + Immutable. The zone in which the cache + instance is running. For example, us-central1-a. + ttl (google.protobuf.duration_pb2.Duration): + Cache entry TTL (ranges between 1h to 7d). + This is a cache-level config that defines how + long a cache entry can live. Default ttl value + (24hrs) is applied if not specified in the + create request. TTL must be in whole seconds. + admission_policy (str): + Cache admission policy. Valid policies includes: + ``admit-on-first-miss`` and ``admit-on-second-miss``. + Defaults to ``admit-on-first-miss``. Default value is + applied if not specified in the create request. + state (str): + Output only. Cache state including RUNNING, + CREATING, DISABLED and PAUSED. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when Anywhere cache + instance is allocated. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when Anywhere cache + instance is last updated, including creation. + pending_update (bool): + Output only. True if there is an active + update operation against this cache instance. + Subsequential update requests will be rejected + if this field is true. Output only. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + zone: str = proto.Field( + proto.STRING, + number=10, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + admission_policy: str = proto.Field( + proto.STRING, + number=9, + ) + state: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + pending_update: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class CreateAnywhereCacheRequest(proto.Message): + r"""Request message for CreateAnywhereCache. + + Attributes: + parent (str): + Required. The bucket to which this cache belongs. Format: + ``projects/{project}/buckets/{bucket}`` + anywhere_cache (google.cloud.storage_control_v2.types.AnywhereCache): + Required. Properties of the Anywhere Cache instance being + created. The parent bucket name is specified in the + ``parent`` field. Server uses the default value of ``ttl`` + or ``admission_policy`` if not specified in request. + request_id (str): + Optional. A unique identifier for this request. UUID is the + recommended format, but other formats are still accepted. + This request is only idempotent if a ``request_id`` is + provided. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + anywhere_cache: "AnywhereCache" = proto.Field( + proto.MESSAGE, + number=3, + message="AnywhereCache", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateAnywhereCacheRequest(proto.Message): + r"""Request message for UpdateAnywhereCache. + + Attributes: + anywhere_cache (google.cloud.storage_control_v2.types.AnywhereCache): + Required. The Anywhere Cache instance to be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated. Mutable fields of + AnywhereCache include ``ttl`` and ``admission_policy``. + + To specify ALL fields, specify a single field with the value + ``*``. Note: We recommend against doing this. If a new field + is introduced at a later time, an older client updating with + the ``*`` may accidentally reset the new field's value. + + Not specifying any fields is an error. + request_id (str): + Optional. A unique identifier for this request. UUID is the + recommended format, but other formats are still accepted. + This request is only idempotent if a ``request_id`` is + provided. + """ + + anywhere_cache: "AnywhereCache" = proto.Field( + proto.MESSAGE, + number=1, + message="AnywhereCache", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DisableAnywhereCacheRequest(proto.Message): + r"""Request message for DisableAnywhereCache. + + Attributes: + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + request_id (str): + Optional. A unique identifier for this request. UUID is the + recommended format, but other formats are still accepted. + This request is only idempotent if a ``request_id`` is + provided. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PauseAnywhereCacheRequest(proto.Message): + r"""Request message for PauseAnywhereCache. + + Attributes: + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + request_id (str): + Optional. A unique identifier for this request. UUID is the + recommended format, but other formats are still accepted. + This request is only idempotent if a ``request_id`` is + provided. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ResumeAnywhereCacheRequest(proto.Message): + r"""Request message for ResumeAnywhereCache. + + Attributes: + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + request_id (str): + Optional. A unique identifier for this request. UUID is the + recommended format, but other formats are still accepted. + This request is only idempotent if a ``request_id`` is + provided. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAnywhereCacheRequest(proto.Message): + r"""Request message for GetAnywhereCache. + + Attributes: + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/anywhereCaches/{anywhere_cache}`` + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAnywhereCachesRequest(proto.Message): + r"""Request message for ListAnywhereCaches. + + Attributes: + parent (str): + Required. The bucket to which this cache + belongs. + page_size (int): + Maximum number of caches to return in a + single response. The service will use this + parameter or 1,000 items, whichever is smaller. + page_token (str): + A previously-returned page token representing + part of the larger set of results to view. + request_id (str): + Optional. A unique identifier for this + request. UUID is the recommended format, but + other formats are still accepted. + """ + + 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, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAnywhereCachesResponse(proto.Message): + r"""Response message for ListAnywhereCaches. + + Attributes: + anywhere_caches (MutableSequence[google.cloud.storage_control_v2.types.AnywhereCache]): + The list of items. + 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 + + anywhere_caches: MutableSequence["AnywhereCache"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AnywhereCache", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class IntelligenceConfig(proto.Message): + r"""The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + Attributes: + name (str): + Identifier. The name of the ``IntelligenceConfig`` resource + associated with your organization, folder, or project. + + The name format varies based on the GCP resource hierarchy + as follows: + + - For project: + ``projects/{project_number}/locations/global/intelligenceConfig`` + - For organization: + ``organizations/{org_id}/locations/global/intelligenceConfig`` + - For folder: + ``folders/{folder_id}/locations/global/intelligenceConfig`` + edition_config (google.cloud.storage_control_v2.types.IntelligenceConfig.EditionConfig): + Optional. The edition configuration of the + ``IntelligenceConfig`` resource. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the ``IntelligenceConfig`` + resource is last updated. + filter (google.cloud.storage_control_v2.types.IntelligenceConfig.Filter): + Optional. Filter over location and bucket. + effective_intelligence_config (google.cloud.storage_control_v2.types.IntelligenceConfig.EffectiveIntelligenceConfig): + Output only. The ``IntelligenceConfig`` resource that is + applicable for the resource. + trial_config (google.cloud.storage_control_v2.types.IntelligenceConfig.TrialConfig): + The trial configuration of the ``IntelligenceConfig`` + resource. + """ + + class EditionConfig(proto.Enum): + r"""The edition configuration of the ``IntelligenceConfig`` resource. + This signifies the edition used for configuring the + ``IntelligenceConfig`` resource and can only take the following + values: ``EDITION_CONFIG_UNSPECIFIED``, ``INHERIT``, ``DISABLED``, + ``STANDARD`` and ``TRIAL``. + + Values: + EDITION_CONFIG_UNSPECIFIED (0): + This is an unknown edition of the resource. + INHERIT (1): + The inherited edition from the parent and filters. This is + the default edition when there is no ``IntelligenceConfig`` + setup for a GCP resource. + DISABLED (2): + The edition configuration is disabled for the + ``IntelligenceConfig`` resource and its children. Filters + are not applicable. + STANDARD (3): + The ``IntelligenceConfig`` resource is of STANDARD edition. + TRIAL (5): + The ``IntelligenceConfig`` resource is available in + ``TRIAL`` edition. During the trial period, Cloud Storage + does not charge for Storage Intelligence usage. You can + specify the buckets to include in the trial period by using + filters. At the end of the trial period, the + ``IntelligenceConfig`` resource is upgraded to ``STANDARD`` + edition. + """ + + EDITION_CONFIG_UNSPECIFIED = 0 + INHERIT = 1 + DISABLED = 2 + STANDARD = 3 + TRIAL = 5 + + class Filter(proto.Message): + r"""Filter over location and bucket using include or exclude + semantics. Resources that match the include or exclude filter + are exclusively included or excluded from the Storage + Intelligence plan. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + included_cloud_storage_locations (google.cloud.storage_control_v2.types.IntelligenceConfig.Filter.CloudStorageLocations): + Bucket locations to include. + + This field is a member of `oneof`_ ``cloud_storage_locations``. + excluded_cloud_storage_locations (google.cloud.storage_control_v2.types.IntelligenceConfig.Filter.CloudStorageLocations): + Bucket locations to exclude. + + This field is a member of `oneof`_ ``cloud_storage_locations``. + included_cloud_storage_buckets (google.cloud.storage_control_v2.types.IntelligenceConfig.Filter.CloudStorageBuckets): + Buckets to include. + + This field is a member of `oneof`_ ``cloud_storage_buckets``. + excluded_cloud_storage_buckets (google.cloud.storage_control_v2.types.IntelligenceConfig.Filter.CloudStorageBuckets): + Buckets to exclude. + + This field is a member of `oneof`_ ``cloud_storage_buckets``. + """ + + class CloudStorageLocations(proto.Message): + r"""Collection of bucket locations. + + Attributes: + locations (MutableSequence[str]): + Optional. Bucket locations. Location can be any of the Cloud + Storage regions specified in lower case format. For example, + ``us-east1``, ``us-west1``. + """ + + locations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class CloudStorageBuckets(proto.Message): + r"""Collection of buckets. + + Attributes: + bucket_id_regexes (MutableSequence[str]): + Optional. A regex pattern for matching bucket names. Regex + should follow the syntax specified in + `google/re2 `__. For example, + ``^sample_.*`` matches all buckets of the form + ``gs://sample_bucket-1``, ``gs://sample_bucket-2``, + ``gs://sample_bucket-n`` but not + ``gs://test_sample_bucket``. If you want to match a single + bucket, say ``gs://sample_bucket``, use ``sample_bucket``. + """ + + bucket_id_regexes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + included_cloud_storage_locations: "IntelligenceConfig.Filter.CloudStorageLocations" = proto.Field( + proto.MESSAGE, + number=1, + oneof="cloud_storage_locations", + message="IntelligenceConfig.Filter.CloudStorageLocations", + ) + excluded_cloud_storage_locations: "IntelligenceConfig.Filter.CloudStorageLocations" = proto.Field( + proto.MESSAGE, + number=2, + oneof="cloud_storage_locations", + message="IntelligenceConfig.Filter.CloudStorageLocations", + ) + included_cloud_storage_buckets: "IntelligenceConfig.Filter.CloudStorageBuckets" = proto.Field( + proto.MESSAGE, + number=3, + oneof="cloud_storage_buckets", + message="IntelligenceConfig.Filter.CloudStorageBuckets", + ) + excluded_cloud_storage_buckets: "IntelligenceConfig.Filter.CloudStorageBuckets" = proto.Field( + proto.MESSAGE, + number=4, + oneof="cloud_storage_buckets", + message="IntelligenceConfig.Filter.CloudStorageBuckets", + ) + + class EffectiveIntelligenceConfig(proto.Message): + r"""The effective ``IntelligenceConfig`` for the resource. + + Attributes: + effective_edition (google.cloud.storage_control_v2.types.IntelligenceConfig.EffectiveIntelligenceConfig.EffectiveEdition): + Output only. The ``IntelligenceConfig`` edition that is + applicable for the resource. + intelligence_config (str): + Output only. The ``IntelligenceConfig`` resource that is + applied for the target resource. Format: + ``{organizations|folders|projects}/{id}/locations/{location}/intelligenceConfig`` + """ + + class EffectiveEdition(proto.Enum): + r"""The effective edition of the ``IntelligenceConfig`` resource. + + Values: + EFFECTIVE_EDITION_UNSPECIFIED (0): + This is an unknown edition of the resource. + NONE (1): + No edition. + STANDARD (2): + The ``IntelligenceConfig`` resource is of STANDARD edition. + """ + + EFFECTIVE_EDITION_UNSPECIFIED = 0 + NONE = 1 + STANDARD = 2 + + effective_edition: "IntelligenceConfig.EffectiveIntelligenceConfig.EffectiveEdition" = proto.Field( + proto.ENUM, + number=1, + enum="IntelligenceConfig.EffectiveIntelligenceConfig.EffectiveEdition", + ) + intelligence_config: str = proto.Field( + proto.STRING, + number=2, + ) + + class TrialConfig(proto.Message): + r"""The trial configuration of the ``IntelligenceConfig`` resource. + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the trial + expires. + """ + + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + edition_config: EditionConfig = proto.Field( + proto.ENUM, + number=2, + enum=EditionConfig, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + filter: Filter = proto.Field( + proto.MESSAGE, + number=4, + message=Filter, + ) + effective_intelligence_config: EffectiveIntelligenceConfig = proto.Field( + proto.MESSAGE, + number=5, + message=EffectiveIntelligenceConfig, + ) + trial_config: TrialConfig = proto.Field( + proto.MESSAGE, + number=7, + message=TrialConfig, + ) + + +class UpdateOrganizationIntelligenceConfigRequest(proto.Message): + r"""Request message to update the ``IntelligenceConfig`` resource + associated with your organization. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the organization. + + Attributes: + intelligence_config (google.cloud.storage_control_v2.types.IntelligenceConfig): + Required. The ``IntelligenceConfig`` resource to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should be + modified by this update. Only the listed fields are updated. + request_id (str): + Optional. The ID that uniquely identifies the + request, preventing duplicate processing. + """ + + intelligence_config: "IntelligenceConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="IntelligenceConfig", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateFolderIntelligenceConfigRequest(proto.Message): + r"""Request message to update the ``IntelligenceConfig`` resource + associated with your folder. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + + Attributes: + intelligence_config (google.cloud.storage_control_v2.types.IntelligenceConfig): + Required. The ``IntelligenceConfig`` resource to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should be + modified by this update. Only the listed fields are updated. + request_id (str): + Optional. The ID that uniquely identifies the + request, preventing duplicate processing. + """ + + intelligence_config: "IntelligenceConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="IntelligenceConfig", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateProjectIntelligenceConfigRequest(proto.Message): + r"""Request message to update the ``IntelligenceConfig`` resource + associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.update`` + `IAM `__ + permission on the folder. + + Attributes: + intelligence_config (google.cloud.storage_control_v2.types.IntelligenceConfig): + Required. The ``IntelligenceConfig`` resource to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The ``update_mask`` that specifies the fields + within the ``IntelligenceConfig`` resource that should be + modified by this update. Only the listed fields are updated. + request_id (str): + Optional. The ID that uniquely identifies the + request, preventing duplicate processing. + """ + + intelligence_config: "IntelligenceConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="IntelligenceConfig", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetOrganizationIntelligenceConfigRequest(proto.Message): + r"""Request message to get the ``IntelligenceConfig`` resource + associated with your organization. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the organization. + + Attributes: + name (str): + Required. The name of the ``IntelligenceConfig`` resource + associated with your organization. + + Format: + ``organizations/{org_id}/locations/global/intelligenceConfig`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetFolderIntelligenceConfigRequest(proto.Message): + r"""Request message to get the ``IntelligenceConfig`` resource + associated with your folder. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the folder. + + Attributes: + name (str): + Required. The name of the ``IntelligenceConfig`` resource + associated with your folder. + + Format: ``folders/{id}/locations/global/intelligenceConfig`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetProjectIntelligenceConfigRequest(proto.Message): + r"""Request message to get the ``IntelligenceConfig`` resource + associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the project. + + Attributes: + name (str): + Required. The name of the ``IntelligenceConfig`` resource + associated with your project. + + Format: + ``projects/{id}/locations/global/intelligenceConfig`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da40dfc6cb820ad0c842345feef97b2cbfb711cd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/__init__.py @@ -0,0 +1,43 @@ +# -*- 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.trace import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.trace_v2.services.trace_service.async_client import ( + TraceServiceAsyncClient, +) +from google.cloud.trace_v2.services.trace_service.client import TraceServiceClient +from google.cloud.trace_v2.types.trace import ( + AttributeValue, + Module, + Span, + StackTrace, + TruncatableString, +) +from google.cloud.trace_v2.types.tracing import BatchWriteSpansRequest + +__all__ = ( + "TraceServiceClient", + "TraceServiceAsyncClient", + "AttributeValue", + "Module", + "Span", + "StackTrace", + "TruncatableString", + "BatchWriteSpansRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..7313c97c30967bee5f1c5555b99e753ea22ae2de --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/gapic_version.py @@ -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__ = "1.19.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..4717a6c0faf00d07c451b77145c88d1d773cadb3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-trace package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b499e93e32148bb4e09b505ff2da4ecf03a4b9c8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/__init__.py @@ -0,0 +1,147 @@ +# -*- 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 sys + +import google.api_core as api_core + +from google.cloud.trace_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.trace_service import TraceServiceAsyncClient, TraceServiceClient +from .types.trace import ( + GetTraceRequest, + ListTracesRequest, + ListTracesResponse, + PatchTracesRequest, + Trace, + Traces, + TraceSpan, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.trace_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.trace_v1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.trace_v1" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "TraceServiceAsyncClient", + "GetTraceRequest", + "ListTracesRequest", + "ListTracesResponse", + "PatchTracesRequest", + "Trace", + "TraceServiceClient", + "TraceSpan", + "Traces", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8d5b08178b39d285a7f4c3db0adb5e15aec99483 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/gapic_metadata.json @@ -0,0 +1,73 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.trace_v1", + "protoPackage": "google.devtools.cloudtrace.v1", + "schema": "1.0", + "services": { + "TraceService": { + "clients": { + "grpc": { + "libraryClient": "TraceServiceClient", + "rpcs": { + "GetTrace": { + "methods": [ + "get_trace" + ] + }, + "ListTraces": { + "methods": [ + "list_traces" + ] + }, + "PatchTraces": { + "methods": [ + "patch_traces" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TraceServiceAsyncClient", + "rpcs": { + "GetTrace": { + "methods": [ + "get_trace" + ] + }, + "ListTraces": { + "methods": [ + "list_traces" + ] + }, + "PatchTraces": { + "methods": [ + "patch_traces" + ] + } + } + }, + "rest": { + "libraryClient": "TraceServiceClient", + "rpcs": { + "GetTrace": { + "methods": [ + "get_trace" + ] + }, + "ListTraces": { + "methods": [ + "list_traces" + ] + }, + "PatchTraces": { + "methods": [ + "patch_traces" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..7313c97c30967bee5f1c5555b99e753ea22ae2de --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/gapic_version.py @@ -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__ = "1.19.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..4717a6c0faf00d07c451b77145c88d1d773cadb3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-trace package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/__init__.py @@ -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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7fbf701aae3c2a3acbd7166351e133c6ab9b466 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/__init__.py @@ -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 TraceServiceAsyncClient +from .client import TraceServiceClient + +__all__ = ( + "TraceServiceClient", + "TraceServiceAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..77c52e700bafd443d3e82967480ed372efd231ba --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/async_client.py @@ -0,0 +1,680 @@ +# -*- 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +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.trace_v1 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.cloud.trace_v1.services.trace_service import pagers +from google.cloud.trace_v1.types import trace + +from .client import TraceServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, TraceServiceTransport +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport + +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 TraceServiceAsyncClient: + """This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + """ + + _client: TraceServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TraceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TraceServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TraceServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TraceServiceClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod( + TraceServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + TraceServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(TraceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TraceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TraceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + TraceServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(TraceServiceClient.common_project_path) + parse_common_project_path = staticmethod( + TraceServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(TraceServiceClient.common_location_path) + parse_common_location_path = staticmethod( + TraceServiceClient.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: + TraceServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + TraceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(TraceServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TraceServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + TraceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(TraceServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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 TraceServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TraceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TraceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = TraceServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, TraceServiceTransport, Callable[..., TraceServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trace service 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,TraceServiceTransport,Callable[..., TraceServiceTransport]]]): + 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 TraceServiceTransport 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 = TraceServiceClient( + 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.devtools.cloudtrace_v1.TraceServiceAsyncClient`.", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "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.devtools.cloudtrace.v1.TraceService", + "credentialsType": None, + }, + ) + + async def list_traces( + self, + request: Optional[Union[trace.ListTracesRequest, dict]] = None, + *, + project_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTracesAsyncPager: + r"""Returns of a list of traces that match the specified + filter conditions. + + .. 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 trace_v1 + + async def sample_list_traces(): + # Create a client + client = trace_v1.TraceServiceAsyncClient() + + # Initialize request argument(s) + request = trace_v1.ListTracesRequest( + project_id="project_id_value", + ) + + # Make the request + page_result = client.list_traces(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.trace_v1.types.ListTracesRequest, dict]]): + The request object. The request message for the ``ListTraces`` method. All + fields are required unless specified. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + + This corresponds to the ``project_id`` 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.trace_v1.services.trace_service.pagers.ListTracesAsyncPager: + The response message for the ListTraces method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [project_id] + 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, trace.ListTracesRequest): + request = trace.ListTracesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_traces + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("project_id", request.project_id),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTracesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_trace( + self, + request: Optional[Union[trace.GetTraceRequest, dict]] = None, + *, + project_id: Optional[str] = None, + trace_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trace.Trace: + r"""Gets a single trace by its ID. + + .. 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 trace_v1 + + async def sample_get_trace(): + # Create a client + client = trace_v1.TraceServiceAsyncClient() + + # Initialize request argument(s) + request = trace_v1.GetTraceRequest( + project_id="project_id_value", + trace_id="trace_id_value", + ) + + # Make the request + response = await client.get_trace(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.trace_v1.types.GetTraceRequest, dict]]): + The request object. The request message for the ``GetTrace`` method. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trace_id (:class:`str`): + Required. ID of the trace to return. + This corresponds to the ``trace_id`` 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.trace_v1.types.Trace: + A trace describes how long it takes + for an application to perform an + operation. It consists of a set of + spans, each of which represent a single + timed event within the operation. + + """ + # 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 = [project_id, trace_id] + 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, trace.GetTraceRequest): + request = trace.GetTraceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trace_id is not None: + request.trace_id = trace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_trace + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project_id", request.project_id), + ("trace_id", request.trace_id), + ) + ), + ) + + # 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 patch_traces( + self, + request: Optional[Union[trace.PatchTracesRequest, dict]] = None, + *, + project_id: Optional[str] = None, + traces: Optional[trace.Traces] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + .. 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 trace_v1 + + async def sample_patch_traces(): + # Create a client + client = trace_v1.TraceServiceAsyncClient() + + # Initialize request argument(s) + request = trace_v1.PatchTracesRequest( + project_id="project_id_value", + ) + + # Make the request + await client.patch_traces(request=request) + + Args: + request (Optional[Union[google.cloud.trace_v1.types.PatchTracesRequest, dict]]): + The request object. The request message for the ``PatchTraces`` method. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + traces (:class:`google.cloud.trace_v1.types.Traces`): + Required. The body of the message. + This corresponds to the ``traces`` 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`. + """ + # 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 = [project_id, traces] + 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, trace.PatchTracesRequest): + request = trace.PatchTracesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if traces is not None: + request.traces = traces + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.patch_traces + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("project_id", request.project_id),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "TraceServiceAsyncClient": + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("TraceServiceAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..49d05a965ef91f7aa016096903099cb6d33bc690 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/client.py @@ -0,0 +1,1092 @@ +# -*- 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 os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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__) + +from google.cloud.trace_v1.services.trace_service import pagers +from google.cloud.trace_v1.types import trace + +from .transports.base import DEFAULT_CLIENT_INFO, TraceServiceTransport +from .transports.grpc import TraceServiceGrpcTransport +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport +from .transports.rest import TraceServiceRestTransport + + +class TraceServiceClientMeta(type): + """Metaclass for the TraceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] + _transport_registry["grpc"] = TraceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TraceServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[TraceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TraceServiceClient(metaclass=TraceServiceClientMeta): + """This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudtrace.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudtrace.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + TraceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TraceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TraceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TraceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. 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. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = TraceServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = TraceServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = TraceServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = TraceServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TraceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = TraceServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._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._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, TraceServiceTransport, Callable[..., TraceServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trace service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,TraceServiceTransport,Callable[..., TraceServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the TraceServiceTransport 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 the ``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_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + TraceServiceClient._read_environment_variables() + ) + self._client_cert_source = TraceServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = TraceServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, TraceServiceTransport) + if transport_provided: + # transport is a TraceServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(TraceServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or TraceServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[TraceServiceTransport], Callable[..., TraceServiceTransport] + ] = ( + TraceServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TraceServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.devtools.cloudtrace_v1.TraceServiceClient`.", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "credentialsType": None, + }, + ) + + def list_traces( + self, + request: Optional[Union[trace.ListTracesRequest, dict]] = None, + *, + project_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTracesPager: + r"""Returns of a list of traces that match the specified + filter conditions. + + .. 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 trace_v1 + + def sample_list_traces(): + # Create a client + client = trace_v1.TraceServiceClient() + + # Initialize request argument(s) + request = trace_v1.ListTracesRequest( + project_id="project_id_value", + ) + + # Make the request + page_result = client.list_traces(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.trace_v1.types.ListTracesRequest, dict]): + The request object. The request message for the ``ListTraces`` method. All + fields are required unless specified. + project_id (str): + Required. ID of the Cloud project + where the trace data is stored. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.trace_v1.services.trace_service.pagers.ListTracesPager: + The response message for the ListTraces method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = [project_id] + 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, trace.ListTracesRequest): + request = trace.ListTracesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_traces] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("project_id", request.project_id),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTracesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_trace( + self, + request: Optional[Union[trace.GetTraceRequest, dict]] = None, + *, + project_id: Optional[str] = None, + trace_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trace.Trace: + r"""Gets a single trace by its ID. + + .. 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 trace_v1 + + def sample_get_trace(): + # Create a client + client = trace_v1.TraceServiceClient() + + # Initialize request argument(s) + request = trace_v1.GetTraceRequest( + project_id="project_id_value", + trace_id="trace_id_value", + ) + + # Make the request + response = client.get_trace(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.trace_v1.types.GetTraceRequest, dict]): + The request object. The request message for the ``GetTrace`` method. + project_id (str): + Required. ID of the Cloud project + where the trace data is stored. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trace_id (str): + Required. ID of the trace to return. + This corresponds to the ``trace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.trace_v1.types.Trace: + A trace describes how long it takes + for an application to perform an + operation. It consists of a set of + spans, each of which represent a single + timed event within the operation. + + """ + # 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 = [project_id, trace_id] + 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, trace.GetTraceRequest): + request = trace.GetTraceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if trace_id is not None: + request.trace_id = trace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_trace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project_id", request.project_id), + ("trace_id", request.trace_id), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def patch_traces( + self, + request: Optional[Union[trace.PatchTracesRequest, dict]] = None, + *, + project_id: Optional[str] = None, + traces: Optional[trace.Traces] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + .. 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 trace_v1 + + def sample_patch_traces(): + # Create a client + client = trace_v1.TraceServiceClient() + + # Initialize request argument(s) + request = trace_v1.PatchTracesRequest( + project_id="project_id_value", + ) + + # Make the request + client.patch_traces(request=request) + + Args: + request (Union[google.cloud.trace_v1.types.PatchTracesRequest, dict]): + The request object. The request message for the ``PatchTraces`` method. + project_id (str): + Required. ID of the Cloud project + where the trace data is stored. + + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + traces (google.cloud.trace_v1.types.Traces): + Required. The body of the message. + This corresponds to the ``traces`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + # 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 = [project_id, traces] + 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, trace.PatchTracesRequest): + request = trace.PatchTracesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project_id is not None: + request.project_id = project_id + if traces is not None: + request.traces = traces + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch_traces] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("project_id", request.project_id),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "TraceServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("TraceServiceClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1817b869e6c70b3ec5f7adeb072fa98de42824 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/pagers.py @@ -0,0 +1,197 @@ +# -*- 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.trace_v1.types import trace + + +class ListTracesPager: + """A pager for iterating through ``list_traces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.trace_v1.types.ListTracesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``traces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTraces`` requests and continue to iterate + through the ``traces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.trace_v1.types.ListTracesResponse` + 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[..., trace.ListTracesResponse], + request: trace.ListTracesRequest, + response: trace.ListTracesResponse, + *, + 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.trace_v1.types.ListTracesRequest): + The initial request object. + response (google.cloud.trace_v1.types.ListTracesResponse): + 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 = trace.ListTracesRequest(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[trace.ListTracesResponse]: + 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[trace.Trace]: + for page in self.pages: + yield from page.traces + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTracesAsyncPager: + """A pager for iterating through ``list_traces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.trace_v1.types.ListTracesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``traces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTraces`` requests and continue to iterate + through the ``traces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.trace_v1.types.ListTracesResponse` + 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[trace.ListTracesResponse]], + request: trace.ListTracesRequest, + response: trace.ListTracesResponse, + *, + 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.trace_v1.types.ListTracesRequest): + The initial request object. + response (google.cloud.trace_v1.types.ListTracesResponse): + 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 = trace.ListTracesRequest(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[trace.ListTracesResponse]: + 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[trace.Trace]: + async def async_generator(): + async for page in self.pages: + for response in page.traces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d3fe0b01934333eff5f74c10795261b1e15d4a9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/__init__.py @@ -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 TraceServiceTransport +from .grpc import TraceServiceGrpcTransport +from .grpc_asyncio import TraceServiceGrpcAsyncIOTransport +from .rest import TraceServiceRestInterceptor, TraceServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] +_transport_registry["grpc"] = TraceServiceGrpcTransport +_transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport +_transport_registry["rest"] = TraceServiceRestTransport + +__all__ = ( + "TraceServiceTransport", + "TraceServiceGrpcTransport", + "TraceServiceGrpcAsyncIOTransport", + "TraceServiceRestTransport", + "TraceServiceRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a3fdd76c5cac80fc22b1a9bd8d9520624993f8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/base.py @@ -0,0 +1,234 @@ +# -*- 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 +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v1 import gapic_version as package_version +from google.cloud.trace_v1.types import trace + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class TraceServiceTransport(abc.ABC): + """Abstract transport class for TraceService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ) + + DEFAULT_HOST: str = "cloudtrace.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: 'cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_traces: gapic_v1.method.wrap_method( + self.list_traces, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=45.0, + ), + default_timeout=45.0, + client_info=client_info, + ), + self.get_trace: gapic_v1.method.wrap_method( + self.get_trace, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=45.0, + ), + default_timeout=45.0, + client_info=client_info, + ), + self.patch_traces: gapic_v1.method.wrap_method( + self.patch_traces, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=45.0, + ), + default_timeout=45.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_traces( + self, + ) -> Callable[ + [trace.ListTracesRequest], + Union[trace.ListTracesResponse, Awaitable[trace.ListTracesResponse]], + ]: + raise NotImplementedError() + + @property + def get_trace( + self, + ) -> Callable[[trace.GetTraceRequest], Union[trace.Trace, Awaitable[trace.Trace]]]: + raise NotImplementedError() + + @property + def patch_traces( + self, + ) -> Callable[ + [trace.PatchTracesRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("TraceServiceTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..896d245dae9192c82444f63f45e08d6423052e92 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/grpc.py @@ -0,0 +1,423 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.trace_v1.types import trace + +from .base import DEFAULT_CLIENT_INFO, TraceServiceTransport + +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)!r}" + + 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.devtools.cloudtrace.v1.TraceService", + "rpcName": str(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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TraceServiceGrpcTransport(TraceServiceTransport): + """gRPC backend transport for TraceService. + + This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + + 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 = "cloudtrace.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: 'cloudtrace.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 = "cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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 list_traces( + self, + ) -> Callable[[trace.ListTracesRequest], trace.ListTracesResponse]: + r"""Return a callable for the list traces method over gRPC. + + Returns of a list of traces that match the specified + filter conditions. + + Returns: + Callable[[~.ListTracesRequest], + ~.ListTracesResponse]: + 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_traces" not in self._stubs: + self._stubs["list_traces"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/ListTraces", + request_serializer=trace.ListTracesRequest.serialize, + response_deserializer=trace.ListTracesResponse.deserialize, + ) + return self._stubs["list_traces"] + + @property + def get_trace(self) -> Callable[[trace.GetTraceRequest], trace.Trace]: + r"""Return a callable for the get trace method over gRPC. + + Gets a single trace by its ID. + + Returns: + Callable[[~.GetTraceRequest], + ~.Trace]: + 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_trace" not in self._stubs: + self._stubs["get_trace"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/GetTrace", + request_serializer=trace.GetTraceRequest.serialize, + response_deserializer=trace.Trace.deserialize, + ) + return self._stubs["get_trace"] + + @property + def patch_traces(self) -> Callable[[trace.PatchTracesRequest], empty_pb2.Empty]: + r"""Return a callable for the patch traces method over gRPC. + + Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + Returns: + Callable[[~.PatchTracesRequest], + ~.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 "patch_traces" not in self._stubs: + self._stubs["patch_traces"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/PatchTraces", + request_serializer=trace.PatchTracesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["patch_traces"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("TraceServiceGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..6f5b0e12e995869b9753f94b96c32187551ae00d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/grpc_asyncio.py @@ -0,0 +1,488 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.trace_v1.types import trace + +from .base import DEFAULT_CLIENT_INFO, TraceServiceTransport +from .grpc import TraceServiceGrpcTransport + +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)!r}" + + 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.devtools.cloudtrace.v1.TraceService", + "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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TraceServiceGrpcAsyncIOTransport(TraceServiceTransport): + """gRPC AsyncIO backend transport for TraceService. + + This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + + 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 = "cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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 = "cloudtrace.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: 'cloudtrace.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 list_traces( + self, + ) -> Callable[[trace.ListTracesRequest], Awaitable[trace.ListTracesResponse]]: + r"""Return a callable for the list traces method over gRPC. + + Returns of a list of traces that match the specified + filter conditions. + + Returns: + Callable[[~.ListTracesRequest], + Awaitable[~.ListTracesResponse]]: + 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_traces" not in self._stubs: + self._stubs["list_traces"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/ListTraces", + request_serializer=trace.ListTracesRequest.serialize, + response_deserializer=trace.ListTracesResponse.deserialize, + ) + return self._stubs["list_traces"] + + @property + def get_trace(self) -> Callable[[trace.GetTraceRequest], Awaitable[trace.Trace]]: + r"""Return a callable for the get trace method over gRPC. + + Gets a single trace by its ID. + + Returns: + Callable[[~.GetTraceRequest], + Awaitable[~.Trace]]: + 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_trace" not in self._stubs: + self._stubs["get_trace"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/GetTrace", + request_serializer=trace.GetTraceRequest.serialize, + response_deserializer=trace.Trace.deserialize, + ) + return self._stubs["get_trace"] + + @property + def patch_traces( + self, + ) -> Callable[[trace.PatchTracesRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the patch traces method over gRPC. + + Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + Returns: + Callable[[~.PatchTracesRequest], + 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 "patch_traces" not in self._stubs: + self._stubs["patch_traces"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/PatchTraces", + request_serializer=trace.PatchTracesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["patch_traces"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_traces: self._wrap_method( + self.list_traces, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=45.0, + ), + default_timeout=45.0, + client_info=client_info, + ), + self.get_trace: self._wrap_method( + self.get_trace, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=45.0, + ), + default_timeout=45.0, + client_info=client_info, + ), + self.patch_traces: self._wrap_method( + self.patch_traces, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=45.0, + ), + default_timeout=45.0, + 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" + + +__all__ = ("TraceServiceGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..d26a3fbeef2fd8d210c8f5f5a995b67a5dde22f3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/rest.py @@ -0,0 +1,747 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.trace_v1.types import trace + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTraceServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class TraceServiceRestInterceptor: + """Interceptor for TraceService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the TraceServiceRestTransport. + + .. code-block:: python + class MyCustomTraceServiceInterceptor(TraceServiceRestInterceptor): + def pre_get_trace(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_trace(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_traces(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_traces(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_patch_traces(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + transport = TraceServiceRestTransport(interceptor=MyCustomTraceServiceInterceptor()) + client = TraceServiceClient(transport=transport) + + + """ + + def pre_get_trace( + self, + request: trace.GetTraceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[trace.GetTraceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_trace + + Override in a subclass to manipulate the request or metadata + before they are sent to the TraceService server. + """ + return request, metadata + + def post_get_trace(self, response: trace.Trace) -> trace.Trace: + """Post-rpc interceptor for get_trace + + DEPRECATED. Please use the `post_get_trace_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TraceService server but before + it is returned to user code. This `post_get_trace` interceptor runs + before the `post_get_trace_with_metadata` interceptor. + """ + return response + + def post_get_trace_with_metadata( + self, response: trace.Trace, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[trace.Trace, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_trace + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TraceService server but before it is returned to user code. + + We recommend only using this `post_get_trace_with_metadata` + interceptor in new development instead of the `post_get_trace` interceptor. + When both interceptors are used, this `post_get_trace_with_metadata` interceptor runs after the + `post_get_trace` interceptor. The (possibly modified) response returned by + `post_get_trace` will be passed to + `post_get_trace_with_metadata`. + """ + return response, metadata + + def pre_list_traces( + self, + request: trace.ListTracesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[trace.ListTracesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_traces + + Override in a subclass to manipulate the request or metadata + before they are sent to the TraceService server. + """ + return request, metadata + + def post_list_traces( + self, response: trace.ListTracesResponse + ) -> trace.ListTracesResponse: + """Post-rpc interceptor for list_traces + + DEPRECATED. Please use the `post_list_traces_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TraceService server but before + it is returned to user code. This `post_list_traces` interceptor runs + before the `post_list_traces_with_metadata` interceptor. + """ + return response + + def post_list_traces_with_metadata( + self, + response: trace.ListTracesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[trace.ListTracesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_traces + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TraceService server but before it is returned to user code. + + We recommend only using this `post_list_traces_with_metadata` + interceptor in new development instead of the `post_list_traces` interceptor. + When both interceptors are used, this `post_list_traces_with_metadata` interceptor runs after the + `post_list_traces` interceptor. The (possibly modified) response returned by + `post_list_traces` will be passed to + `post_list_traces_with_metadata`. + """ + return response, metadata + + def pre_patch_traces( + self, + request: trace.PatchTracesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[trace.PatchTracesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for patch_traces + + Override in a subclass to manipulate the request or metadata + before they are sent to the TraceService server. + """ + return request, metadata + + +@dataclasses.dataclass +class TraceServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TraceServiceRestInterceptor + + +class TraceServiceRestTransport(_BaseTraceServiceRestTransport): + """REST backend synchronous transport for TraceService. + + This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + + 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 = "cloudtrace.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[TraceServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[TraceServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or TraceServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetTrace(_BaseTraceServiceRestTransport._BaseGetTrace, TraceServiceRestStub): + def __hash__(self): + return hash("TraceServiceRestTransport.GetTrace") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: trace.GetTraceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trace.Trace: + r"""Call the get trace method over HTTP. + + Args: + request (~.trace.GetTraceRequest): + The request object. The request message for the ``GetTrace`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.trace.Trace: + A trace describes how long it takes + for an application to perform an + operation. It consists of a set of + spans, each of which represent a single + timed event within the operation. + + """ + + http_options = ( + _BaseTraceServiceRestTransport._BaseGetTrace._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_trace(request, metadata) + transcoded_request = ( + _BaseTraceServiceRestTransport._BaseGetTrace._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseTraceServiceRestTransport._BaseGetTrace._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.devtools.cloudtrace_v1.TraceServiceClient.GetTrace", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "rpcName": "GetTrace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TraceServiceRestTransport._GetTrace._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = trace.Trace() + pb_resp = trace.Trace.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_trace(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_trace_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = trace.Trace.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.devtools.cloudtrace_v1.TraceServiceClient.get_trace", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "rpcName": "GetTrace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTraces( + _BaseTraceServiceRestTransport._BaseListTraces, TraceServiceRestStub + ): + def __hash__(self): + return hash("TraceServiceRestTransport.ListTraces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: trace.ListTracesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trace.ListTracesResponse: + r"""Call the list traces method over HTTP. + + Args: + request (~.trace.ListTracesRequest): + The request object. The request message for the ``ListTraces`` method. All + fields are required unless specified. + 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`. + + Returns: + ~.trace.ListTracesResponse: + The response message for the ``ListTraces`` method. + """ + + http_options = ( + _BaseTraceServiceRestTransport._BaseListTraces._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_traces(request, metadata) + transcoded_request = ( + _BaseTraceServiceRestTransport._BaseListTraces._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseTraceServiceRestTransport._BaseListTraces._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.devtools.cloudtrace_v1.TraceServiceClient.ListTraces", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "rpcName": "ListTraces", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TraceServiceRestTransport._ListTraces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = trace.ListTracesResponse() + pb_resp = trace.ListTracesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_traces(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_traces_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = trace.ListTracesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.devtools.cloudtrace_v1.TraceServiceClient.list_traces", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "rpcName": "ListTraces", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PatchTraces( + _BaseTraceServiceRestTransport._BasePatchTraces, TraceServiceRestStub + ): + def __hash__(self): + return hash("TraceServiceRestTransport.PatchTraces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: trace.PatchTracesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the patch traces method over HTTP. + + Args: + request (~.trace.PatchTracesRequest): + The request object. The request message for the ``PatchTraces`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseTraceServiceRestTransport._BasePatchTraces._get_http_options() + ) + + request, metadata = self._interceptor.pre_patch_traces(request, metadata) + transcoded_request = ( + _BaseTraceServiceRestTransport._BasePatchTraces._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseTraceServiceRestTransport._BasePatchTraces._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseTraceServiceRestTransport._BasePatchTraces._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.devtools.cloudtrace_v1.TraceServiceClient.PatchTraces", + extra={ + "serviceName": "google.devtools.cloudtrace.v1.TraceService", + "rpcName": "PatchTraces", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TraceServiceRestTransport._PatchTraces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + @property + def get_trace(self) -> Callable[[trace.GetTraceRequest], trace.Trace]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTrace(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_traces( + self, + ) -> Callable[[trace.ListTracesRequest], trace.ListTracesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTraces(self._session, self._host, self._interceptor) # type: ignore + + @property + def patch_traces(self) -> Callable[[trace.PatchTracesRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PatchTraces(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("TraceServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e7eb7b094a6298f7cca37d5719bed5dd92b00fc3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/services/trace_service/transports/rest_base.py @@ -0,0 +1,243 @@ +# -*- 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 + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.trace_v1.types import trace + +from .base import DEFAULT_CLIENT_INFO, TraceServiceTransport + + +class _BaseTraceServiceRestTransport(TraceServiceTransport): + """Base REST backend transport for TraceService. + + 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 = "cloudtrace.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: 'cloudtrace.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("^(?Phttp(?:s)?://)?(?P.*)$", 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 _BaseGetTrace: + 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": "/v1/projects/{project_id}/traces/{trace_id}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = trace.GetTraceRequest.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( + _BaseTraceServiceRestTransport._BaseGetTrace._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTraces: + 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": "/v1/projects/{project_id}/traces", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = trace.ListTracesRequest.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( + _BaseTraceServiceRestTransport._BaseListTraces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePatchTraces: + 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": "/v1/projects/{project_id}/traces", + "body": "traces", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = trace.PatchTracesRequest.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( + _BaseTraceServiceRestTransport._BasePatchTraces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseTraceServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..575f4daa1995572e42ea94a8d66731f2259a195e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/types/__init__.py @@ -0,0 +1,34 @@ +# -*- 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 .trace import ( + GetTraceRequest, + ListTracesRequest, + ListTracesResponse, + PatchTracesRequest, + Trace, + Traces, + TraceSpan, +) + +__all__ = ( + "GetTraceRequest", + "ListTracesRequest", + "ListTracesResponse", + "PatchTracesRequest", + "Trace", + "Traces", + "TraceSpan", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/types/trace.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/types/trace.py new file mode 100644 index 0000000000000000000000000000000000000000..8acd14fd9bf1f2bafb510f80cc61265bed28142d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v1/types/trace.py @@ -0,0 +1,427 @@ +# -*- 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 + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.devtools.cloudtrace.v1", + manifest={ + "Trace", + "Traces", + "TraceSpan", + "ListTracesRequest", + "ListTracesResponse", + "GetTraceRequest", + "PatchTracesRequest", + }, +) + + +class Trace(proto.Message): + r"""A trace describes how long it takes for an application to + perform an operation. It consists of a set of spans, each of + which represent a single timed event within the operation. + + Attributes: + project_id (str): + Project ID of the Cloud project where the + trace data is stored. + trace_id (str): + Globally unique identifier for the trace. This identifier is + a 128-bit numeric value formatted as a 32-byte hex string. + For example, ``382d4f4c6b7bb2f4a972559d9085001d``. + spans (MutableSequence[google.cloud.trace_v1.types.TraceSpan]): + Collection of spans in the trace. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + trace_id: str = proto.Field( + proto.STRING, + number=2, + ) + spans: MutableSequence["TraceSpan"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="TraceSpan", + ) + + +class Traces(proto.Message): + r"""List of new or updated traces. + + Attributes: + traces (MutableSequence[google.cloud.trace_v1.types.Trace]): + List of traces. + """ + + traces: MutableSequence["Trace"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Trace", + ) + + +class TraceSpan(proto.Message): + r"""A span represents a single timed event within a trace. Spans + can be nested and form a trace tree. Often, a trace contains a + root span that describes the end-to-end latency of an operation + and, optionally, one or more subspans for its suboperations. + Spans do not need to be contiguous. There may be gaps between + spans in a trace. + + Attributes: + span_id (int): + Identifier for the span. Must be a 64-bit integer other than + 0 and unique within a trace. For example, + ``2205310701640571284``. + kind (google.cloud.trace_v1.types.TraceSpan.SpanKind): + Distinguishes between spans generated in a particular + context. For example, two spans with the same name may be + distinguished using ``RPC_CLIENT`` and ``RPC_SERVER`` to + identify queueing latency associated with the span. + name (str): + Name of the span. Must be less than 128 + bytes. The span name is sanitized and displayed + in the Stackdriver Trace tool in the Google + Cloud Platform Console. + The name may be a method name or some other + per-call site name. For the same executable and + the same call point, a best practice is to use a + consistent name, which makes it easier to + correlate cross-trace spans. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of the span in nanoseconds from + the UNIX epoch. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the span in nanoseconds from the + UNIX epoch. + parent_span_id (int): + Optional. ID of the parent span, if any. + labels (MutableMapping[str, str]): + Collection of labels associated with the span. Label keys + must be less than 128 bytes. Label values must be less than + 16 kilobytes (10MB for ``/stacktrace`` values). + + Some predefined label keys exist, or you may create your + own. When creating your own, we recommend the following + formats: + + - ``/category/product/key`` for agents of well-known + products (e.g. ``/db/mongodb/read_size``). + - ``short_host/path/key`` for domain-specific keys (e.g. + ``foo.com/myproduct/bar``) + + Predefined labels include: + + - ``/agent`` + - ``/component`` + - ``/error/message`` + - ``/error/name`` + - ``/http/client_city`` + - ``/http/client_country`` + - ``/http/client_protocol`` + - ``/http/client_region`` + - ``/http/host`` + - ``/http/method`` + - ``/http/path`` + - ``/http/redirected_url`` + - ``/http/request/size`` + - ``/http/response/size`` + - ``/http/route`` + - ``/http/status_code`` + - ``/http/url`` + - ``/http/user_agent`` + - ``/pid`` + - ``/stacktrace`` + - ``/tid`` + """ + + class SpanKind(proto.Enum): + r"""Type of span. Can be used to specify additional relationships + between spans in addition to a parent/child relationship. + + Values: + SPAN_KIND_UNSPECIFIED (0): + Unspecified. + RPC_SERVER (1): + Indicates that the span covers server-side + handling of an RPC or other remote network + request. + RPC_CLIENT (2): + Indicates that the span covers the + client-side wrapper around an RPC or other + remote request. + """ + + SPAN_KIND_UNSPECIFIED = 0 + RPC_SERVER = 1 + RPC_CLIENT = 2 + + span_id: int = proto.Field( + proto.FIXED64, + number=1, + ) + kind: SpanKind = proto.Field( + proto.ENUM, + number=2, + enum=SpanKind, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + parent_span_id: int = proto.Field( + proto.FIXED64, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +class ListTracesRequest(proto.Message): + r"""The request message for the ``ListTraces`` method. All fields are + required unless specified. + + Attributes: + project_id (str): + Required. ID of the Cloud project where the + trace data is stored. + view (google.cloud.trace_v1.types.ListTracesRequest.ViewType): + Optional. Type of data returned for traces in the list. + Default is ``MINIMAL``. + page_size (int): + Optional. Maximum number of traces to return. + If not specified or <= 0, the implementation + selects a reasonable value. The implementation + may return fewer traces than the requested page + size. + page_token (str): + Token identifying the page of results to return. If + provided, use the value of the ``next_page_token`` field + from a previous request. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of the time interval (inclusive) during + which the trace data was collected from the + application. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End of the time interval (inclusive) during + which the trace data was collected from the + application. + filter (str): + Optional. A filter against labels for the request. + + By default, searches use prefix matching. To specify exact + match, prepend a plus symbol (``+``) to the search term. + Multiple terms are ANDed. Syntax: + + - ``root:NAME_PREFIX`` or ``NAME_PREFIX``: Return traces + where any root span starts with ``NAME_PREFIX``. + - ``+root:NAME`` or ``+NAME``: Return traces where any root + span's name is exactly ``NAME``. + - ``span:NAME_PREFIX``: Return traces where any span starts + with ``NAME_PREFIX``. + - ``+span:NAME``: Return traces where any span's name is + exactly ``NAME``. + - ``latency:DURATION``: Return traces whose overall latency + is greater or equal to than ``DURATION``. Accepted units + are nanoseconds (``ns``), milliseconds (``ms``), and + seconds (``s``). Default is ``ms``. For example, + ``latency:24ms`` returns traces whose overall latency is + greater than or equal to 24 milliseconds. + - ``label:LABEL_KEY``: Return all traces containing the + specified label key (exact match, case-sensitive) + regardless of the key:value pair's value (including empty + values). + - ``LABEL_KEY:VALUE_PREFIX``: Return all traces containing + the specified label key (exact match, case-sensitive) + whose value starts with ``VALUE_PREFIX``. Both a key and a + value must be specified. + - ``+LABEL_KEY:VALUE``: Return all traces containing a + key:value pair exactly matching the specified text. Both a + key and a value must be specified. + - ``method:VALUE``: Equivalent to ``/http/method:VALUE``. + - ``url:VALUE``: Equivalent to ``/http/url:VALUE``. + order_by (str): + Optional. Field used to sort the returned traces. Can be one + of the following: + + - ``trace_id`` + - ``name`` (``name`` field of root span in the trace) + - ``duration`` (difference between ``end_time`` and + ``start_time`` fields of the root span) + - ``start`` (``start_time`` field of the root span) + + Descending order can be specified by appending ``desc`` to + the sort field (for example, ``name desc``). + + Only one sort field is permitted. + """ + + class ViewType(proto.Enum): + r"""Type of data returned for traces in the list. + + Values: + VIEW_TYPE_UNSPECIFIED (0): + Default is ``MINIMAL`` if unspecified. + MINIMAL (1): + Minimal view of the trace record that + contains only the project and trace IDs. + ROOTSPAN (2): + Root span view of the trace record that + returns the root spans along with the minimal + trace data. + COMPLETE (3): + Complete view of the trace record that contains the actual + trace data. This is equivalent to calling the REST ``get`` + or RPC ``GetTrace`` method using the ID of each listed + trace. + """ + + VIEW_TYPE_UNSPECIFIED = 0 + MINIMAL = 1 + ROOTSPAN = 2 + COMPLETE = 3 + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + view: ViewType = proto.Field( + proto.ENUM, + number=2, + enum=ViewType, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + filter: str = proto.Field( + proto.STRING, + number=7, + ) + order_by: str = proto.Field( + proto.STRING, + number=8, + ) + + +class ListTracesResponse(proto.Message): + r"""The response message for the ``ListTraces`` method. + + Attributes: + traces (MutableSequence[google.cloud.trace_v1.types.Trace]): + List of trace records as specified by the + view parameter. + next_page_token (str): + If defined, indicates that there are more + traces that match the request and that this + value should be passed to the next request to + continue retrieving additional traces. + """ + + @property + def raw_page(self): + return self + + traces: MutableSequence["Trace"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Trace", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTraceRequest(proto.Message): + r"""The request message for the ``GetTrace`` method. + + Attributes: + project_id (str): + Required. ID of the Cloud project where the + trace data is stored. + trace_id (str): + Required. ID of the trace to return. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + trace_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PatchTracesRequest(proto.Message): + r"""The request message for the ``PatchTraces`` method. + + Attributes: + project_id (str): + Required. ID of the Cloud project where the + trace data is stored. + traces (google.cloud.trace_v1.types.Traces): + Required. The body of the message. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + traces: "Traces" = proto.Field( + proto.MESSAGE, + number=2, + message="Traces", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..388317837ed6a1de43c77411724685f9e2988152 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/__init__.py @@ -0,0 +1,139 @@ +# -*- 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 sys + +import google.api_core as api_core + +from google.cloud.trace_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.trace_service import TraceServiceAsyncClient, TraceServiceClient +from .types.trace import AttributeValue, Module, Span, StackTrace, TruncatableString +from .types.tracing import BatchWriteSpansRequest + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.trace_v2") # type: ignore + api_core.check_dependency_versions("google.cloud.trace_v2") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.trace_v2" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "TraceServiceAsyncClient", + "AttributeValue", + "BatchWriteSpansRequest", + "Module", + "Span", + "StackTrace", + "TraceServiceClient", + "TruncatableString", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..47eae47671adeac7cf88f99ab9e388f2f4d64e30 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.trace_v2", + "protoPackage": "google.devtools.cloudtrace.v2", + "schema": "1.0", + "services": { + "TraceService": { + "clients": { + "grpc": { + "libraryClient": "TraceServiceClient", + "rpcs": { + "BatchWriteSpans": { + "methods": [ + "batch_write_spans" + ] + }, + "CreateSpan": { + "methods": [ + "create_span" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TraceServiceAsyncClient", + "rpcs": { + "BatchWriteSpans": { + "methods": [ + "batch_write_spans" + ] + }, + "CreateSpan": { + "methods": [ + "create_span" + ] + } + } + }, + "rest": { + "libraryClient": "TraceServiceClient", + "rpcs": { + "BatchWriteSpans": { + "methods": [ + "batch_write_spans" + ] + }, + "CreateSpan": { + "methods": [ + "create_span" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..7313c97c30967bee5f1c5555b99e753ea22ae2de --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/gapic_version.py @@ -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__ = "1.19.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..4717a6c0faf00d07c451b77145c88d1d773cadb3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-trace package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/__init__.py @@ -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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7fbf701aae3c2a3acbd7166351e133c6ab9b466 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/__init__.py @@ -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 TraceServiceAsyncClient +from .client import TraceServiceClient + +__all__ = ( + "TraceServiceClient", + "TraceServiceAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0dd61555ab988628ea8f04f5616f942885f0dc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/async_client.py @@ -0,0 +1,539 @@ +# -*- 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +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.trace_v2 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 + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore + +from google.cloud.trace_v2.types import trace, tracing + +from .client import TraceServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, TraceServiceTransport +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport + +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 TraceServiceAsyncClient: + """Service for collecting and viewing traces and spans within a + trace. + A trace is a collection of spans corresponding to a single + operation or a set of operations in an application. + + A span is an individual timed event which forms a node of the + trace tree. A single trace can contain spans from multiple + services. + """ + + _client: TraceServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TraceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TraceServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TraceServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TraceServiceClient._DEFAULT_UNIVERSE + + span_path = staticmethod(TraceServiceClient.span_path) + parse_span_path = staticmethod(TraceServiceClient.parse_span_path) + common_billing_account_path = staticmethod( + TraceServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + TraceServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(TraceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TraceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TraceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + TraceServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(TraceServiceClient.common_project_path) + parse_common_project_path = staticmethod( + TraceServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(TraceServiceClient.common_location_path) + parse_common_location_path = staticmethod( + TraceServiceClient.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: + TraceServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + TraceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(TraceServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TraceServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + TraceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(TraceServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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 TraceServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TraceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TraceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = TraceServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, TraceServiceTransport, Callable[..., TraceServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trace service 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,TraceServiceTransport,Callable[..., TraceServiceTransport]]]): + 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 TraceServiceTransport 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 = TraceServiceClient( + 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.devtools.cloudtrace_v2.TraceServiceAsyncClient`.", + extra={ + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "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.devtools.cloudtrace.v2.TraceService", + "credentialsType": None, + }, + ) + + async def batch_write_spans( + self, + request: Optional[Union[tracing.BatchWriteSpansRequest, dict]] = None, + *, + name: Optional[str] = None, + spans: Optional[MutableSequence[trace.Span]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Batch writes new spans to new or existing traces. You + cannot update existing spans. + + .. 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 trace_v2 + + async def sample_batch_write_spans(): + # Create a client + client = trace_v2.TraceServiceAsyncClient() + + # Initialize request argument(s) + spans = trace_v2.Span() + spans.name = "name_value" + spans.span_id = "span_id_value" + + request = trace_v2.BatchWriteSpansRequest( + name="name_value", + spans=spans, + ) + + # Make the request + await client.batch_write_spans(request=request) + + Args: + request (Optional[Union[google.cloud.trace_v2.types.BatchWriteSpansRequest, dict]]): + The request object. The request message for the ``BatchWriteSpans`` method. + name (:class:`str`): + Required. The name of the project where the spans + belong. The format is ``projects/[PROJECT_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + spans (:class:`MutableSequence[google.cloud.trace_v2.types.Span]`): + Required. A list of new spans. The + span names must not match existing + spans, otherwise the results are + undefined. + + This corresponds to the ``spans`` 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`. + """ + # 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 = [name, spans] + 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, tracing.BatchWriteSpansRequest): + request = tracing.BatchWriteSpansRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if spans: + request.spans.extend(spans) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_write_spans + ] + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_span( + self, + request: Optional[Union[trace.Span, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trace.Span: + r"""Creates a new span. + + .. 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 trace_v2 + + async def sample_create_span(): + # Create a client + client = trace_v2.TraceServiceAsyncClient() + + # Initialize request argument(s) + request = trace_v2.Span( + name="name_value", + span_id="span_id_value", + ) + + # Make the request + response = await client.create_span(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.trace_v2.types.Span, dict]]): + The request object. A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. + + A trace can also contain multiple root + spans, or none at all. Spans do not need + to be contiguous. There might be gaps or + overlaps between spans in a trace. + 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.trace_v2.types.Span: + A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. + + A trace can also contain multiple root + spans, or none at all. Spans do not need + to be contiguous. There might be gaps or + overlaps between spans in a trace. + + """ + # Create or coerce a protobuf request object. + # - 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, trace.Span): + request = trace.Span(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_span + ] + + # 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) -> "TraceServiceAsyncClient": + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("TraceServiceAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..2e166abec4c40b41fd8935bfd5380f7f211880db --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/client.py @@ -0,0 +1,975 @@ +# -*- 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 os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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__) + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore + +from google.cloud.trace_v2.types import trace, tracing + +from .transports.base import DEFAULT_CLIENT_INFO, TraceServiceTransport +from .transports.grpc import TraceServiceGrpcTransport +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport +from .transports.rest import TraceServiceRestTransport + + +class TraceServiceClientMeta(type): + """Metaclass for the TraceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] + _transport_registry["grpc"] = TraceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TraceServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[TraceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TraceServiceClient(metaclass=TraceServiceClientMeta): + """Service for collecting and viewing traces and spans within a + trace. + A trace is a collection of spans corresponding to a single + operation or a set of operations in an application. + + A span is an individual timed event which forms a node of the + trace tree. A single trace can contain spans from multiple + services. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudtrace.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudtrace.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + TraceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TraceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TraceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TraceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def span_path( + project: str, + trace: str, + span: str, + ) -> str: + """Returns a fully-qualified span string.""" + return "projects/{project}/traces/{trace}/spans/{span}".format( + project=project, + trace=trace, + span=span, + ) + + @staticmethod + def parse_span_path(path: str) -> Dict[str, str]: + """Parses a span path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/traces/(?P.+?)/spans/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. 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. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = TraceServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = TraceServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = TraceServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = TraceServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TraceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = TraceServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._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._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, TraceServiceTransport, Callable[..., TraceServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trace service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,TraceServiceTransport,Callable[..., TraceServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the TraceServiceTransport 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 the ``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_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + TraceServiceClient._read_environment_variables() + ) + self._client_cert_source = TraceServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = TraceServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, TraceServiceTransport) + if transport_provided: + # transport is a TraceServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(TraceServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or TraceServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[TraceServiceTransport], Callable[..., TraceServiceTransport] + ] = ( + TraceServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TraceServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.devtools.cloudtrace_v2.TraceServiceClient`.", + extra={ + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "credentialsType": None, + }, + ) + + def batch_write_spans( + self, + request: Optional[Union[tracing.BatchWriteSpansRequest, dict]] = None, + *, + name: Optional[str] = None, + spans: Optional[MutableSequence[trace.Span]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Batch writes new spans to new or existing traces. You + cannot update existing spans. + + .. 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 trace_v2 + + def sample_batch_write_spans(): + # Create a client + client = trace_v2.TraceServiceClient() + + # Initialize request argument(s) + spans = trace_v2.Span() + spans.name = "name_value" + spans.span_id = "span_id_value" + + request = trace_v2.BatchWriteSpansRequest( + name="name_value", + spans=spans, + ) + + # Make the request + client.batch_write_spans(request=request) + + Args: + request (Union[google.cloud.trace_v2.types.BatchWriteSpansRequest, dict]): + The request object. The request message for the ``BatchWriteSpans`` method. + name (str): + Required. The name of the project where the spans + belong. The format is ``projects/[PROJECT_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + spans (MutableSequence[google.cloud.trace_v2.types.Span]): + Required. A list of new spans. The + span names must not match existing + spans, otherwise the results are + undefined. + + This corresponds to the ``spans`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + # 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 = [name, spans] + 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, tracing.BatchWriteSpansRequest): + request = tracing.BatchWriteSpansRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if spans is not None: + request.spans = spans + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_write_spans] + + # 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._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_span( + self, + request: Optional[Union[trace.Span, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trace.Span: + r"""Creates a new span. + + .. 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 trace_v2 + + def sample_create_span(): + # Create a client + client = trace_v2.TraceServiceClient() + + # Initialize request argument(s) + request = trace_v2.Span( + name="name_value", + span_id="span_id_value", + ) + + # Make the request + response = client.create_span(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.trace_v2.types.Span, dict]): + The request object. A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. + + A trace can also contain multiple root + spans, or none at all. Spans do not need + to be contiguous. There might be gaps or + overlaps between spans in a trace. + 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`. + + Returns: + google.cloud.trace_v2.types.Span: + A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. + + A trace can also contain multiple root + spans, or none at all. Spans do not need + to be contiguous. There might be gaps or + overlaps between spans in a trace. + + """ + # Create or coerce a protobuf request object. + # - 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, trace.Span): + request = trace.Span(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_span] + + # 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._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "TraceServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("TraceServiceClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d3fe0b01934333eff5f74c10795261b1e15d4a9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/__init__.py @@ -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 TraceServiceTransport +from .grpc import TraceServiceGrpcTransport +from .grpc_asyncio import TraceServiceGrpcAsyncIOTransport +from .rest import TraceServiceRestInterceptor, TraceServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] +_transport_registry["grpc"] = TraceServiceGrpcTransport +_transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport +_transport_registry["rest"] = TraceServiceRestTransport + +__all__ = ( + "TraceServiceTransport", + "TraceServiceGrpcTransport", + "TraceServiceGrpcAsyncIOTransport", + "TraceServiceRestTransport", + "TraceServiceRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c57551432239b360291c3e1cf9949fae304559 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/base.py @@ -0,0 +1,210 @@ +# -*- 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 +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v2 import gapic_version as package_version +from google.cloud.trace_v2.types import trace, tracing + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class TraceServiceTransport(abc.ABC): + """Abstract transport class for TraceService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ) + + DEFAULT_HOST: str = "cloudtrace.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: 'cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_write_spans: gapic_v1.method.wrap_method( + self.batch_write_spans, + default_retry=retries.Retry( + initial=0.1, + maximum=30.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.create_span: gapic_v1.method.wrap_method( + self.create_span, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def batch_write_spans( + self, + ) -> Callable[ + [tracing.BatchWriteSpansRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_span( + self, + ) -> Callable[[trace.Span], Union[trace.Span, Awaitable[trace.Span]]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("TraceServiceTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..d480a3367228f6b999b0b4ee84f269154037d8d6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/grpc.py @@ -0,0 +1,395 @@ +# -*- 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 +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.trace_v2.types import trace, tracing + +from .base import DEFAULT_CLIENT_INFO, TraceServiceTransport + +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)!r}" + + 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.devtools.cloudtrace.v2.TraceService", + "rpcName": str(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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TraceServiceGrpcTransport(TraceServiceTransport): + """gRPC backend transport for TraceService. + + Service for collecting and viewing traces and spans within a + trace. + A trace is a collection of spans corresponding to a single + operation or a set of operations in an application. + + A span is an individual timed event which forms a node of the + trace tree. A single trace can contain spans from multiple + services. + + 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 = "cloudtrace.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: 'cloudtrace.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 = "cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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 batch_write_spans( + self, + ) -> Callable[[tracing.BatchWriteSpansRequest], empty_pb2.Empty]: + r"""Return a callable for the batch write spans method over gRPC. + + Batch writes new spans to new or existing traces. You + cannot update existing spans. + + Returns: + Callable[[~.BatchWriteSpansRequest], + ~.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 "batch_write_spans" not in self._stubs: + self._stubs["batch_write_spans"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans", + request_serializer=tracing.BatchWriteSpansRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["batch_write_spans"] + + @property + def create_span(self) -> Callable[[trace.Span], trace.Span]: + r"""Return a callable for the create span method over gRPC. + + Creates a new span. + + Returns: + Callable[[~.Span], + ~.Span]: + 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_span" not in self._stubs: + self._stubs["create_span"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/CreateSpan", + request_serializer=trace.Span.serialize, + response_deserializer=trace.Span.deserialize, + ) + return self._stubs["create_span"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("TraceServiceGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..8af55a2ba7e52d21be27e8eae36b78370b519515 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/grpc_asyncio.py @@ -0,0 +1,443 @@ +# -*- 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 +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +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.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.trace_v2.types import trace, tracing + +from .base import DEFAULT_CLIENT_INFO, TraceServiceTransport +from .grpc import TraceServiceGrpcTransport + +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)!r}" + + 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.devtools.cloudtrace.v2.TraceService", + "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 `` 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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TraceServiceGrpcAsyncIOTransport(TraceServiceTransport): + """gRPC AsyncIO backend transport for TraceService. + + Service for collecting and viewing traces and spans within a + trace. + A trace is a collection of spans corresponding to a single + operation or a set of operations in an application. + + A span is an individual timed event which forms a node of the + trace tree. A single trace can contain spans from multiple + services. + + 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 = "cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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 = "cloudtrace.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: 'cloudtrace.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]): Deprecated. 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. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 batch_write_spans( + self, + ) -> Callable[[tracing.BatchWriteSpansRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the batch write spans method over gRPC. + + Batch writes new spans to new or existing traces. You + cannot update existing spans. + + Returns: + Callable[[~.BatchWriteSpansRequest], + 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 "batch_write_spans" not in self._stubs: + self._stubs["batch_write_spans"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans", + request_serializer=tracing.BatchWriteSpansRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["batch_write_spans"] + + @property + def create_span(self) -> Callable[[trace.Span], Awaitable[trace.Span]]: + r"""Return a callable for the create span method over gRPC. + + Creates a new span. + + Returns: + Callable[[~.Span], + Awaitable[~.Span]]: + 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_span" not in self._stubs: + self._stubs["create_span"] = self._logged_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/CreateSpan", + request_serializer=trace.Span.serialize, + response_deserializer=trace.Span.deserialize, + ) + return self._stubs["create_span"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.batch_write_spans: self._wrap_method( + self.batch_write_spans, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=30.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.create_span: self._wrap_method( + self.create_span, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + 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" + + +__all__ = ("TraceServiceGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..f15387c75ba5e4b554edae444de097686ded741e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/rest.py @@ -0,0 +1,560 @@ +# -*- 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.trace_v2.types import trace, tracing + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTraceServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +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 = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class TraceServiceRestInterceptor: + """Interceptor for TraceService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the TraceServiceRestTransport. + + .. code-block:: python + class MyCustomTraceServiceInterceptor(TraceServiceRestInterceptor): + def pre_batch_write_spans(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_create_span(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_span(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TraceServiceRestTransport(interceptor=MyCustomTraceServiceInterceptor()) + client = TraceServiceClient(transport=transport) + + + """ + + def pre_batch_write_spans( + self, + request: tracing.BatchWriteSpansRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tracing.BatchWriteSpansRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for batch_write_spans + + Override in a subclass to manipulate the request or metadata + before they are sent to the TraceService server. + """ + return request, metadata + + def pre_create_span( + self, request: trace.Span, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[trace.Span, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_span + + Override in a subclass to manipulate the request or metadata + before they are sent to the TraceService server. + """ + return request, metadata + + def post_create_span(self, response: trace.Span) -> trace.Span: + """Post-rpc interceptor for create_span + + DEPRECATED. Please use the `post_create_span_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TraceService server but before + it is returned to user code. This `post_create_span` interceptor runs + before the `post_create_span_with_metadata` interceptor. + """ + return response + + def post_create_span_with_metadata( + self, response: trace.Span, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[trace.Span, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_span + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TraceService server but before it is returned to user code. + + We recommend only using this `post_create_span_with_metadata` + interceptor in new development instead of the `post_create_span` interceptor. + When both interceptors are used, this `post_create_span_with_metadata` interceptor runs after the + `post_create_span` interceptor. The (possibly modified) response returned by + `post_create_span` will be passed to + `post_create_span_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class TraceServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TraceServiceRestInterceptor + + +class TraceServiceRestTransport(_BaseTraceServiceRestTransport): + """REST backend synchronous transport for TraceService. + + Service for collecting and viewing traces and spans within a + trace. + A trace is a collection of spans corresponding to a single + operation or a set of operations in an application. + + A span is an individual timed event which forms a node of the + trace tree. A single trace can contain spans from multiple + services. + + 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 = "cloudtrace.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[TraceServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudtrace.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[TraceServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or TraceServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchWriteSpans( + _BaseTraceServiceRestTransport._BaseBatchWriteSpans, TraceServiceRestStub + ): + def __hash__(self): + return hash("TraceServiceRestTransport.BatchWriteSpans") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: tracing.BatchWriteSpansRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the batch write spans method over HTTP. + + Args: + request (~.tracing.BatchWriteSpansRequest): + The request object. The request message for the ``BatchWriteSpans`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = ( + _BaseTraceServiceRestTransport._BaseBatchWriteSpans._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_write_spans( + request, metadata + ) + transcoded_request = _BaseTraceServiceRestTransport._BaseBatchWriteSpans._get_transcoded_request( + http_options, request + ) + + body = _BaseTraceServiceRestTransport._BaseBatchWriteSpans._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseTraceServiceRestTransport._BaseBatchWriteSpans._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.devtools.cloudtrace_v2.TraceServiceClient.BatchWriteSpans", + extra={ + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "rpcName": "BatchWriteSpans", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TraceServiceRestTransport._BatchWriteSpans._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _CreateSpan( + _BaseTraceServiceRestTransport._BaseCreateSpan, TraceServiceRestStub + ): + def __hash__(self): + return hash("TraceServiceRestTransport.CreateSpan") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: trace.Span, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trace.Span: + r"""Call the create span method over HTTP. + + Args: + request (~.trace.Span): + The request object. A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. + + A trace can also contain multiple root + spans, or none at all. Spans do not need + to be contiguous. There might be gaps or + overlaps between spans in a trace. + 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`. + + Returns: + ~.trace.Span: + A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. + + A trace can also contain multiple root + spans, or none at all. Spans do not need + to be contiguous. There might be gaps or + overlaps between spans in a trace. + + """ + + http_options = ( + _BaseTraceServiceRestTransport._BaseCreateSpan._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_span(request, metadata) + transcoded_request = ( + _BaseTraceServiceRestTransport._BaseCreateSpan._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseTraceServiceRestTransport._BaseCreateSpan._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseTraceServiceRestTransport._BaseCreateSpan._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.devtools.cloudtrace_v2.TraceServiceClient.CreateSpan", + extra={ + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "rpcName": "CreateSpan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TraceServiceRestTransport._CreateSpan._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = trace.Span() + pb_resp = trace.Span.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_span(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_span_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = trace.Span.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.devtools.cloudtrace_v2.TraceServiceClient.create_span", + extra={ + "serviceName": "google.devtools.cloudtrace.v2.TraceService", + "rpcName": "CreateSpan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_write_spans( + self, + ) -> Callable[[tracing.BatchWriteSpansRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchWriteSpans(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_span(self) -> Callable[[trace.Span], trace.Span]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSpan(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("TraceServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..fead8a31b8d107c3f8b4b5bc37f9e482a3324d12 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/services/trace_service/transports/rest_base.py @@ -0,0 +1,206 @@ +# -*- 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 + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.trace_v2.types import trace, tracing + +from .base import DEFAULT_CLIENT_INFO, TraceServiceTransport + + +class _BaseTraceServiceRestTransport(TraceServiceTransport): + """Base REST backend transport for TraceService. + + 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 = "cloudtrace.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: 'cloudtrace.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("^(?Phttp(?:s)?://)?(?P.*)$", 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 _BaseBatchWriteSpans: + 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": "/v2/{name=projects/*}/traces:batchWrite", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tracing.BatchWriteSpansRequest.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( + _BaseTraceServiceRestTransport._BaseBatchWriteSpans._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSpan: + 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": "/v2/{name=projects/*/traces/*/spans/*}", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = trace.Span.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( + _BaseTraceServiceRestTransport._BaseCreateSpan._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseTraceServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..100510a85055c767645054559a8dfa1a7dbefe73 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/__init__.py @@ -0,0 +1,34 @@ +# -*- 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 .trace import ( + AttributeValue, + Module, + Span, + StackTrace, + TruncatableString, +) +from .tracing import ( + BatchWriteSpansRequest, +) + +__all__ = ( + "AttributeValue", + "Module", + "Span", + "StackTrace", + "TruncatableString", + "BatchWriteSpansRequest", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/trace.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/trace.py new file mode 100644 index 0000000000000000000000000000000000000000..045f28009cdef9c3eadb8332f4d602b712a3c623 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/trace.py @@ -0,0 +1,718 @@ +# -*- 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 + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.devtools.cloudtrace.v2", + manifest={ + "Span", + "AttributeValue", + "StackTrace", + "Module", + "TruncatableString", + }, +) + + +class Span(proto.Message): + r"""A span represents a single operation within a trace. Spans + can be nested to form a trace tree. Often, a trace contains a + root span that describes the end-to-end latency, and one or more + subspans for its sub-operations. + + A trace can also contain multiple root spans, or none at all. + Spans do not need to be contiguous. There might be + gaps or overlaps between spans in a trace. + + Attributes: + name (str): + Required. The resource name of the span in the following + format: + + - ``projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID]`` + + ``[TRACE_ID]`` is a unique identifier for a trace within a + project; it is a 32-character hexadecimal encoding of a + 16-byte array. It should not be zero. + + ``[SPAN_ID]`` is a unique identifier for a span within a + trace; it is a 16-character hexadecimal encoding of an + 8-byte array. It should not be zero. . + span_id (str): + Required. The ``[SPAN_ID]`` portion of the span's resource + name. + parent_span_id (str): + The ``[SPAN_ID]`` of this span's parent span. If this is a + root span, then this field must be empty. + display_name (google.cloud.trace_v2.types.TruncatableString): + Required. A description of the span's + operation (up to 128 bytes). Cloud Trace + displays the description in the Cloud console. + For example, the display name can be a qualified + method name or a file name and a line number + where the operation is called. A best practice + is to use the same display name within an + application and at the same call point. This + makes it easier to correlate spans in different + traces. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The start time of the span. On the + client side, this is the time kept by the local + machine where the span execution starts. On the + server side, this is the time when the server's + application handler starts running. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The end time of the span. On the + client side, this is the time kept by the local + machine where the span execution ends. On the + server side, this is the time when the server + application handler stops running. + attributes (google.cloud.trace_v2.types.Span.Attributes): + A set of attributes on the span. You can have + up to 32 attributes per span. + stack_trace (google.cloud.trace_v2.types.StackTrace): + Stack trace captured at the start of the + span. + time_events (google.cloud.trace_v2.types.Span.TimeEvents): + A set of time events. You can have up to 32 + annotations and 128 message events per span. + links (google.cloud.trace_v2.types.Span.Links): + Links associated with the span. You can have + up to 128 links per Span. + status (google.rpc.status_pb2.Status): + Optional. The final status for this span. + same_process_as_parent_span (google.protobuf.wrappers_pb2.BoolValue): + Optional. Set this parameter to indicate + whether this span is in the same process as its + parent. If you do not set this parameter, Trace + is unable to take advantage of this helpful + information. + child_span_count (google.protobuf.wrappers_pb2.Int32Value): + Optional. The number of child spans that were + generated while this span was active. If set, + allows implementation to detect missing child + spans. + span_kind (google.cloud.trace_v2.types.Span.SpanKind): + Optional. Distinguishes between spans generated in a + particular context. For example, two spans with the same + name may be distinguished using ``CLIENT`` (caller) and + ``SERVER`` (callee) to identify an RPC call. + """ + + class SpanKind(proto.Enum): + r"""Type of span. Can be used to specify additional relationships + between spans in addition to a parent/child relationship. + + Values: + SPAN_KIND_UNSPECIFIED (0): + Unspecified. Do NOT use as default. + Implementations MAY assume SpanKind.INTERNAL to + be default. + INTERNAL (1): + Indicates that the span is used internally. + Default value. + SERVER (2): + Indicates that the span covers server-side + handling of an RPC or other remote network + request. + CLIENT (3): + Indicates that the span covers the + client-side wrapper around an RPC or other + remote request. + PRODUCER (4): + Indicates that the span describes producer + sending a message to a broker. Unlike client and + server, there is no direct critical path latency + relationship between producer and consumer spans + (e.g. publishing a message to a pubsub service). + CONSUMER (5): + Indicates that the span describes consumer + receiving a message from a broker. Unlike client + and server, there is no direct critical path + latency relationship between producer and + consumer spans (e.g. receiving a message from a + pubsub service subscription). + """ + + SPAN_KIND_UNSPECIFIED = 0 + INTERNAL = 1 + SERVER = 2 + CLIENT = 3 + PRODUCER = 4 + CONSUMER = 5 + + class Attributes(proto.Message): + r"""A set of attributes as key-value pairs. + + Attributes: + attribute_map (MutableMapping[str, google.cloud.trace_v2.types.AttributeValue]): + A set of attributes. Each attribute's key can be up to 128 + bytes long. The value can be a string up to 256 bytes, a + signed 64-bit integer, or the boolean values ``true`` or + ``false``. For example: + + :: + + "/instance_id": { "string_value": { "value": "my-instance" } } + "/http/request_bytes": { "int_value": 300 } + "abc.com/myattribute": { "bool_value": false } + dropped_attributes_count (int): + The number of attributes that were discarded. + Attributes can be discarded because their keys + are too long or because there are too many + attributes. If this value is 0 then all + attributes are valid. + """ + + attribute_map: MutableMapping[str, "AttributeValue"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="AttributeValue", + ) + dropped_attributes_count: int = proto.Field( + proto.INT32, + number=2, + ) + + class TimeEvent(proto.Message): + r"""A time-stamped annotation or message event in the Span. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp indicating the time the event + occurred. + annotation (google.cloud.trace_v2.types.Span.TimeEvent.Annotation): + Text annotation with a set of attributes. + + This field is a member of `oneof`_ ``value``. + message_event (google.cloud.trace_v2.types.Span.TimeEvent.MessageEvent): + An event describing a message sent/received + between Spans. + + This field is a member of `oneof`_ ``value``. + """ + + class Annotation(proto.Message): + r"""Text annotation with a set of attributes. + + Attributes: + description (google.cloud.trace_v2.types.TruncatableString): + A user-supplied message describing the event. + The maximum length for the description is 256 + bytes. + attributes (google.cloud.trace_v2.types.Span.Attributes): + A set of attributes on the annotation. You + can have up to 4 attributes per Annotation. + """ + + description: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=1, + message="TruncatableString", + ) + attributes: "Span.Attributes" = proto.Field( + proto.MESSAGE, + number=2, + message="Span.Attributes", + ) + + class MessageEvent(proto.Message): + r"""An event describing a message sent/received between Spans. + + Attributes: + type (google.cloud.trace_v2.types.Span.TimeEvent.MessageEvent.Type): + Type of MessageEvent. Indicates whether the + message was sent or received. + id (int): + An identifier for the MessageEvent's message that can be + used to match ``SENT`` and ``RECEIVED`` MessageEvents. + uncompressed_size_bytes (int): + The number of uncompressed bytes sent or + received. + compressed_size_bytes (int): + The number of compressed bytes sent or + received. If missing, the compressed size is + assumed to be the same size as the uncompressed + size. + """ + + class Type(proto.Enum): + r"""Indicates whether the message was sent or received. + + Values: + TYPE_UNSPECIFIED (0): + Unknown event type. + SENT (1): + Indicates a sent message. + RECEIVED (2): + Indicates a received message. + """ + + TYPE_UNSPECIFIED = 0 + SENT = 1 + RECEIVED = 2 + + type: "Span.TimeEvent.MessageEvent.Type" = proto.Field( + proto.ENUM, + number=1, + enum="Span.TimeEvent.MessageEvent.Type", + ) + id: int = proto.Field( + proto.INT64, + number=2, + ) + uncompressed_size_bytes: int = proto.Field( + proto.INT64, + number=3, + ) + compressed_size_bytes: int = proto.Field( + proto.INT64, + number=4, + ) + + time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + annotation: "Span.TimeEvent.Annotation" = proto.Field( + proto.MESSAGE, + number=2, + oneof="value", + message="Span.TimeEvent.Annotation", + ) + message_event: "Span.TimeEvent.MessageEvent" = proto.Field( + proto.MESSAGE, + number=3, + oneof="value", + message="Span.TimeEvent.MessageEvent", + ) + + class TimeEvents(proto.Message): + r"""A collection of ``TimeEvent``\ s. A ``TimeEvent`` is a time-stamped + annotation on the span, consisting of either user-supplied key:value + pairs, or details of a message sent/received between Spans. + + Attributes: + time_event (MutableSequence[google.cloud.trace_v2.types.Span.TimeEvent]): + A collection of ``TimeEvent``\ s. + dropped_annotations_count (int): + The number of dropped annotations in all the + included time events. If the value is 0, then no + annotations were dropped. + dropped_message_events_count (int): + The number of dropped message events in all + the included time events. If the value is 0, + then no message events were dropped. + """ + + time_event: MutableSequence["Span.TimeEvent"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Span.TimeEvent", + ) + dropped_annotations_count: int = proto.Field( + proto.INT32, + number=2, + ) + dropped_message_events_count: int = proto.Field( + proto.INT32, + number=3, + ) + + class Link(proto.Message): + r"""A pointer from the current span to another span in the same + trace or in a different trace. For example, this can be used in + batching operations, where a single batch handler processes + multiple requests from different traces or when the handler + receives a request from a different project. + + Attributes: + trace_id (str): + The ``[TRACE_ID]`` for a trace within a project. + span_id (str): + The ``[SPAN_ID]`` for a span within a trace. + type (google.cloud.trace_v2.types.Span.Link.Type): + The relationship of the current span relative + to the linked span. + attributes (google.cloud.trace_v2.types.Span.Attributes): + A set of attributes on the link. Up to 32 + attributes can be specified per link. + """ + + class Type(proto.Enum): + r"""The relationship of the current span relative to the linked + span: child, parent, or unspecified. + + Values: + TYPE_UNSPECIFIED (0): + The relationship of the two spans is unknown. + CHILD_LINKED_SPAN (1): + The linked span is a child of the current + span. + PARENT_LINKED_SPAN (2): + The linked span is a parent of the current + span. + """ + + TYPE_UNSPECIFIED = 0 + CHILD_LINKED_SPAN = 1 + PARENT_LINKED_SPAN = 2 + + trace_id: str = proto.Field( + proto.STRING, + number=1, + ) + span_id: str = proto.Field( + proto.STRING, + number=2, + ) + type: "Span.Link.Type" = proto.Field( + proto.ENUM, + number=3, + enum="Span.Link.Type", + ) + attributes: "Span.Attributes" = proto.Field( + proto.MESSAGE, + number=4, + message="Span.Attributes", + ) + + class Links(proto.Message): + r"""A collection of links, which are references from this span to + a span in the same or different trace. + + Attributes: + link (MutableSequence[google.cloud.trace_v2.types.Span.Link]): + A collection of links. + dropped_links_count (int): + The number of dropped links after the maximum + size was enforced. If this value is 0, then no + links were dropped. + """ + + link: MutableSequence["Span.Link"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Span.Link", + ) + dropped_links_count: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + span_id: str = proto.Field( + proto.STRING, + number=2, + ) + parent_span_id: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=4, + message="TruncatableString", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + attributes: Attributes = proto.Field( + proto.MESSAGE, + number=7, + message=Attributes, + ) + stack_trace: "StackTrace" = proto.Field( + proto.MESSAGE, + number=8, + message="StackTrace", + ) + time_events: TimeEvents = proto.Field( + proto.MESSAGE, + number=9, + message=TimeEvents, + ) + links: Links = proto.Field( + proto.MESSAGE, + number=10, + message=Links, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=11, + message=status_pb2.Status, + ) + same_process_as_parent_span: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=12, + message=wrappers_pb2.BoolValue, + ) + child_span_count: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=13, + message=wrappers_pb2.Int32Value, + ) + span_kind: SpanKind = proto.Field( + proto.ENUM, + number=14, + enum=SpanKind, + ) + + +class AttributeValue(proto.Message): + r"""The allowed types for ``[VALUE]`` in a ``[KEY]:[VALUE]`` attribute. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_value (google.cloud.trace_v2.types.TruncatableString): + A string up to 256 bytes long. + + This field is a member of `oneof`_ ``value``. + int_value (int): + A 64-bit signed integer. + + This field is a member of `oneof`_ ``value``. + bool_value (bool): + A Boolean value represented by ``true`` or ``false``. + + This field is a member of `oneof`_ ``value``. + """ + + string_value: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=1, + oneof="value", + message="TruncatableString", + ) + int_value: int = proto.Field( + proto.INT64, + number=2, + oneof="value", + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=3, + oneof="value", + ) + + +class StackTrace(proto.Message): + r"""A call stack appearing in a trace. + + Attributes: + stack_frames (google.cloud.trace_v2.types.StackTrace.StackFrames): + Stack frames in this stack trace. A maximum + of 128 frames are allowed. + stack_trace_hash_id (int): + The hash ID is used to conserve network bandwidth for + duplicate stack traces within a single trace. + + Often multiple spans will have identical stack traces. The + first occurrence of a stack trace should contain both the + ``stackFrame`` content and a value in ``stackTraceHashId``. + + Subsequent spans within the same request can refer to that + stack trace by only setting ``stackTraceHashId``. + """ + + class StackFrame(proto.Message): + r"""Represents a single stack frame in a stack trace. + + Attributes: + function_name (google.cloud.trace_v2.types.TruncatableString): + The fully-qualified name that uniquely + identifies the function or method that is active + in this frame (up to 1024 bytes). + original_function_name (google.cloud.trace_v2.types.TruncatableString): + An un-mangled function name, if ``function_name`` is + mangled. To get information about name mangling, run `this + search `__. + The name can be fully-qualified (up to 1024 bytes). + file_name (google.cloud.trace_v2.types.TruncatableString): + The name of the source file where the + function call appears (up to 256 bytes). + line_number (int): + The line number in ``file_name`` where the function call + appears. + column_number (int): + The column number where the function call + appears, if available. This is important in + JavaScript because of its anonymous functions. + load_module (google.cloud.trace_v2.types.Module): + The binary module from where the code was + loaded. + source_version (google.cloud.trace_v2.types.TruncatableString): + The version of the deployed source code (up + to 128 bytes). + """ + + function_name: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=1, + message="TruncatableString", + ) + original_function_name: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=2, + message="TruncatableString", + ) + file_name: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=3, + message="TruncatableString", + ) + line_number: int = proto.Field( + proto.INT64, + number=4, + ) + column_number: int = proto.Field( + proto.INT64, + number=5, + ) + load_module: "Module" = proto.Field( + proto.MESSAGE, + number=6, + message="Module", + ) + source_version: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=7, + message="TruncatableString", + ) + + class StackFrames(proto.Message): + r"""A collection of stack frames, which can be truncated. + + Attributes: + frame (MutableSequence[google.cloud.trace_v2.types.StackTrace.StackFrame]): + Stack frames in this call stack. + dropped_frames_count (int): + The number of stack frames that were dropped + because there were too many stack frames. + If this value is 0, then no stack frames were + dropped. + """ + + frame: MutableSequence["StackTrace.StackFrame"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="StackTrace.StackFrame", + ) + dropped_frames_count: int = proto.Field( + proto.INT32, + number=2, + ) + + stack_frames: StackFrames = proto.Field( + proto.MESSAGE, + number=1, + message=StackFrames, + ) + stack_trace_hash_id: int = proto.Field( + proto.INT64, + number=2, + ) + + +class Module(proto.Message): + r"""Binary module. + + Attributes: + module (google.cloud.trace_v2.types.TruncatableString): + For example: main binary, kernel modules, and + dynamic libraries such as libc.so, sharedlib.so + (up to 256 bytes). + build_id (google.cloud.trace_v2.types.TruncatableString): + A unique identifier for the module, usually a + hash of its contents (up to 128 bytes). + """ + + module: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=1, + message="TruncatableString", + ) + build_id: "TruncatableString" = proto.Field( + proto.MESSAGE, + number=2, + message="TruncatableString", + ) + + +class TruncatableString(proto.Message): + r"""Represents a string that might be shortened to a specified + length. + + Attributes: + value (str): + The shortened string. For example, if the original string is + 500 bytes long and the limit of the string is 128 bytes, + then ``value`` contains the first 128 bytes of the 500-byte + string. + + Truncation always happens on a UTF8 character boundary. If + there are multi-byte characters in the string, then the + length of the shortened string might be less than the size + limit. + truncated_byte_count (int): + The number of bytes removed from the original + string. If this value is 0, then the string was + not shortened. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + truncated_byte_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/tracing.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..9aeeecf6dba75608fe1db384b435564d0213bbc4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/trace_v2/types/tracing.py @@ -0,0 +1,56 @@ +# -*- 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 + +import proto # type: ignore + +from google.cloud.trace_v2.types import trace + +__protobuf__ = proto.module( + package="google.devtools.cloudtrace.v2", + manifest={ + "BatchWriteSpansRequest", + }, +) + + +class BatchWriteSpansRequest(proto.Message): + r"""The request message for the ``BatchWriteSpans`` method. + + Attributes: + name (str): + Required. The name of the project where the spans belong. + The format is ``projects/[PROJECT_ID]``. + spans (MutableSequence[google.cloud.trace_v2.types.Span]): + Required. A list of new spans. The span names + must not match existing spans, otherwise the + results are undefined. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + spans: MutableSequence[trace.Span] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=trace.Span, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/version.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1cc6e9e1840a05ed497a6753d3883f82f167c8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/cloud/version.py @@ -0,0 +1,15 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "2.5.1" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata.proto new file mode 100644 index 0000000000000000000000000000000000000000..0f2855c15a66716f379115e79c54b2a2a3b88a03 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata.proto @@ -0,0 +1,98 @@ +// Copyright 2020 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.gapic.metadata; + +option csharp_namespace = "Google.Gapic.Metadata"; +option go_package = "google.golang.org/genproto/googleapis/gapic/metadata;metadata"; +option java_multiple_files = true; +option java_outer_classname = "GapicMetadataProto"; +option java_package = "com.google.gapic.metadata"; +option php_namespace = "Google\\Gapic\\Metadata"; +option ruby_package = "Google::Gapic::Metadata"; + +// Metadata about a GAPIC library service for a specific combination of API, +// version, and computer language. +message GapicMetadata { + // Schema version of this proto. Current value: 1.0 + string schema = 1; + + // Any human-readable comments to be included in this file. + string comment = 2; + + // Computer language of this generated language. This must be + // spelled out as it spoken in English, with no capitalization or + // separators (e.g. "csharp", "nodejs"). + string language = 3; + + // The proto package containing the API definition for which this + // GAPIC library was generated. + string proto_package = 4; + + // The language-specific library package for this GAPIC library. + string library_package = 5; + + // A map from each proto-defined service to ServiceForTransports, + // which allows listing information about transport-specific + // implementations of the service. + // + // The key is the name of the service as it appears in the .proto + // file. + map services = 6; + + // A map from a transport name to ServiceAsClient, which allows + // listing information about the client objects that implement the + // parent RPC service for the specified transport. + message ServiceForTransport { + // Map of transport name to ServiceAsClient. The key name is the transport, + // lower-cased with no separators (e.g. "grpc", "rest"). + map clients = 1; + + // The API version for the interface definition found in the + // `google.api.api_version` annotation of this proto-defined service during + // code generation. + // This is the value populated by the client in the API version request + // parameter as per + // [AIP-4236](https://google.aip.dev/client-libraries/4236). + string api_version = 2; + } + + // Information about a specific client implementing a proto-defined service. + message ServiceAsClient { + // The name of the library client formatted as it appears in the source code + string library_client = 1; + + // A mapping from each proto-defined RPC name to the the list of + // methods in library_client that implement it. There can be more + // than one library_client method for each RPC. RPCs with no + // library_client methods need not be included. + // + // The key name is the name of the RPC as defined and formatted in + // the proto file. + map rpcs = 2; + } + + // List of GAPIC client methods implementing the proto-defined RPC + // for the transport and service specified in the containing + // structures. + message MethodList { + // List of methods for a specific proto-service client in the + // GAPIC. These names should be formatted as they appear in the + // source code. + repeated string methods = 1; + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8665a4a4aeefe8706fbb093ff07fa6b8655eb8a8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata_pb2.py @@ -0,0 +1,68 @@ +# -*- 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/gapic/metadata/gapic_metadata.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n*google/gapic/metadata/gapic_metadata.proto\x12\x15google.gapic.metadata"\x85\x06\n\rGapicMetadata\x12\x0e\n\x06schema\x18\x01 \x01(\t\x12\x0f\n\x07\x63omment\x18\x02 \x01(\t\x12\x10\n\x08language\x18\x03 \x01(\t\x12\x15\n\rproto_package\x18\x04 \x01(\t\x12\x17\n\x0flibrary_package\x18\x05 \x01(\t\x12\x44\n\x08services\x18\x06 \x03(\x0b\x32\x32.google.gapic.metadata.GapicMetadata.ServicesEntry\x1ai\n\rServicesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12G\n\x05value\x18\x02 \x01(\x0b\x32\x38.google.gapic.metadata.GapicMetadata.ServiceForTransport:\x02\x38\x01\x1a\xe8\x01\n\x13ServiceForTransport\x12V\n\x07\x63lients\x18\x01 \x03(\x0b\x32\x45.google.gapic.metadata.GapicMetadata.ServiceForTransport.ClientsEntry\x12\x13\n\x0b\x61pi_version\x18\x02 \x01(\t\x1a\x64\n\x0c\x43lientsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x43\n\x05value\x18\x02 \x01(\x0b\x32\x34.google.gapic.metadata.GapicMetadata.ServiceAsClient:\x02\x38\x01\x1a\xd5\x01\n\x0fServiceAsClient\x12\x16\n\x0elibrary_client\x18\x01 \x01(\t\x12L\n\x04rpcs\x18\x02 \x03(\x0b\x32>.google.gapic.metadata.GapicMetadata.ServiceAsClient.RpcsEntry\x1a\\\n\tRpcsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12>\n\x05value\x18\x02 \x01(\x0b\x32/.google.gapic.metadata.GapicMetadata.MethodList:\x02\x38\x01\x1a\x1d\n\nMethodList\x12\x0f\n\x07methods\x18\x01 \x03(\tB\xba\x01\n\x19\x63om.google.gapic.metadataB\x12GapicMetadataProtoP\x01Z=google.golang.org/genproto/googleapis/gapic/metadata;metadata\xaa\x02\x15Google.Gapic.Metadata\xca\x02\x15Google\\Gapic\\Metadata\xea\x02\x17Google::Gapic::Metadatab\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.gapic.metadata.gapic_metadata_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\031com.google.gapic.metadataB\022GapicMetadataProtoP\001Z=google.golang.org/genproto/googleapis/gapic/metadata;metadata\252\002\025Google.Gapic.Metadata\312\002\025Google\\Gapic\\Metadata\352\002\027Google::Gapic::Metadata" + _globals["_GAPICMETADATA_SERVICESENTRY"]._options = None + _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_options = b"8\001" + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._options = None + _globals[ + "_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY" + ]._serialized_options = b"8\001" + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._options = None + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_options = b"8\001" + _globals["_GAPICMETADATA"]._serialized_start = 70 + _globals["_GAPICMETADATA"]._serialized_end = 843 + _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_start = 256 + _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_end = 361 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT"]._serialized_start = 364 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT"]._serialized_end = 596 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._serialized_start = 496 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._serialized_end = 596 + _globals["_GAPICMETADATA_SERVICEASCLIENT"]._serialized_start = 599 + _globals["_GAPICMETADATA_SERVICEASCLIENT"]._serialized_end = 812 + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_start = 720 + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_end = 812 + _globals["_GAPICMETADATA_METHODLIST"]._serialized_start = 814 + _globals["_GAPICMETADATA_METHODLIST"]._serialized_end = 843 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..aed974f2cf54f3983f200587fb336159e810139f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi @@ -0,0 +1,125 @@ +# 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 ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class GapicMetadata(_message.Message): + __slots__ = ( + "schema", + "comment", + "language", + "proto_package", + "library_package", + "services", + ) + + class ServicesEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: GapicMetadata.ServiceForTransport + def __init__( + self, + key: _Optional[str] = ..., + value: _Optional[_Union[GapicMetadata.ServiceForTransport, _Mapping]] = ..., + ) -> None: ... + + class ServiceForTransport(_message.Message): + __slots__ = ("clients", "api_version") + + class ClientsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: GapicMetadata.ServiceAsClient + def __init__( + self, + key: _Optional[str] = ..., + value: _Optional[_Union[GapicMetadata.ServiceAsClient, _Mapping]] = ..., + ) -> None: ... + + CLIENTS_FIELD_NUMBER: _ClassVar[int] + API_VERSION_FIELD_NUMBER: _ClassVar[int] + clients: _containers.MessageMap[str, GapicMetadata.ServiceAsClient] + api_version: str + def __init__( + self, + clients: _Optional[_Mapping[str, GapicMetadata.ServiceAsClient]] = ..., + api_version: _Optional[str] = ..., + ) -> None: ... + + class ServiceAsClient(_message.Message): + __slots__ = ("library_client", "rpcs") + + class RpcsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: GapicMetadata.MethodList + def __init__( + self, + key: _Optional[str] = ..., + value: _Optional[_Union[GapicMetadata.MethodList, _Mapping]] = ..., + ) -> None: ... + + LIBRARY_CLIENT_FIELD_NUMBER: _ClassVar[int] + RPCS_FIELD_NUMBER: _ClassVar[int] + library_client: str + rpcs: _containers.MessageMap[str, GapicMetadata.MethodList] + def __init__( + self, + library_client: _Optional[str] = ..., + rpcs: _Optional[_Mapping[str, GapicMetadata.MethodList]] = ..., + ) -> None: ... + + class MethodList(_message.Message): + __slots__ = ("methods",) + METHODS_FIELD_NUMBER: _ClassVar[int] + methods: _containers.RepeatedScalarFieldContainer[str] + def __init__(self, methods: _Optional[_Iterable[str]] = ...) -> None: ... + + SCHEMA_FIELD_NUMBER: _ClassVar[int] + COMMENT_FIELD_NUMBER: _ClassVar[int] + LANGUAGE_FIELD_NUMBER: _ClassVar[int] + PROTO_PACKAGE_FIELD_NUMBER: _ClassVar[int] + LIBRARY_PACKAGE_FIELD_NUMBER: _ClassVar[int] + SERVICES_FIELD_NUMBER: _ClassVar[int] + schema: str + comment: str + language: str + proto_package: str + library_package: str + services: _containers.MessageMap[str, GapicMetadata.ServiceForTransport] + def __init__( + self, + schema: _Optional[str] = ..., + comment: _Optional[str] = ..., + language: _Optional[str] = ..., + proto_package: _Optional[str] = ..., + library_package: _Optional[str] = ..., + services: _Optional[_Mapping[str, GapicMetadata.ServiceForTransport]] = ..., + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c98f6ef6a945ff9e93a11da32fa35c811176695 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__init__.py @@ -0,0 +1,26 @@ +# 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. +# + +"""Google Gen AI SDK""" + +from . import interactions +from . import types +from . import version +from .client import Client + + +__version__ = version.__version__ + +__all__ = ['Client'] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc0262c3996a93c97372c0651ba5f2b29645264b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_adapters.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_adapters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b45d17e697ece5622e877f5a80c40a66d056eb6a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_adapters.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_api_client.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_api_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75a62af915f0dce398eff1baa17601ebf3a5695e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_api_client.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_api_module.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_api_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67975d97a51b687c2029057e8495f428a0924993 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_api_module.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_base_transformers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_base_transformers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..964d9a7a6194d245ded4c17e2141d498f609b4f3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_base_transformers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_base_url.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_base_url.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0cfaca059f6e41339862a482540dd33b02cf700 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_base_url.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_common.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56030e45f40daecb877238cd42f50622efde2d6c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_common.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_extra_utils.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_extra_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98d3eadab51c027e99b5334823ed49bd646e055a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_extra_utils.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_live_converters.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_live_converters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b4744c5bd350d763400b0802b39ca620a49e057 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_live_converters.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_mcp_utils.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_mcp_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..913ddd312c3d00262c00b9893b30c758b7e8df92 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_mcp_utils.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_operations_converters.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_operations_converters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e266af7e7fe907ef287620aef487e6a76855e59 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_operations_converters.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_replay_api_client.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_replay_api_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ab040d3bdd86123a9da0cba3a190fa48c36a413 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_replay_api_client.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_tokens_converters.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_tokens_converters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e87e8d838c4d12cddddb0361d5ce4cfa47ced480 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_tokens_converters.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_transformers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_transformers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d64e4ebf006afea01f035851b83b1a8a5462fc61 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/_transformers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/batches.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/batches.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77b4dd663e399a3bdb5df14f6f1fa033a9d61e87 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/batches.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/caches.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/caches.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aacfbbe26fb20a6d68bf146baf3d65ed41362a2 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/caches.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/chats.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/chats.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cd77735742692d6852c8bfac5761820b1db8f73 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/chats.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/client.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d02f68fa3c0fadc8fa276bf7a642ec2f053506c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/client.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/documents.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/documents.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c1a67c17c954b0c5525b8078dbe3c71120c8e0b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/documents.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/errors.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b78811b2daf4779c5e1e071a48f5101ce2d99e00 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/errors.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/file_search_stores.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/file_search_stores.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..373e04bb08a69c01c5748ee696563bce15657a4f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/file_search_stores.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/files.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ec0baaceac51c9238e6fcf00c3cce788e311e23 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/files.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/interactions.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/interactions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87da05f585b2786022b5b71674c66a1e7693b95c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/interactions.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/live.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/live.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c691b157b03a02060f0108d38665b86eb988aa1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/live.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/live_music.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/live_music.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..841e3233891e91c1fee0d69f78779c652b00172d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/live_music.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/models.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20b7534243be4cc641ded2d4c7ad18830411ef37 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/models.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b1379756ee6f563b8a833c49f1ce18753db7844daaf14d9b7be50be65869919 +size 271622 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/operations.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/operations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa88483714ba1f2700c033a7cd8f1b5a7bd1a68d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/operations.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/pagers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/pagers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21033eb29ad70f30b03a7bd7a35caec5516f81d4 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/pagers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/tokens.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/tokens.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..205c3f344bd8cc09b60e3ff4e6afafa5649c1b4f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/tokens.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/tunings.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/tunings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9966f563ab33dfbed226bb485162ac336d14795c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/tunings.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/types.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..908c9439ff430b5861043418a5f036c67a1d30f5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/types.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56481841e759efd26fcbdd1d1742fbcaf29af61983ae7d0982284ca76301c2c6 +size 673072 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/version.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..857df3c01fe2ec9240e4b7683d9fefd662cf317c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/version.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_adapters.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..d1dddb2b28c54bc94cb64b40e918b0b479c50306 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_adapters.py @@ -0,0 +1,55 @@ +# 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 typing + +from ._mcp_utils import mcp_to_gemini_tools +from .types import FunctionCall, Tool + +if typing.TYPE_CHECKING: + from mcp import types as mcp_types + from mcp import ClientSession + + +class McpToGenAiToolAdapter: + """Adapter for working with MCP tools in a GenAI client.""" + + def __init__( + self, + session: "mcp.ClientSession", # type: ignore # noqa: F821 + list_tools_result: "mcp_types.ListToolsResult", # type: ignore + ) -> None: + self._mcp_session = session + self._list_tools_result = list_tools_result + + async def call_tool( + self, function_call: FunctionCall + ) -> "mcp_types.CallToolResult": # type: ignore + """Calls a function on the MCP server.""" + name = function_call.name if function_call.name else "" + arguments = dict(function_call.args) if function_call.args else {} + + return typing.cast( + "mcp_types.CallToolResult", + await self._mcp_session.call_tool( + name=name, + arguments=arguments, + ), + ) + + @property + def tools(self) -> list[Tool]: + """Returns a list of Google GenAI tools.""" + return mcp_to_gemini_tools(self._list_tools_result.tools) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_api_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_api_client.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9865cc4fa407cce5867b3327e3048ea0e7cb93 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_api_client.py @@ -0,0 +1,2157 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +"""Base client for calling HTTP APIs sending and receiving JSON. + +The BaseApiClient is intended to be a private module and is subject to change. +""" + +import asyncio +from collections.abc import Generator +import copy +from dataclasses import dataclass +import inspect +import io +import json +import logging +import math +import os +import random +import ssl +import sys +import threading +import time +from typing import Any, AsyncIterator, Iterator, Optional, TYPE_CHECKING, Tuple, Union +from urllib.parse import urlparse +from urllib.parse import urlunparse +import warnings + +import anyio +import certifi +import google.auth +import google.auth.credentials +from google.auth.credentials import Credentials +from google.auth.transport import mtls +from google.auth.transport.requests import AuthorizedSession +import httpx +from pydantic import BaseModel +from pydantic import ValidationError +import requests +from requests.structures import CaseInsensitiveDict +import tenacity + +from . import _common +from . import errors +from . import version +from .types import HttpOptions +from .types import HttpOptionsOrDict +from .types import HttpResponse as SdkHttpResponse +from .types import HttpRetryOptions +from .types import ResourceScope + + +try: + from websockets.asyncio.client import connect as ws_connect +except ModuleNotFoundError: + # This try/except is for TAP, mypy complains about it which is why we have the type: ignore + from websockets.client import connect as ws_connect # type: ignore + + +has_aiohttp = False +try: + import aiohttp + + has_aiohttp = True +except ImportError: + pass + + +if TYPE_CHECKING: + from multidict import CIMultiDictProxy + from google.auth.aio.transport.sessions import AsyncAuthorizedSession + + +logger = logging.getLogger('google_genai._api_client') +CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB chunk size +READ_BUFFER_SIZE = 2**22 +MAX_RETRY_COUNT = 3 +INITIAL_RETRY_DELAY = 1 # second +DELAY_MULTIPLIER = 2 + +_MULTI_REGIONAL_LOCATIONS = {'us', 'eu'} + + +class EphemeralTokenAPIKeyError(ValueError): + """Error raised when the API key is invalid.""" + + +# This method checks for the API key in the environment variables. Google API +# key is precedenced over Gemini API key. +def get_env_api_key() -> Optional[str]: + """Gets the API key from environment variables, prioritizing GOOGLE_API_KEY. + + Returns: + The API key string if found, otherwise None. Empty string is considered + invalid. + """ + env_google_api_key = os.environ.get('GOOGLE_API_KEY', None) + env_gemini_api_key = os.environ.get('GEMINI_API_KEY', None) + if env_google_api_key and env_gemini_api_key: + logger.warning( + 'Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.' + ) + + return env_google_api_key or env_gemini_api_key or None + + +def append_library_version_headers(headers: dict[str, str]) -> None: + """Appends the telemetry header to the headers dict.""" + library_label = f'google-genai-sdk/{version.__version__}' + language_label = 'gl-python/' + sys.version.split()[0] + version_header_value = f'{library_label} {language_label}' + if ( + 'user-agent' in headers + and version_header_value not in headers['user-agent'] + ): + headers['user-agent'] = f'{version_header_value} ' + headers['user-agent'] + elif 'user-agent' not in headers: + headers['user-agent'] = version_header_value + if ( + 'x-goog-api-client' in headers + and version_header_value not in headers['x-goog-api-client'] + ): + headers['x-goog-api-client'] = ( + f'{version_header_value} ' + headers['x-goog-api-client'] + ) + elif 'x-goog-api-client' not in headers: + headers['x-goog-api-client'] = version_header_value + + +def patch_http_options( + options: HttpOptions, patch_options: HttpOptions +) -> HttpOptions: + copy_option = options.model_copy() + + options_headers = copy_option.headers or {} + patch_options_headers = patch_options.headers or {} + copy_option.headers = { + **options_headers, + **patch_options_headers, + } + + http_options_keys = HttpOptions.model_fields.keys() + + for key in http_options_keys: + if key == 'headers': + continue + patch_value = getattr(patch_options, key, None) + if patch_value is not None: + setattr(copy_option, key, patch_value) + else: + setattr(copy_option, key, getattr(options, key)) + + if copy_option.headers is not None: + append_library_version_headers(copy_option.headers) + return copy_option + + +def populate_server_timeout_header( + headers: dict[str, str], timeout_in_seconds: Optional[Union[float, int]] +) -> None: + """Populates the server timeout header in the headers dict.""" + if timeout_in_seconds and 'X-Server-Timeout' not in headers: + headers['X-Server-Timeout'] = str(math.ceil(timeout_in_seconds)) + + +def join_url_path(base_url: str, path: str) -> str: + parsed_base = urlparse(base_url) + base_path = ( + parsed_base.path[:-1] + if parsed_base.path.endswith('/') + else parsed_base.path + ) + path = path[1:] if path.startswith('/') else path + return urlunparse(parsed_base._replace(path=base_path + '/' + path)) + + +def load_auth(*, project: Union[str, None]) -> Tuple[Credentials, str]: + """Loads google auth credentials and project id.""" + credentials, loaded_project_id = google.auth.default( # type: ignore[no-untyped-call] + scopes=['https://www.googleapis.com/auth/cloud-platform'], + ) + + if not project: + project = loaded_project_id + + if not project: + raise ValueError( + 'Could not resolve project using application default credentials.' + ) + + return credentials, project + + +def refresh_auth(credentials: Credentials) -> Credentials: + from google.auth.transport.requests import Request + credentials.refresh(Request()) # type: ignore[no-untyped-call] + return credentials + + +def get_timeout_in_seconds( + timeout: Optional[Union[float, int]], +) -> Optional[float]: + """Converts the timeout to seconds.""" + if timeout: + # HttpOptions.timeout is in milliseconds. But httpx.Client.request() + # expects seconds. + timeout_in_seconds = timeout / 1000.0 + else: + timeout_in_seconds = None + return timeout_in_seconds + + +@dataclass +class HttpRequest: + headers: dict[str, str] + url: str + method: str + data: Union[dict[str, object], bytes] + timeout: Optional[float] = None + + +class HttpResponse: + + def __init__( + self, + headers: Union[ + dict[str, str], + httpx.Headers, + 'CIMultiDictProxy[str]', + CaseInsensitiveDict, + ], + response_stream: Union[Any, str] = None, + byte_stream: Union[Any, bytes] = None, + ): + if isinstance(headers, dict): + self.headers = headers + elif isinstance(headers, httpx.Headers): + self.headers = { + key: ', '.join(headers.get_list(key)) for key in headers.keys() + } + elif isinstance(headers, CaseInsensitiveDict): + self.headers = {key: value for key, value in headers.items()} + elif type(headers).__name__ == 'CIMultiDictProxy': + self.headers = { + key: ', '.join(headers.getall(key)) for key in headers.keys() + } + + self.status_code: int = 200 + self.response_stream = response_stream + self.byte_stream = byte_stream + + # Async iterator for async streaming. + def __aiter__(self) -> 'HttpResponse': + self.segment_iterator = self.async_segments() + return self + + async def __anext__(self) -> Any: + try: + return await self.segment_iterator.__anext__() + except StopIteration: + raise StopAsyncIteration + + @property + def json(self) -> Any: + # Handle case where response_stream is not a list (e.g., aiohttp.ClientResponse) + # This can happen when the API returns an error and the response object + # is passed directly instead of being wrapped in a list. + # See: https://github.com/googleapis/python-genai/issues/1897 + if not isinstance(self.response_stream, list): + return None + if not self.response_stream or not self.response_stream[0]: # Empty response + return '' + return self._load_json_from_response(self.response_stream[0]) + + def segments(self) -> Generator[Any, None, None]: + if isinstance(self.response_stream, list): + # list of objects retrieved from replay or from non-streaming API. + for chunk in self.response_stream: + yield self._load_json_from_response(chunk) if chunk else {} + elif self.response_stream is None: + yield from [] + else: + # Iterator of objects retrieved from the API. + for chunk in self._iter_response_stream(): + yield self._load_json_from_response(chunk) + + async def async_segments(self) -> AsyncIterator[Any]: + if isinstance(self.response_stream, list): + # list of objects retrieved from replay or from non-streaming API. + for chunk in self.response_stream: + yield self._load_json_from_response(chunk) if chunk else {} + elif self.response_stream is None: + async for c in []: # type: ignore[attr-defined] + yield c + else: + # Iterator of objects retrieved from the API. + async for chunk in self._aiter_response_stream(): + yield self._load_json_from_response(chunk) + + def byte_segments(self) -> Generator[Union[bytes, Any], None, None]: + if isinstance(self.byte_stream, list): + # list of objects retrieved from replay or from non-streaming API. + yield from self.byte_stream + elif self.byte_stream is None: + yield from [] + else: + raise ValueError( + 'Byte segments are not supported for streaming responses.' + ) + + def _copy_to_dict(self, response_payload: dict[str, object]) -> None: + # Cannot pickle 'generator' object. + delattr(self, 'segment_iterator') + for attribute in dir(self): + response_payload[attribute] = copy.deepcopy(getattr(self, attribute)) + + def _iter_response_stream(self) -> Iterator[str]: + """Iterates over chunks retrieved from the API.""" + if not ( + isinstance(self.response_stream, httpx.Response) + or isinstance(self.response_stream, requests.Response) + ): + raise TypeError( + 'Expected self.response_stream to be an httpx.Response object, ' + f'but got {type(self.response_stream).__name__}.' + ) + + chunk = '' + balance = 0 + if isinstance(self.response_stream, httpx.Response): + response_stream = self.response_stream.iter_lines() + else: + response_stream = self.response_stream.iter_lines(decode_unicode=True) + for line in response_stream: + if not line: + continue + + # In streaming mode, the response of JSON is prefixed with "data: " which + # we must strip before parsing. + if line.startswith('data: '): + yield line[len('data: '):] + continue + + # When API returns an error message, it comes line by line. So we buffer + # the lines until a complete JSON string is read. A complete JSON string + # is found when the balance is 0. + for c in line: + if c == '{': + balance += 1 + elif c == '}': + balance -= 1 + + chunk += line + if balance == 0: + yield chunk + chunk = '' + + # If there is any remaining chunk, yield it. + if chunk: + yield chunk + + async def _aiter_response_stream(self) -> AsyncIterator[str]: + """Asynchronously iterates over chunks retrieved from the API.""" + is_valid_response = isinstance(self.response_stream, httpx.Response) or ( + has_aiohttp and isinstance(self.response_stream, aiohttp.ClientResponse) + ) + if not is_valid_response: + raise TypeError( + 'Expected self.response_stream to be an httpx.Response or' + ' aiohttp.ClientResponse object, but got' + f' {type(self.response_stream).__name__}.' + ) + + chunk = '' + balance = 0 + # httpx.Response has a dedicated async line iterator. + if isinstance(self.response_stream, httpx.Response): + try: + async for line in self.response_stream.aiter_lines(): + if not line: + continue + # In streaming mode, the response of JSON is prefixed with "data: " + # which we must strip before parsing. + if line.startswith('data: '): + yield line[len('data: '):] + continue + + # When API returns an error message, it comes line by line. So we buffer + # the lines until a complete JSON string is read. A complete JSON string + # is found when the balance is 0. + for c in line: + if c == '{': + balance += 1 + elif c == '}': + balance -= 1 + + chunk += line + if balance == 0: + yield chunk + chunk = '' + # If there is any remaining chunk, yield it. + if chunk: + yield chunk + finally: + # Close the response and release the connection. + await self.response_stream.aclose() + + # aiohttp.ClientResponse uses a content stream that we read line by line. + elif has_aiohttp and isinstance( + self.response_stream, aiohttp.ClientResponse + ): + try: + while True: + # Read a line from the stream. This returns bytes. + line_bytes = await self.response_stream.content.readline() + if not line_bytes: + break + # Decode the bytes and remove trailing whitespace and newlines. + line = line_bytes.decode('utf-8').rstrip() + if not line: + continue + + # In streaming mode, the response of JSON is prefixed with "data: " + # which we must strip before parsing. + if line.startswith('data: '): + yield line[len('data: '):] + continue + + # When API returns an error message, it comes line by line. So we + # buffer the lines until a complete JSON string is read. A complete + # JSON strings found when the balance is 0. + for c in line: + if c == '{': + balance += 1 + elif c == '}': + balance -= 1 + + chunk += line + if balance == 0: + yield chunk + chunk = '' + # If there is any remaining chunk, yield it. + if chunk: + yield chunk + finally: + # Release the connection back to the pool for potential reuse. + self.response_stream.release() + + @classmethod + def _load_json_from_response(cls, response: Any) -> Any: + """Loads JSON from the response, or raises an error if the parsing fails.""" + try: + return json.loads(response) + except json.JSONDecodeError as e: + raise errors.UnknownApiResponseError( + f'Failed to parse response as JSON. Raw response: {response}' + ) from e + + +# Default retry options. +# The config is based on https://cloud.google.com/storage/docs/retry-strategy. +# By default, the client will retry 4 times with approximately 1.0, 2.0, 4.0, +# 8.0 seconds between each attempt. +_RETRY_ATTEMPTS = 5 # including the initial call. +_RETRY_INITIAL_DELAY = 1.0 # seconds +_RETRY_MAX_DELAY = 60.0 # seconds +_RETRY_EXP_BASE = 2 +_RETRY_JITTER = 1 +_RETRY_HTTP_STATUS_CODES = ( + 408, # Request timeout. + 429, # Too many requests. + 500, # Internal server error. + 502, # Bad gateway. + 503, # Service unavailable. + 504, # Gateway timeout +) + + +def retry_args(options: Optional[HttpRetryOptions]) -> _common.StringDict: + """Returns the retry args for the given http retry options. + + Args: + options: The http retry options to use for the retry configuration. If None, + the 'never retry' stop strategy will be used. + + Returns: + The arguments passed to the tenacity.(Async)Retrying constructor. + """ + if options is None: + return {'stop': tenacity.stop_after_attempt(1), 'reraise': True} + if options.attempts == 0: + options.attempts = 1 + stop = tenacity.stop_after_attempt(options.attempts or _RETRY_ATTEMPTS) + retriable_codes = options.http_status_codes or _RETRY_HTTP_STATUS_CODES + retry = tenacity.retry_if_exception( + lambda e: isinstance(e, errors.APIError) and e.code in retriable_codes, + ) + wait = tenacity.wait_exponential_jitter( + initial=options.initial_delay or _RETRY_INITIAL_DELAY, + max=options.max_delay or _RETRY_MAX_DELAY, + exp_base=options.exp_base or _RETRY_EXP_BASE, + jitter=options.jitter or _RETRY_JITTER, + ) + return { + 'stop': stop, + 'retry': retry, + 'reraise': True, + 'wait': wait, + 'before_sleep': tenacity.before_sleep_log(logger, logging.INFO), + } + + +class SyncHttpxClient(httpx.Client): + """Sync httpx client.""" + + def __init__(self, **kwargs: Any) -> None: + """Initializes the httpx client.""" + kwargs.setdefault('follow_redirects', True) + super().__init__(**kwargs) + + def __del__(self) -> None: + """Closes the httpx client.""" + try: + if self.is_closed: + return + except Exception: + pass + try: + self.close() + except Exception: + pass + + +class AsyncHttpxClient(httpx.AsyncClient): + """Async httpx client.""" + + def __init__(self, **kwargs: Any) -> None: + """Initializes the httpx client.""" + kwargs.setdefault('follow_redirects', True) + super().__init__(**kwargs) + + def __del__(self) -> None: + try: + if self.is_closed: + return + except Exception: + pass + try: + asyncio.get_running_loop().create_task(self.aclose()) + except Exception: + pass + + +class BaseApiClient: + """Client for calling HTTP APIs sending and receiving JSON.""" + + def __init__( + self, + vertexai: Optional[bool] = None, + api_key: Optional[str] = None, + credentials: Optional[google.auth.credentials.Credentials] = None, + project: Optional[str] = None, + location: Optional[str] = None, + http_options: Optional[HttpOptionsOrDict] = None, + ): + self.vertexai = vertexai + self.custom_base_url = None + if self.vertexai is None: + if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI', '0').lower() in [ + 'true', + '1', + ]: + self.vertexai = True + + # Validate explicitly set initializer values. + if (project or location) and api_key: + # API cannot consume both project/location and api_key. + raise ValueError( + 'Project/location and API key are mutually exclusive in the client' + ' initializer.' + ) + elif credentials and api_key: + # API cannot consume both credentials and api_key. + raise ValueError( + 'Credentials and API key are mutually exclusive in the client' + ' initializer.' + ) + + # Validate http_options if it is provided. + validated_http_options = HttpOptions() + if isinstance(http_options, dict): + try: + validated_http_options = HttpOptions.model_validate(http_options) + except ValidationError as e: + raise ValueError('Invalid http_options') from e + elif http_options and _common.is_duck_type_of(http_options, HttpOptions): + validated_http_options = http_options + + if ( + validated_http_options.base_url_resource_scope + and not validated_http_options.base_url + ): + # base_url_resource_scope is only valid when base_url is set. + raise ValueError( + 'base_url must be set when base_url_resource_scope is set.' + ) + + # Retrieve implicitly set values from the environment. + env_project = os.environ.get('GOOGLE_CLOUD_PROJECT', None) + env_location = os.environ.get('GOOGLE_CLOUD_LOCATION', None) + env_api_key = get_env_api_key() + self.project = project or env_project + self.location = location or env_location + self.api_key = api_key or env_api_key + + self._credentials = credentials + self._http_options = HttpOptions() + # Initialize the lock. This lock will be used to protect access to the + # credentials. This is crucial for thread safety when multiple coroutines + # might be accessing the credentials at the same time. + self._sync_auth_lock = threading.Lock() + self._async_auth_lock: Optional[asyncio.Lock] = None + self._async_auth_lock_creation_lock: Optional[asyncio.Lock] = None + + # Handle when to use Vertex AI in express mode (api key). + # Explicit initializer arguments are already validated above. + if self.vertexai: + if credentials and env_api_key: + # Explicit credentials take precedence over implicit api_key. + logger.info( + 'The user provided Google Cloud credentials will take precedence' + + ' over the API key from the environment variable.' + ) + self.api_key = None + elif (env_location or env_project) and api_key: + # Explicit api_key takes precedence over implicit project/location. + logger.info( + 'The user provided Vertex AI API key will take precedence over the' + + ' project/location from the environment variables.' + ) + self.project = None + self.location = None + elif (project or location) and env_api_key: + # Explicit project/location takes precedence over implicit api_key. + logger.info( + 'The user provided project/location will take precedence over the' + + ' Vertex AI API key from the environment variable.' + ) + self.api_key = None + elif (env_location or env_project) and env_api_key: + # Implicit project/location takes precedence over implicit api_key. + logger.info( + 'The project/location from the environment variables will take' + + ' precedence over the API key from the environment variables.' + ) + self.api_key = None + + self.custom_base_url = ( + validated_http_options.base_url + if validated_http_options.base_url + else None + ) + + if ( + not self.location + and not self.api_key + ): + if not self.custom_base_url: + self.location = 'global' + elif self.custom_base_url.endswith('.googleapis.com'): + self.location = 'global' + + # Skip fetching project from ADC if base url is provided in http options. + if ( + not self.project + and not self.api_key + and not self.custom_base_url + ): + credentials, self.project = load_auth(project=None) + if not self._credentials: + self._credentials = credentials + + has_sufficient_auth = (self.project and self.location) or self.api_key + + if not has_sufficient_auth and not self.custom_base_url: + # Skip sufficient auth check if base url is provided in http options. + raise ValueError( + 'Project or API key must be set when using the Vertex AI API.' + ) + if ( + self.api_key or self.location == 'global' + ) and not self.custom_base_url: + self._http_options.base_url = f'https://aiplatform.googleapis.com/' + elif ( + self.location in _MULTI_REGIONAL_LOCATIONS + and not self.custom_base_url + ): + self._http_options.base_url = ( + f'https://aiplatform.{self.location}.rep.googleapis.com/' + ) + elif ( + self.custom_base_url + and not self.custom_base_url.endswith('.googleapis.com') + ) and not ((project and location) or api_key): + # Avoid setting default base url and api version if base_url provided. + # API gateway proxy can use the auth in custom headers, not url. + # Enable custom url if auth is not sufficient. + self._http_options.base_url = self.custom_base_url + # Clear project and location if base_url is provided. + self.project = None + self.location = None + else: + self._http_options.base_url = ( + f'https://{self.location}-aiplatform.googleapis.com/' + ) + self._http_options.api_version = 'v1beta1' + else: # Implicit initialization or missing arguments. + if not self.api_key: + raise ValueError( + 'No API key was provided. Please pass a valid API key. Learn how to' + ' create an API key at' + ' https://ai.google.dev/gemini-api/docs/api-key.' + ) + self._http_options.base_url = 'https://generativelanguage.googleapis.com/' + self._http_options.api_version = 'v1beta' + # Default options for both clients. + self._http_options.headers = {'Content-Type': 'application/json'} + if self.api_key: + self.api_key = self.api_key.strip() + if self._http_options.headers is not None: + self._http_options.headers['x-goog-api-key'] = self.api_key + # Update the http options with the user provided http options. + if http_options: + self._http_options = patch_http_options( + self._http_options, validated_http_options + ) + else: + if self._http_options.headers is not None: + append_library_version_headers(self._http_options.headers) + + client_args, async_client_args = self._ensure_httpx_ssl_ctx( + self._http_options + ) + self._async_httpx_client_args = async_client_args + self._authorized_session: Optional[AuthorizedSession] = None + + if self._use_google_auth_sync(): + self._httpx_client = None + elif self._http_options.httpx_client: + self._httpx_client = self._http_options.httpx_client + else: + self._httpx_client = SyncHttpxClient(**client_args) + + if self._use_google_auth_async(): + self._async_httpx_client = None + elif self._http_options.httpx_async_client: + self._async_httpx_client = self._http_options.httpx_async_client + else: + self._async_httpx_client = AsyncHttpxClient(**async_client_args) + + if self._http_options.httpx_async_client: + self._async_httpx_client = self._http_options.httpx_async_client + else: + self._async_httpx_client = AsyncHttpxClient(**async_client_args) + + # Initialize the aiohttp client session. + self._aiohttp_session: Optional[Union['aiohttp.ClientSession', 'AsyncAuthorizedSession']] = None + if self._use_aiohttp(): + try: + import aiohttp # pylint: disable=g-import-not-at-top + + if self._http_options.aiohttp_client: + self._aiohttp_session = self._http_options.aiohttp_client + # Do it once at the genai.Client level. Share among all requests. + self._async_client_session_request_args = ( + self._ensure_aiohttp_ssl_ctx(self._http_options) + ) + if self._use_google_auth_async(): + self._async_client_session_request_args['ssl'] = True # type: ignore[no-untyped-call] + self._async_client_session_request_args['max_allowed_time'] = float( + 'inf' + ) if self._http_options.timeout is None else float( + self._http_options.timeout + ) + self._async_client_session_request_args['total_attempts'] = 1 + except ImportError: + pass + + retry_kwargs = retry_args(self._http_options.retry_options) + self._websocket_ssl_ctx = self._ensure_websocket_ssl_ctx(self._http_options) + self._retry = tenacity.Retrying(**retry_kwargs) + self._async_retry = tenacity.AsyncRetrying(**retry_kwargs) + + def _use_google_auth_sync(self) -> bool: + if not hasattr(mtls, 'should_use_client_cert'): + return False + return bool( + self.vertexai + and mtls.should_use_client_cert() # type: ignore[no-untyped-call] + and mtls.has_default_client_cert_source() # type: ignore[no-untyped-call] + and not ( + self._http_options.httpx_client or self._http_options.client_args + ) + ) + + def _use_google_auth_async(self) -> bool: + try: + from google.auth.aio.credentials import StaticCredentials + from google.auth.aio.transport.sessions import AsyncAuthorizedSession + except ImportError: + return False + return bool( + has_aiohttp + and self.vertexai + and mtls.should_use_client_cert() # type: ignore[no-untyped-call] + and mtls.has_default_client_cert_source() # type: ignore[no-untyped-call] + and not self._http_options.httpx_async_client + ) + + async def _get_aiohttp_session( + self, + ) -> Union['aiohttp.ClientSession', 'AsyncAuthorizedSession']: + """Returns the aiohttp client session.""" + + if self._aiohttp_session is None and self._use_google_auth_async(): + try: + from google.auth.aio.credentials import StaticCredentials + from google.auth.aio.transport.sessions import AsyncAuthorizedSession + + async_creds = StaticCredentials(token=self._access_token()) # type: ignore[no-untyped-call] + self._aiohttp_session = AsyncAuthorizedSession(async_creds) # type: ignore[no-untyped-call,assignment] + return self._aiohttp_session # type: ignore[return-value] + except ImportError: + pass + + if not self._use_google_auth_async() and ( + self._aiohttp_session is None + or self._aiohttp_session.closed # type: ignore[union-attr] + or self._aiohttp_session._loop.is_closed() # type: ignore[union-attr] + ): # pylint: disable=protected-access + # Initialize the aiohttp client session if it's not set up or closed. + class AiohttpClientSession(aiohttp.ClientSession): # type: ignore[misc] + + def __del__(self, _warnings: Any = warnings) -> None: + if not self.closed: + context = { + 'client_session': self, + 'message': 'Unclosed client session', + } + if self._source_traceback is not None: + context['source_traceback'] = self._source_traceback + # Remove this self._loop.call_exception_handler(context) + + class AiohttpTCPConnector(aiohttp.TCPConnector): # type: ignore[misc] + + def __del__(self, _warnings: Any = warnings) -> None: + if self._closed: + return + if not self._conns: + return + conns = [repr(c) for c in self._conns.values()] + # After v3.13.2, it may change to self._close_immediately() + self._close() + context = { + 'connector': self, + 'connections': conns, + 'message': 'Unclosed connector', + } + if self._source_traceback is not None: + context['source_traceback'] = self._source_traceback + # Remove this self._loop.call_exception_handler(context) + self._aiohttp_session = AiohttpClientSession( + connector=AiohttpTCPConnector(limit=0), + trust_env=True, + read_bufsize=READ_BUFFER_SIZE, + ) + + return self._aiohttp_session # type: ignore[return-value] + + @staticmethod + def _ensure_httpx_ssl_ctx( + options: HttpOptions, + ) -> Tuple[_common.StringDict, _common.StringDict]: + """Ensures the SSL context is present in the HTTPX client args. + + Creates a default SSL context if one is not provided. + + Args: + options: The http options to check for SSL context. + + Returns: + A tuple of sync/async httpx client args. + """ + + verify = 'verify' + args = options.client_args + async_args = options.async_client_args + ctx = ( + args.get(verify) + if args + else None or async_args.get(verify) + if async_args + else None + ) + + if not ctx: + # Initialize the SSL context for the httpx client. + # Unlike requests, the httpx package does not automatically pull in the + # environment variables SSL_CERT_FILE or SSL_CERT_DIR. They need to be + # enabled explicitly. + ctx = ssl.create_default_context( + cafile=os.environ.get('SSL_CERT_FILE', certifi.where()), + capath=os.environ.get('SSL_CERT_DIR'), + ) + + def _maybe_set( + args: Optional[_common.StringDict], + ctx: ssl.SSLContext, + ) -> _common.StringDict: + """Sets the SSL context in the client args if not set. + + Does not override the SSL context if it is already set. + + Args: + args: The client args to to check for SSL context. + ctx: The SSL context to set. + + Returns: + The client args with the SSL context included. + """ + if not args or not args.get(verify): + args = (args or {}).copy() + args[verify] = ctx + # Drop the args that isn't used by the httpx client. + copied_args = args.copy() + for key in copied_args.copy(): + if key not in inspect.signature(httpx.Client.__init__).parameters: + del copied_args[key] + return copied_args + + return ( + _maybe_set(args, ctx), + _maybe_set(async_args, ctx), + ) + + @staticmethod + def _ensure_aiohttp_ssl_ctx(options: HttpOptions) -> _common.StringDict: + """Ensures the SSL context is present in the async client args. + + Creates a default SSL context if one is not provided. + + Args: + options: The http options to check for SSL context. + + Returns: + An async aiohttp ClientSession._request args. + """ + verify = 'ssl' # keep it consistent with aiohttp. + async_args = options.async_client_args + ctx = async_args.get(verify) if async_args else None + + if not ctx: + ctx = ssl.create_default_context( + cafile=os.environ.get('SSL_CERT_FILE', certifi.where()), + capath=os.environ.get('SSL_CERT_DIR'), + ) + + def _maybe_set( + args: Optional[_common.StringDict], + ctx: ssl.SSLContext, + ) -> _common.StringDict: + """Sets the SSL context in the client args if not set. + + Does not override the SSL context if it is already set. + + Args: + args: The client args to to check for SSL context. + ctx: The SSL context to set. + + Returns: + The client args with the SSL context included. + """ + if not args or not args.get(verify): + args = (args or {}).copy() + args[verify] = ctx + # Drop the args that isn't in the aiohttp RequestOptions. + copied_args = args.copy() + for key in copied_args.copy(): + if ( + key + not in inspect.signature(aiohttp.ClientSession._request).parameters + ): + del copied_args[key] + return copied_args + + return _maybe_set(async_args, ctx) + + @staticmethod + def _ensure_websocket_ssl_ctx(options: HttpOptions) -> _common.StringDict: + """Ensures the SSL context is present in the async client args. + + Creates a default SSL context if one is not provided. + + Args: + options: The http options to check for SSL context. + + Returns: + An async aiohttp ClientSession._request args. + """ + + verify = 'ssl' # keep it consistent with httpx. + async_args = options.async_client_args + ctx = async_args.get(verify) if async_args else None + + if not ctx: + # Initialize the SSL context for the httpx client. + # Unlike requests, the aiohttp package does not automatically pull in the + # environment variables SSL_CERT_FILE or SSL_CERT_DIR. They need to be + # enabled explicitly. Instead of 'verify' at client level in httpx, + # aiohttp uses 'ssl' at request level. + ctx = ssl.create_default_context( + cafile=os.environ.get('SSL_CERT_FILE', certifi.where()), + capath=os.environ.get('SSL_CERT_DIR'), + ) + + def _maybe_set( + args: Optional[_common.StringDict], + ctx: ssl.SSLContext, + ) -> _common.StringDict: + """Sets the SSL context in the client args if not set. + + Does not override the SSL context if it is already set. + + Args: + args: The client args to to check for SSL context. + ctx: The SSL context to set. + + Returns: + The client args with the SSL context included. + """ + if not args or not args.get(verify): + args = (args or {}).copy() + args[verify] = ctx + # Drop the args that isn't in the aiohttp RequestOptions. + copied_args = args.copy() + for key in copied_args.copy(): + if key not in inspect.signature(ws_connect).parameters and key != 'ssl': + del copied_args[key] + return copied_args + + return _maybe_set(async_args, ctx) + + def _use_aiohttp(self) -> bool: + # If the instantiator has passed a custom transport, they want httpx not + # aiohttp. + return ( + has_aiohttp + and (self._http_options.async_client_args or {}).get('transport') + is None + and (self._http_options.httpx_async_client is None) + ) + + def _websocket_base_url(self) -> str: + has_sufficient_auth = (self.project and self.location) or self.api_key + if self.custom_base_url and not has_sufficient_auth: + # API gateway proxy can use the auth in custom headers, not url. + # Enable custom url if auth is not sufficient. + return self.custom_base_url + url_parts = urlparse(self._http_options.base_url) + return url_parts._replace(scheme='wss').geturl() # type: ignore[arg-type, return-value] + + def _access_token(self) -> str: + """Retrieves the access token for the credentials.""" + with self._sync_auth_lock: + if not self._credentials: + self._credentials, project = load_auth(project=self.project) + if not self.project: + self.project = project + + if self._credentials: + return get_token_from_credentials(self, self._credentials) # type: ignore[no-any-return] + else: + raise RuntimeError('Could not resolve API token from the environment') + + async def _get_async_auth_lock(self) -> asyncio.Lock: + """Lazily initializes and returns an asyncio.Lock for async authentication. + + This method ensures that a single `asyncio.Lock` instance is created and + shared among all asynchronous operations that require authentication, + preventing race conditions when accessing or refreshing credentials. + + The lock is created on the first call to this method. An internal async lock + is used to protect the creation of the main authentication lock to ensure + it's a singleton within the client instance. + + Returns: + The asyncio.Lock instance for asynchronous authentication operations. + """ + if self._async_auth_lock is None: + # Create async creation lock if needed + if self._async_auth_lock_creation_lock is None: + self._async_auth_lock_creation_lock = asyncio.Lock() + + async with self._async_auth_lock_creation_lock: + if self._async_auth_lock is None: + self._async_auth_lock = asyncio.Lock() + + return self._async_auth_lock + + async def _async_access_token(self) -> Union[str, Any]: + """Retrieves the access token for the credentials asynchronously.""" + if not self._credentials: + async_auth_lock = await self._get_async_auth_lock() + async with async_auth_lock: + # This ensures that only one coroutine can execute the auth logic at a + # time for thread safety. + if not self._credentials: + # Double check that the credentials are not set before loading them. + self._credentials, project = await asyncio.to_thread( + load_auth, project=self.project + ) + if not self.project: + self.project = project + + if self._credentials: + return await async_get_token_from_credentials( + self, + self._credentials + ) # type: ignore[no-any-return] + else: + raise RuntimeError('Could not resolve API token from the environment') + + def _build_request( + self, + http_method: str, + path: str, + request_dict: dict[str, object], + http_options: Optional[HttpOptionsOrDict] = None, + ) -> HttpRequest: + # Remove all special dict keys such as _url and _query. + keys_to_delete = [key for key in request_dict.keys() if key.startswith('_')] + for key in keys_to_delete: + del request_dict[key] + # patch the http options with the user provided settings. + if http_options: + if isinstance(http_options, HttpOptions): + patched_http_options = patch_http_options( + self._http_options, + http_options, + ) + else: + patched_http_options = patch_http_options( + self._http_options, HttpOptions.model_validate(http_options) + ) + else: + patched_http_options = self._http_options + # Skip adding project and locations when getting Vertex AI base models. + query_vertex_base_models = False + if ( + self.vertexai + and http_method == 'get' + and path.startswith('publishers/google/models') + ): + query_vertex_base_models = True + if ( + self.vertexai + and not path.startswith('projects/') + and not query_vertex_base_models + and (self.project or self.location) + and not ( + self.custom_base_url + and patched_http_options.base_url_resource_scope + == ResourceScope.COLLECTION + ) + ): + path = f'projects/{self.project}/locations/{self.location}/' + path + + if patched_http_options.api_version is None: + versioned_path = f'/{path}' + else: + versioned_path = f'{patched_http_options.api_version}/{path}' + + if ( + patched_http_options.base_url is None + or not patched_http_options.base_url + ): + raise ValueError('Base URL must be set.') + else: + base_url = patched_http_options.base_url + + if ( + hasattr(patched_http_options, 'extra_body') + and patched_http_options.extra_body + ): + _common.recursive_dict_update( + request_dict, patched_http_options.extra_body + ) + url = base_url + if ( + not self.custom_base_url + or (self.project and self.location) + or self.api_key + ): + if ( + patched_http_options.base_url_resource_scope + == ResourceScope.COLLECTION + ): + url = join_url_path(base_url, path) + else: + url = join_url_path( + base_url, + versioned_path, + ) + elif( + self.custom_base_url + and patched_http_options.base_url_resource_scope == ResourceScope.COLLECTION + ): + url = join_url_path(base_url, path) + + if self.api_key and self.api_key.startswith('auth_tokens/'): + raise EphemeralTokenAPIKeyError( + 'Ephemeral tokens can only be used with the live API.' + ) + + timeout_in_seconds = get_timeout_in_seconds(patched_http_options.timeout) + + if patched_http_options.headers is None: + raise ValueError('Request headers must be set.') + populate_server_timeout_header( + patched_http_options.headers, timeout_in_seconds + ) + return HttpRequest( + method=http_method, + url=url, + headers=patched_http_options.headers, + data=request_dict, + timeout=timeout_in_seconds, + ) + + def _request_once( + self, + http_request: HttpRequest, + stream: bool = False, + ) -> HttpResponse: + data: Optional[Union[str, bytes]] = None + # If using proj/location, fetch ADC + if self.vertexai and (self.project or self.location): + http_request.headers['Authorization'] = f'Bearer {self._access_token()}' + if self._credentials and self._credentials.quota_project_id: + http_request.headers['x-goog-user-project'] = ( + self._credentials.quota_project_id + ) + data = json.dumps(http_request.data) if http_request.data else None + else: + if http_request.data: + if not isinstance(http_request.data, bytes): + data = json.dumps(http_request.data) if http_request.data else None + else: + data = http_request.data + + if self._use_google_auth_sync(): + url = str(http_request.url) + if self._authorized_session is None: + self._authorized_session = AuthorizedSession( # type: ignore[no-untyped-call] + self._credentials, + max_refresh_attempts=1, + ) + client_cert_source = mtls.default_client_cert_source() # type: ignore[no-untyped-call] + self._authorized_session.configure_mtls_channel( + client_cert_source + ) # type: ignore[no-untyped-call] + if self._authorized_session._is_mtls and 'googleapis.com' in url: + if 'sandbox' in url: + url = url.replace( + 'sandbox.googleapis.com', 'mtls.sandbox.googleapis.com' + ) + else: + url = url.replace('googleapis.com', 'mtls.googleapis.com') + response = self._authorized_session.request( # type: ignore[no-untyped-call] + method=http_request.method.upper(), + url=url, + data=data, + headers=http_request.headers, + timeout=http_request.timeout, + stream=stream, + ) + else: + httpx_request = self._httpx_client.build_request( # type: ignore[union-attr] + method=http_request.method, + url=http_request.url, + content=data, + headers=http_request.headers, + timeout=http_request.timeout, + ) + response = self._httpx_client.send(httpx_request, stream=stream) # type: ignore[union-attr] + errors.APIError.raise_for_response(response) + return HttpResponse( + response.headers, response if stream else [response.text] + ) + + def _request( + self, + http_request: HttpRequest, + http_options: Optional[HttpOptionsOrDict] = None, + stream: bool = False, + ) -> HttpResponse: + if http_options: + parameter_model = ( + HttpOptions(**http_options) + if isinstance(http_options, dict) + else http_options + ) + # Support per request retry options. + if parameter_model.retry_options: + retry_kwargs = retry_args(parameter_model.retry_options) + retry = tenacity.Retrying(**retry_kwargs) + return retry(self._request_once, http_request, stream) # type: ignore[no-any-return] + + return self._retry(self._request_once, http_request, stream) # type: ignore[no-any-return] + + async def _async_request_once( + self, http_request: HttpRequest, stream: bool = False + ) -> HttpResponse: + data: Optional[bytes] = None + + # If using proj/location, fetch ADC + if self.vertexai and (self.project or self.location): + http_request.headers['Authorization'] = ( + f'Bearer {await self._async_access_token()}' + ) + if self._credentials and self._credentials.quota_project_id: + http_request.headers['x-goog-user-project'] = ( + self._credentials.quota_project_id + ) + if http_request.data: + if not isinstance(http_request.data, bytes): + data = json.dumps(http_request.data).encode('utf-8') + else: + data = http_request.data + + if stream: + if self._use_aiohttp(): + self._aiohttp_session = await self._get_aiohttp_session() # type: ignore[assignment] + url = http_request.url + if self._use_google_auth_async(): + client_cert_source = mtls.default_client_cert_source() # type: ignore[no-untyped-call] + await self._aiohttp_session.configure_mtls_channel( # type: ignore[union-attr] + client_cert_source + ) + if self._aiohttp_session._is_mtls and 'googleapis.com' in url: # type: ignore[union-attr] + if 'sandbox' in url: + url = url.replace( + 'sandbox.googleapis.com', 'mtls.sandbox.googleapis.com' + ) + else: + url = url.replace('googleapis.com', 'mtls.googleapis.com') + try: + response = await self._aiohttp_session.request( # type: ignore[union-attr] + method=http_request.method, + url=url, + headers=http_request.headers, + data=data, + timeout=aiohttp.ClientTimeout(total=http_request.timeout), + **self._async_client_session_request_args, + ) + except ( + aiohttp.ClientConnectorError, + aiohttp.ClientConnectorDNSError, + aiohttp.ClientOSError, + aiohttp.ServerDisconnectedError, + ) as e: + await asyncio.sleep(1 + random.randint(0, 9)) + logger.info('Retrying due to aiohttp error: %s' % e) + # Retrieve the SSL context from the session. + self._async_client_session_request_args = ( + self._ensure_aiohttp_ssl_ctx(self._http_options) + ) + # Instantiate a new session with the updated SSL context. + self._aiohttp_session = await self._get_aiohttp_session() # type: ignore[assignment] + response = await self._aiohttp_session.request( # type: ignore[union-attr] + method=http_request.method, + url=url, + headers=http_request.headers, + data=data, + timeout=aiohttp.ClientTimeout(total=http_request.timeout), + **self._async_client_session_request_args, + ) + + await errors.APIError.raise_for_async_response(response) + if hasattr(response, '_response'): + # Extract the underlying aiohttp.ClientResponse from the + # AsyncAuthorizedSession Response. + response = response._response + return HttpResponse(response.headers, response) + else: + # aiohttp is not available. Fall back to httpx. + httpx_request = self._async_httpx_client.build_request( # type: ignore[union-attr] + method=http_request.method, + url=http_request.url, + content=data, + headers=http_request.headers, + timeout=http_request.timeout, + ) + client_response = await self._async_httpx_client.send( # type: ignore[union-attr] + httpx_request, + stream=stream, + ) + await errors.APIError.raise_for_async_response(client_response) + return HttpResponse(client_response.headers, client_response) + else: + if self._use_aiohttp(): + self._aiohttp_session = await self._get_aiohttp_session() # type: ignore[assignment] + url = http_request.url + if self._use_google_auth_async(): + client_cert_source = mtls.default_client_cert_source() # type: ignore[no-untyped-call] + await self._aiohttp_session.configure_mtls_channel( # type: ignore[union-attr] + client_cert_source + ) + if self._aiohttp_session._is_mtls and 'googleapis.com' in url: # type: ignore[union-attr] + if 'sandbox' in url: + url = url.replace( + 'sandbox.googleapis.com', 'mtls.sandbox.googleapis.com' + ) + else: + url = url.replace('googleapis.com', 'mtls.googleapis.com') + try: + response = await self._aiohttp_session.request( # type: ignore[union-attr] + method=http_request.method, + url=url, + headers=http_request.headers, + data=data, + timeout=aiohttp.ClientTimeout(total=http_request.timeout), + **self._async_client_session_request_args, + ) + await errors.APIError.raise_for_async_response(response) + unwrapped_response: Any = response + if hasattr(unwrapped_response, '_response'): + unwrapped_response = unwrapped_response._response + + return HttpResponse( + unwrapped_response.headers, [await unwrapped_response.text()] + ) + except ( + aiohttp.ClientConnectorError, + aiohttp.ClientConnectorDNSError, + aiohttp.ClientOSError, + aiohttp.ServerDisconnectedError, + ) as e: + await asyncio.sleep(1 + random.randint(0, 9)) + logger.info('Retrying due to aiohttp error: %s' % e) + # Retrieve the SSL context from the session. + self._async_client_session_request_args = ( + self._ensure_aiohttp_ssl_ctx(self._http_options) + ) + # Instantiate a new session with the updated SSL context. + self._aiohttp_session = await self._get_aiohttp_session() # type: ignore[assignment] + response = await self._aiohttp_session.request( # type: ignore[union-attr] + method=http_request.method, + url=url, + headers=http_request.headers, + data=data, + timeout=aiohttp.ClientTimeout(total=http_request.timeout), + **self._async_client_session_request_args, + ) + await errors.APIError.raise_for_async_response(response) + unwrapped_retry_response: Any = response + if hasattr(unwrapped_retry_response, '_response'): + unwrapped_retry_response = unwrapped_retry_response._response + + return HttpResponse( + unwrapped_retry_response.headers, + [await unwrapped_retry_response.text()], + ) + else: + # aiohttp is not available. Fall back to httpx. + client_response = await self._async_httpx_client.request( # type: ignore[union-attr] + method=http_request.method, + url=http_request.url, + headers=http_request.headers, + content=data, + timeout=http_request.timeout, + ) + await errors.APIError.raise_for_async_response(client_response) + return HttpResponse(client_response.headers, [client_response.text]) + + async def _async_request( + self, + http_request: HttpRequest, + http_options: Optional[HttpOptionsOrDict] = None, + stream: bool = False, + ) -> HttpResponse: + if http_options: + parameter_model = ( + HttpOptions(**http_options) + if isinstance(http_options, dict) + else http_options + ) + # Support per request retry options. + if parameter_model.retry_options: + retry_kwargs = retry_args(parameter_model.retry_options) + retry = tenacity.AsyncRetrying(**retry_kwargs) + return await retry(self._async_request_once, http_request, stream) # type: ignore[no-any-return] + return await self._async_retry( # type: ignore[no-any-return] + self._async_request_once, http_request, stream + ) + + def get_read_only_http_options(self) -> _common.StringDict: + if isinstance(self._http_options, BaseModel): + copied = self._http_options.model_dump() + else: + copied = self._http_options + return copied + + def request( + self, + http_method: str, + path: str, + request_dict: dict[str, object], + http_options: Optional[HttpOptionsOrDict] = None, + ) -> SdkHttpResponse: + http_request = self._build_request( + http_method, path, request_dict, http_options + ) + response = self._request(http_request, http_options, stream=False) + response_body = ( + response.response_stream[0] if response.response_stream else '' + ) + return SdkHttpResponse(headers=response.headers, body=response_body) + + def request_streamed( + self, + http_method: str, + path: str, + request_dict: dict[str, object], + http_options: Optional[HttpOptionsOrDict] = None, + ) -> Generator[SdkHttpResponse, None, None]: + http_request = self._build_request( + http_method, path, request_dict, http_options + ) + + session_response = self._request(http_request, http_options, stream=True) + for chunk in session_response.segments(): + chunk_dump = json.dumps(chunk) + try: + if chunk_dump.startswith('{"error":'): + chunk_json = json.loads(chunk_dump) + errors.APIError.raise_error( + chunk_json.get('error', {}).get('code'), + chunk_json, + session_response, + ) + except json.decoder.JSONDecodeError: + logger.debug( + 'Failed to decode chunk that contains an error: %s' % chunk_dump + ) + pass + yield SdkHttpResponse(headers=session_response.headers, body=chunk_dump) + + async def async_request( + self, + http_method: str, + path: str, + request_dict: dict[str, object], + http_options: Optional[HttpOptionsOrDict] = None, + ) -> SdkHttpResponse: + http_request = self._build_request( + http_method, path, request_dict, http_options + ) + + result = await self._async_request( + http_request=http_request, http_options=http_options, stream=False + ) + response_body = result.response_stream[0] if result.response_stream else '' + return SdkHttpResponse(headers=result.headers, body=response_body) + + async def async_request_streamed( + self, + http_method: str, + path: str, + request_dict: dict[str, object], + http_options: Optional[HttpOptionsOrDict] = None, + ) -> Any: + http_request = self._build_request( + http_method, path, request_dict, http_options + ) + + response = await self._async_request( + http_request=http_request, http_options=http_options, stream=True + ) + + async def async_generator(): # type: ignore[no-untyped-def] + async for chunk in response: + chunk_dump = json.dumps(chunk) + try: + if chunk_dump.startswith('{"error":'): + chunk_json = json.loads(chunk_dump) + await errors.APIError.raise_error_async( + chunk_json.get('error', {}).get('code'), + chunk_json, + response, + ) + except json.decoder.JSONDecodeError: + logger.debug( + 'Failed to decode chunk that contains an error: %s' % chunk_dump + ) + pass + yield SdkHttpResponse(headers=response.headers, body=chunk_dump) + + return async_generator() # type: ignore[no-untyped-call] + + def upload_file( + self, + file_path: Union[str, io.IOBase], + upload_url: str, + upload_size: int, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> HttpResponse: + """Transfers a file to the given URL. + + Args: + file_path: The full path to the file or a file like object inherited from + io.BytesIO. If the local file path is not found, an error will be + raised. + upload_url: The URL to upload the file to. + upload_size: The size of file content to be uploaded, this will have to + match the size requested in the resumable upload request. + http_options: The http options to use for the request. + + returns: + The HttpResponse object from the finalize request. + """ + if isinstance(file_path, io.IOBase): + return self._upload_fd( + file_path, upload_url, upload_size, http_options=http_options + ) + else: + with open(file_path, 'rb') as file: + return self._upload_fd( + file, upload_url, upload_size, http_options=http_options + ) + + def _upload_fd( + self, + file: io.IOBase, + upload_url: str, + upload_size: int, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> HttpResponse: + """Transfers a file to the given URL. + + Args: + file: A file like object inherited from io.BytesIO. + upload_url: The URL to upload the file to. + upload_size: The size of file content to be uploaded, this will have to + match the size requested in the resumable upload request. + http_options: The http options to use for the request. + + returns: + The HttpResponse object from the finalize request. + """ + offset = 0 + http_options = http_options if http_options else self._http_options + base_url = ( + http_options.get('base_url') + if isinstance(http_options, dict) + else getattr(http_options, 'base_url', None) + ) + if base_url: + parsed_base = urlparse(base_url) + parsed_upload = urlparse(upload_url) + upload_url = urlunparse( + parsed_upload._replace( + scheme=parsed_base.scheme, netloc=parsed_base.netloc + ) + ) + + # Upload the file in chunks + while True: + file_chunk = file.read(CHUNK_SIZE) + chunk_size = 0 + if file_chunk: + chunk_size = len(file_chunk) + upload_command = 'upload' + # If last chunk, finalize the upload. + if chunk_size + offset >= upload_size: + upload_command += ', finalize' + timeout = ( + http_options.get('timeout') + if isinstance(http_options, dict) + else http_options.timeout + ) + if timeout is None: + # Per request timeout is not configured. Check the global timeout. + timeout = ( + self._http_options.timeout + if isinstance(self._http_options, dict) + else self._http_options.timeout + ) + timeout_in_seconds = get_timeout_in_seconds(timeout) + user_headers = ( + http_options.get('headers', {}) + if isinstance(http_options, dict) + else (getattr(http_options, 'headers', {}) or {}) + ) + upload_headers = dict(user_headers) if user_headers else {} + upload_headers.update({ + 'X-Goog-Upload-Command': upload_command, + 'X-Goog-Upload-Offset': str(offset), + 'Content-Length': str(chunk_size), + }) + populate_server_timeout_header(upload_headers, timeout_in_seconds) + retry_count = 0 + while retry_count < MAX_RETRY_COUNT: + response = self._httpx_client.request( # type: ignore[union-attr] + method='POST', + url=upload_url, + headers=upload_headers, + content=file_chunk, + timeout=timeout_in_seconds, + ) + if response.headers.get('x-goog-upload-status'): + break + delay_seconds = INITIAL_RETRY_DELAY * (DELAY_MULTIPLIER**retry_count) + retry_count += 1 + time.sleep(delay_seconds) + + offset += chunk_size + if response.headers.get('x-goog-upload-status') != 'active': + break # upload is complete or it has been interrupted. + if upload_size <= offset: # Status is not finalized. + raise ValueError( + f'All content has been uploaded, but the upload status is not' + f' finalized.' + ) + errors.APIError.raise_for_response(response) + if response.headers.get('x-goog-upload-status') != 'final': + raise ValueError('Failed to upload file: Upload status is not finalized.') + return HttpResponse(response.headers, response_stream=[response.text]) + + def download_file( + self, + path: str, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> Union[Any, bytes]: + """Downloads the file data. + + Args: + path: The request path with query params. + http_options: The http options to use for the request. + + returns: + The file bytes + """ + http_request = self._build_request( + 'get', path=path, request_dict={}, http_options=http_options + ) + + data: Optional[Union[str, bytes]] = None + if http_request.data: + if not isinstance(http_request.data, bytes): + data = json.dumps(http_request.data) + else: + data = http_request.data + + response = self._httpx_client.request( # type: ignore[union-attr] + method=http_request.method, + url=http_request.url, + headers=http_request.headers, + content=data, + timeout=http_request.timeout, + ) + + errors.APIError.raise_for_response(response) + return HttpResponse( + response.headers, byte_stream=[response.read()] + ).byte_stream[0] + + async def async_upload_file( + self, + file_path: Union[str, io.IOBase], + upload_url: str, + upload_size: int, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> HttpResponse: + """Transfers a file asynchronously to the given URL. + + Args: + file_path: The full path to the file. If the local file path is not found, + an error will be raised. + upload_url: The URL to upload the file to. + upload_size: The size of file content to be uploaded, this will have to + match the size requested in the resumable upload request. + http_options: The http options to use for the request. + + returns: + The HttpResponse object from the finalize request. + """ + if isinstance(file_path, io.IOBase): + return await self._async_upload_fd( + file_path, upload_url, upload_size, http_options=http_options + ) + else: + file = anyio.Path(file_path) + fd = await file.open('rb') + async with fd: + return await self._async_upload_fd( + fd, upload_url, upload_size, http_options=http_options + ) + + async def _async_upload_fd( + self, + file: Union[io.IOBase, anyio.AsyncFile[Any]], + upload_url: str, + upload_size: int, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> HttpResponse: + """Transfers a file asynchronously to the given URL. + + Args: + file: A file like object inherited from io.BytesIO. + upload_url: The URL to upload the file to. + upload_size: The size of file content to be uploaded, this will have to + match the size requested in the resumable upload request. + http_options: The http options to use for the request. + + returns: + The HttpResponse object from the finalized request. + """ + offset = 0 + http_options = http_options if http_options else self._http_options + base_url = ( + http_options.get('base_url') + if isinstance(http_options, dict) + else getattr(http_options, 'base_url', None) + ) + if base_url: + parsed_base = urlparse(base_url) + parsed_upload = urlparse(upload_url) + upload_url = urlunparse( + parsed_upload._replace( + scheme=parsed_base.scheme, netloc=parsed_base.netloc + ) + ) + + # Upload the file in chunks + if self._use_aiohttp(): # pylint: disable=g-import-not-at-top + self._aiohttp_session = await self._get_aiohttp_session() # type: ignore[assignment] + while True: + if isinstance(file, io.IOBase): + file_chunk = file.read(CHUNK_SIZE) + else: + file_chunk = await file.read(CHUNK_SIZE) + chunk_size = 0 + if file_chunk: + chunk_size = len(file_chunk) + upload_command = 'upload' + # If last chunk, finalize the upload. + if chunk_size + offset >= upload_size: + upload_command += ', finalize' + timeout = ( + http_options.get('timeout') + if isinstance(http_options, dict) + else http_options.timeout + ) + if timeout is None: + # Per request timeout is not configured. Check the global timeout. + timeout = ( + self._http_options.timeout + if isinstance(self._http_options, dict) + else self._http_options.timeout + ) + timeout_in_seconds = get_timeout_in_seconds(timeout) + user_headers = ( + http_options.get('headers', {}) + if isinstance(http_options, dict) + else (getattr(http_options, 'headers', {}) or {}) + ) + upload_headers = dict(user_headers) if user_headers else {} + upload_headers.update({ + 'X-Goog-Upload-Command': upload_command, + 'X-Goog-Upload-Offset': str(offset), + 'Content-Length': str(chunk_size), + }) + populate_server_timeout_header(upload_headers, timeout_in_seconds) + + retry_count = 0 + response = None + while retry_count < MAX_RETRY_COUNT: + response = await self._aiohttp_session.request( # type: ignore[union-attr] + method='POST', + url=upload_url, + data=file_chunk, + headers=upload_headers, + timeout=aiohttp.ClientTimeout(total=timeout_in_seconds), + ) + + if response.headers.get('X-Goog-Upload-Status'): + break + delay_seconds = INITIAL_RETRY_DELAY * (DELAY_MULTIPLIER**retry_count) + retry_count += 1 + await asyncio.sleep(delay_seconds) + + offset += chunk_size + if ( + response is not None + and response.headers.get('X-Goog-Upload-Status') != 'active' + ): + break # upload is complete or it has been interrupted. + + if upload_size <= offset: # Status is not finalized. + raise ValueError( + f'All content has been uploaded, but the upload status is not' + f' finalized.' + ) + + await errors.APIError.raise_for_async_response(response) + if ( + response is not None + and response.headers.get('X-Goog-Upload-Status') != 'final' + ): + raise ValueError( + 'Failed to upload file: Upload status is not finalized.' + ) + return HttpResponse( + response.headers, response_stream=[await response.text()] # type: ignore[union-attr] + ) + else: + # aiohttp is not available. Fall back to httpx. + while True: + if isinstance(file, io.IOBase): + file_chunk = file.read(CHUNK_SIZE) + else: + file_chunk = await file.read(CHUNK_SIZE) + chunk_size = 0 + if file_chunk: + chunk_size = len(file_chunk) + upload_command = 'upload' + # If last chunk, finalize the upload. + if chunk_size + offset >= upload_size: + upload_command += ', finalize' + timeout = ( + http_options.get('timeout') + if isinstance(http_options, dict) + else http_options.timeout + ) + if timeout is None: + # Per request timeout is not configured. Check the global timeout. + timeout = ( + self._http_options.timeout + if isinstance(self._http_options, dict) + else self._http_options.timeout + ) + timeout_in_seconds = get_timeout_in_seconds(timeout) + user_headers = ( + http_options.get('headers', {}) + if isinstance(http_options, dict) + else (getattr(http_options, 'headers', {}) or {}) + ) + upload_headers = dict(user_headers) if user_headers else {} + upload_headers.update({ + 'X-Goog-Upload-Command': upload_command, + 'X-Goog-Upload-Offset': str(offset), + 'Content-Length': str(chunk_size), + }) + populate_server_timeout_header(upload_headers, timeout_in_seconds) + + retry_count = 0 + client_response = None + while retry_count < MAX_RETRY_COUNT: + client_response = await self._async_httpx_client.request( # type: ignore[union-attr] + method='POST', + url=upload_url, + content=file_chunk, + headers=upload_headers, + timeout=timeout_in_seconds, + ) + if ( + client_response is not None + and client_response.headers + and client_response.headers.get('x-goog-upload-status') + ): + break + delay_seconds = INITIAL_RETRY_DELAY * (DELAY_MULTIPLIER**retry_count) + retry_count += 1 + time.sleep(delay_seconds) + + offset += chunk_size + if ( + client_response is not None + and client_response.headers.get('x-goog-upload-status') != 'active' + ): + break # upload is complete or it has been interrupted. + + if upload_size <= offset: # Status is not finalized. + raise ValueError( + 'All content has been uploaded, but the upload status is not' + ' finalized.' + ) + + await errors.APIError.raise_for_async_response(client_response) + if ( + client_response is not None + and client_response.headers.get('x-goog-upload-status') != 'final' + ): + raise ValueError( + 'Failed to upload file: Upload status is not finalized.' + ) + return HttpResponse( + client_response.headers, response_stream=[client_response.text] + ) + + async def async_download_file( + self, + path: str, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> Union[Any, bytes]: + """Downloads the file data. + + Args: + path: The request path with query params. + http_options: The http options to use for the request. + + returns: + The file bytes + """ + http_request = self._build_request( + 'get', path=path, request_dict={}, http_options=http_options + ) + + data: Optional[bytes] = None + if http_request.data: + if not isinstance(http_request.data, bytes): + data = json.dumps(http_request.data).encode('utf-8') + else: + data = http_request.data + + if self._use_aiohttp(): + self._aiohttp_session = await self._get_aiohttp_session() # type: ignore[assignment] + response = await self._aiohttp_session.request( # type: ignore[union-attr] + method=http_request.method, + url=http_request.url, + headers=http_request.headers, + data=data, + timeout=aiohttp.ClientTimeout(total=http_request.timeout), + ) + await errors.APIError.raise_for_async_response(response) + + return HttpResponse( + response.headers, byte_stream=[await response.read()] + ).byte_stream[0] + else: + # aiohttp is not available. Fall back to httpx. + client_response = await self._async_httpx_client.request( # type: ignore[union-attr] + method=http_request.method, + url=http_request.url, + headers=http_request.headers, + content=data, + timeout=http_request.timeout, + ) + await errors.APIError.raise_for_async_response(client_response) + + return HttpResponse( + client_response.headers, byte_stream=[client_response.read()] + ).byte_stream[0] + + # This method does nothing in the real api client. It is used in the + # replay_api_client to verify the response from the SDK method matches the + # recorded response. + def _verify_response(self, response_model: _common.BaseModel) -> None: + pass + + def close(self) -> None: + """Closes the API client.""" + # Let users close the custom client explicitly by themselves. Otherwise, + # close the client when the object is garbage collected. + if not self._http_options.httpx_client and self._httpx_client: + self._httpx_client.close() + if self._authorized_session: + self._authorized_session.close() # type: ignore[no-untyped-call] + + async def aclose(self) -> None: + """Closes the API async client.""" + # Let users close the custom client explicitly by themselves. Otherwise, + # close the client when the object is garbage collected. + if not self._http_options.httpx_async_client: + await self._async_httpx_client.aclose() # type: ignore[union-attr] + if self._aiohttp_session and not self._http_options.aiohttp_client: + await self._aiohttp_session.close() + + def __del__(self) -> None: + """Closes the API client when the object is garbage collected. + + ADK uses this client so cannot rely on the genai.[Async]Client.__del__ + for cleanup. + """ + + try: + if not self._http_options.httpx_client: + self.close() + except Exception: # pylint: disable=broad-except + pass + + try: + asyncio.get_running_loop().create_task(self.aclose()) + except Exception: # pylint: disable=broad-except + pass + + +def get_token_from_credentials( + client: 'BaseApiClient', + credentials: google.auth.credentials.Credentials +) -> str: + """Refreshes the authentication token for the given credentials.""" + if credentials.expired or not credentials.token: + # Only refresh when it needs to. Default expiration is 3600 seconds. + refresh_auth(credentials) + if not credentials.token: + raise RuntimeError('Could not resolve API token from the environment') + return credentials.token # type: ignore[no-any-return] + + +async def async_get_token_from_credentials( + client: 'BaseApiClient', + credentials: google.auth.credentials.Credentials +) -> str: + """Refreshes the authentication token for the given credentials.""" + if credentials.expired or not credentials.token: + # Only refresh when it needs to. Default expiration is 3600 seconds. + async_auth_lock = await client._get_async_auth_lock() + async with async_auth_lock: + if credentials.expired or not credentials.token: + # Double check that the credentials expired before refreshing. + await asyncio.to_thread(refresh_auth, credentials) + + if not credentials.token: + raise RuntimeError('Could not resolve API token from the environment') + + return credentials.token # type: ignore[no-any-return] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_api_module.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_api_module.py new file mode 100644 index 0000000000000000000000000000000000000000..bd5abd4d72b2cdaa187ede5882b9112d12ca2faf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_api_module.py @@ -0,0 +1,29 @@ +# 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. +# + +"""Utilities for the API Modules of the Google Gen AI SDK.""" + +from typing import Optional +from . import _api_client + + +class BaseModule: + + def __init__(self, api_client_: _api_client.BaseApiClient): + self._api_client = api_client_ + + @property + def vertexai(self) -> Optional[bool]: + return self._api_client.vertexai diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_automatic_function_calling_util.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_automatic_function_calling_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7f9a7028c8554c11b3531273682efb9dd3c890 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_automatic_function_calling_util.py @@ -0,0 +1,325 @@ +# 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 sys +import types as builtin_types +import typing +from typing import _GenericAlias, Any, Callable, get_args, get_origin, Literal, Optional, Union # type: ignore[attr-defined] + +import pydantic + +from . import _extra_utils +from . import types + + +if sys.version_info >= (3, 10): + VersionedUnionType = builtin_types.UnionType +else: + VersionedUnionType = typing._UnionGenericAlias # type: ignore[attr-defined] + + +__all__ = [ + '_py_builtin_type_to_schema_type', + '_raise_for_unsupported_param', + '_handle_params_as_deferred_annotations', + '_add_unevaluated_items_to_fixed_len_tuple_schema', + '_is_builtin_primitive_or_compound', + '_is_default_value_compatible', + '_parse_schema_from_parameter', + '_get_required_fields', +] + +_py_builtin_type_to_schema_type = { + str: types.Type.STRING, + int: types.Type.INTEGER, + float: types.Type.NUMBER, + bool: types.Type.BOOLEAN, + list: types.Type.ARRAY, + dict: types.Type.OBJECT, + None: types.Type.NULL, +} + + +def _raise_for_unsupported_param( + param: inspect.Parameter, func_name: str, exception: Union[Exception, type[Exception]] +) -> None: + raise ValueError( + f'Failed to parse the parameter {param} of function {func_name} for' + ' automatic function calling.Automatic function calling works best with' + ' simpler function signature schema, consider manually parsing your' + f' function declaration for function {func_name}.' + ) from exception + + +def _handle_params_as_deferred_annotations(param: inspect.Parameter, annotation_under_future: dict[str, Any], name: str) -> inspect.Parameter: + """Catches the case when type hints are stored as strings.""" + if isinstance(param.annotation, str): + param = param.replace(annotation=annotation_under_future[name]) + return param + + +def _add_unevaluated_items_to_fixed_len_tuple_schema( + json_schema: dict[str, Any] +) -> dict[str, Any]: + if ( + json_schema.get('maxItems') + and ( + json_schema.get('prefixItems') + and len(json_schema['prefixItems']) == json_schema['maxItems'] + ) + and json_schema.get('type') == 'array' + ): + json_schema['unevaluatedItems'] = False + return json_schema + + +def _is_builtin_primitive_or_compound( + annotation: inspect.Parameter.annotation, # type: ignore[valid-type] +) -> bool: + return annotation in _py_builtin_type_to_schema_type.keys() + + +def _is_default_value_compatible( + default_value: Any, annotation: inspect.Parameter.annotation # type: ignore[valid-type] +) -> bool: + # None type is expected to be handled external to this function + if _is_builtin_primitive_or_compound(annotation): + return isinstance(default_value, annotation) + + if ( + isinstance(annotation, _GenericAlias) + or isinstance(annotation, builtin_types.GenericAlias) + or isinstance(annotation, VersionedUnionType) + ): + origin = get_origin(annotation) + if origin in (Union, VersionedUnionType): # type: ignore[comparison-overlap] + return any( + _is_default_value_compatible(default_value, arg) + for arg in get_args(annotation) + ) + + if origin is dict: # type: ignore[comparison-overlap] + return isinstance(default_value, dict) + + if origin is list: # type: ignore[comparison-overlap] + if not isinstance(default_value, list): + return False + # most tricky case, element in list is union type + # need to apply any logic within all + # see test case test_generic_alias_complex_array_with_default_value + # a: typing.List[int | str | float | bool] + # default_value: [1, 'a', 1.1, True] + return all( + any( + _is_default_value_compatible(item, arg) + for arg in get_args(annotation) + ) + for item in default_value + ) + + if origin is Literal: # type: ignore[comparison-overlap] + return default_value in get_args(annotation) + + # return False for any other unrecognized annotation + return False + + +def _parse_schema_from_parameter( # type: ignore[return] + api_option: Literal['VERTEX_AI', 'GEMINI_API'], + param: inspect.Parameter, + func_name: str, +) -> types.Schema: + """parse schema from parameter. + + from the simplest case to the most complex case. + """ + schema = types.Schema() + default_value_error_msg = ( + f'Default value {param.default} of parameter {param} of function' + f' {func_name} is not compatible with the parameter annotation' + f' {param.annotation}.' + ) + if _is_builtin_primitive_or_compound(param.annotation): + if param.default is not inspect.Parameter.empty: + if not _is_default_value_compatible(param.default, param.annotation): + raise ValueError(default_value_error_msg) + schema.default = param.default + schema.type = _py_builtin_type_to_schema_type[param.annotation] + return schema + if ( + isinstance(param.annotation, VersionedUnionType) + # only parse simple UnionType, example int | str | float | bool + # complex UnionType will be invoked in raise branch + and all( + (_is_builtin_primitive_or_compound(arg) or arg is type(None)) + for arg in get_args(param.annotation) + ) + ): + schema.type = _py_builtin_type_to_schema_type[dict] + schema.any_of = [] + unique_types = set() + for arg in get_args(param.annotation): + if arg.__name__ == 'NoneType': # Optional type + schema.nullable = True + continue + schema_in_any_of = _parse_schema_from_parameter( + api_option, + inspect.Parameter( + 'item', inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=arg + ), + func_name, + ) + if ( + schema_in_any_of.model_dump_json(exclude_none=True) + not in unique_types + ): + schema.any_of.append(schema_in_any_of) + unique_types.add(schema_in_any_of.model_dump_json(exclude_none=True)) + if len(schema.any_of) == 1: # param: list | None -> Array + schema.type = schema.any_of[0].type + schema.any_of = None + if ( + param.default is not inspect.Parameter.empty + and param.default is not None + ): + if not _is_default_value_compatible(param.default, param.annotation): + raise ValueError(default_value_error_msg) + schema.default = param.default + return schema + if isinstance(param.annotation, _GenericAlias) or isinstance( + param.annotation, builtin_types.GenericAlias + ): + origin = get_origin(param.annotation) + args = get_args(param.annotation) + if origin is dict: + schema.type = _py_builtin_type_to_schema_type[dict] + if param.default is not inspect.Parameter.empty: + if not _is_default_value_compatible(param.default, param.annotation): + raise ValueError(default_value_error_msg) + schema.default = param.default + return schema + if origin is Literal: + if not all(isinstance(arg, str) for arg in args): + raise ValueError( + f'Literal type {param.annotation} must be a list of strings.' + ) + schema.type = _py_builtin_type_to_schema_type[str] + schema.enum = list(args) + if param.default is not inspect.Parameter.empty: + if not _is_default_value_compatible(param.default, param.annotation): + raise ValueError(default_value_error_msg) + schema.default = param.default + return schema + if origin is list: + schema.type = _py_builtin_type_to_schema_type[list] + schema.items = _parse_schema_from_parameter( + api_option, + inspect.Parameter( + 'item', + inspect.Parameter.POSITIONAL_OR_KEYWORD, + annotation=args[0], + ), + func_name, + ) + if param.default is not inspect.Parameter.empty: + if not _is_default_value_compatible(param.default, param.annotation): + raise ValueError(default_value_error_msg) + schema.default = param.default + return schema + if origin is Union: + schema.any_of = [] + schema.type = _py_builtin_type_to_schema_type[dict] + unique_types = set() + for arg in args: + # The first check is for NoneType in Python 3.9, since the __name__ + # attribute is not available in Python 3.9 + if type(arg) is type(None) or ( + hasattr(arg, '__name__') and arg.__name__ == 'NoneType' + ): # Optional type + schema.nullable = True + continue + schema_in_any_of = _parse_schema_from_parameter( + api_option, + inspect.Parameter( + 'item', + inspect.Parameter.POSITIONAL_OR_KEYWORD, + annotation=arg, + ), + func_name, + ) + if ( + len(param.annotation.__args__) == 2 + and type(None) in param.annotation.__args__ + ): # Optional type + for optional_arg in param.annotation.__args__: + if ( + hasattr(optional_arg, '__origin__') + and optional_arg.__origin__ is list + ): + # Optional type with list, for example Optional[list[str]] + schema.items = schema_in_any_of.items + if ( + schema_in_any_of.model_dump_json(exclude_none=True) + not in unique_types + ): + schema.any_of.append(schema_in_any_of) + unique_types.add(schema_in_any_of.model_dump_json(exclude_none=True)) + if len(schema.any_of) == 1: # param: Union[List, None] -> Array + schema.type = schema.any_of[0].type + schema.any_of = None + if ( + param.default is not None + and param.default is not inspect.Parameter.empty + ): + if not _is_default_value_compatible(param.default, param.annotation): + raise ValueError(default_value_error_msg) + schema.default = param.default + return schema + # all other generic alias will be invoked in raise branch + if ( + # for user defined class, we only support pydantic model + _extra_utils.is_annotation_pydantic_model(param.annotation) + ): + if ( + param.default is not inspect.Parameter.empty + and param.default is not None + ): + schema.default = param.default + schema.type = _py_builtin_type_to_schema_type[dict] + schema.properties = {} + for field_name, field_info in param.annotation.model_fields.items(): + schema.properties[field_name] = _parse_schema_from_parameter( + api_option, + inspect.Parameter( + field_name, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + annotation=field_info.annotation, + ), + func_name, + ) + schema.required = _get_required_fields(schema) + return schema + _raise_for_unsupported_param(param, func_name, ValueError) + + +def _get_required_fields(schema: types.Schema) -> Optional[list[str]]: + if not schema.properties: + return None + return [ + field_name + for field_name, field_schema in schema.properties.items() + if not field_schema.nullable and field_schema.default is None + ] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_base_transformers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_base_transformers.py new file mode 100644 index 0000000000000000000000000000000000000000..cc61877a2c2ef412b8bee11965c4254ec4e86235 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_base_transformers.py @@ -0,0 +1,26 @@ +# 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. +# + +"""Base transformers for Google GenAI SDK.""" +import base64 + +# Some fields don't accept url safe base64 encoding. +# We shouldn't use this transformer if the backend adhere to Cloud Type +# format https://cloud.google.com/docs/discovery/type-format. +# TODO(b/389133914,b/390320301): Remove the hack after backend fix the issue. +def t_bytes(data: bytes) -> str: + if not isinstance(data, bytes): + return data + return base64.b64encode(data).decode('ascii') diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_base_url.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_base_url.py new file mode 100644 index 0000000000000000000000000000000000000000..150537d783f1f1cddea06e3f5b987a3bea1269b5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_base_url.py @@ -0,0 +1,50 @@ +# 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 os +from typing import Optional + +from .types import HttpOptions + +_default_base_gemini_url = None +_default_base_vertex_url = None + + +def set_default_base_urls( + gemini_url: Optional[str], vertex_url: Optional[str] +) -> None: + """Overrides the base URLs for the Gemini API and Vertex AI API.""" + global _default_base_gemini_url, _default_base_vertex_url + _default_base_gemini_url = gemini_url + _default_base_vertex_url = vertex_url + + +def get_base_url( + vertexai: bool, + http_options: Optional[HttpOptions] = None, +) -> Optional[str]: + """Returns the default base URL based on the following priority. + + 1. Base URLs set via HttpOptions. + 2. Base URLs set via the latest call to setDefaultBaseUrls. + 3. Base URLs set via environment variables. + """ + if http_options and http_options.base_url: + return http_options.base_url + + if vertexai: + return _default_base_vertex_url or os.getenv('GOOGLE_VERTEX_BASE_URL') + else: + return _default_base_gemini_url or os.getenv('GOOGLE_GEMINI_BASE_URL') diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_common.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a6984f79d3ec55cfdff793391e478401d45448 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_common.py @@ -0,0 +1,847 @@ +# 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. +# + +"""Common utilities for the SDK.""" + +import base64 +import collections.abc +import datetime +import enum +import functools +import logging +import re +import typing +from typing import Any, Callable, FrozenSet, Optional, Union, get_args, get_origin +import uuid +import warnings +import pydantic +from pydantic import alias_generators +from typing_extensions import TypeAlias + +logger = logging.getLogger('google_genai._common') + +StringDict: TypeAlias = dict[str, Any] + + +class ExperimentalWarning(Warning): + """Warning for experimental features.""" + + +def set_value_by_path( + data: Optional[dict[Any, Any]], keys: list[str], value: Any +) -> None: + """Examples: + + set_value_by_path({}, ['a', 'b'], v) + -> {'a': {'b': v}} + set_value_by_path({}, ['a', 'b[]', c], [v1, v2]) + -> {'a': {'b': [{'c': v1}, {'c': v2}]}} + set_value_by_path({'a': {'b': [{'c': v1}, {'c': v2}]}}, ['a', 'b[]', 'd'], v3) + -> {'a': {'b': [{'c': v1, 'd': v3}, {'c': v2, 'd': v3}]}} + """ + if value is None: + return + for i, key in enumerate(keys[:-1]): + if key.endswith('[]'): + key_name = key[:-2] + if data is not None and key_name not in data: + if isinstance(value, list): + data[key_name] = [{} for _ in range(len(value))] + else: + raise ValueError( + f'value {value} must be a list given an array path {key}' + ) + if isinstance(value, list) and data is not None: + for j, d in enumerate(data[key_name]): + set_value_by_path(d, keys[i + 1 :], value[j]) + else: + if data is not None: + for d in data[key_name]: + set_value_by_path(d, keys[i + 1 :], value) + return + elif key.endswith('[0]'): + key_name = key[:-3] + if data is not None and key_name not in data: + data[key_name] = [{}] + if data is not None: + set_value_by_path(data[key_name][0], keys[i + 1 :], value) + return + if data is not None: + data = data.setdefault(key, {}) + + if data is not None: + existing_data = data.get(keys[-1]) + # If there is an existing value, merge, not overwrite. + if existing_data is not None: + # Don't overwrite existing non-empty value with new empty value. + # This is triggered when handling tuning datasets. + if not value: + pass + # Don't fail when overwriting value with same value + elif value == existing_data: + pass + # Instead of overwriting dictionary with another dictionary, merge them. + # This is important for handling training and validation datasets in tuning. + elif isinstance(existing_data, dict) and isinstance(value, dict): + # Merging dictionaries. Consider deep merging in the future. + existing_data.update(value) + else: + raise ValueError( + f'Cannot set value for an existing key. Key: {keys[-1]};' + f' Existing value: {existing_data}; New value: {value}.' + ) + else: + if ( + keys[-1] == '_self' + and isinstance(data, dict) + and isinstance(value, dict) + ): + data.update(value) + else: + data[keys[-1]] = value + + +def get_value_by_path( + data: Any, keys: list[str], *, default_value: Any = None +) -> Any: + """Examples: + + get_value_by_path({'a': {'b': v}}, ['a', 'b']) + -> v + get_value_by_path({'a': {'b': [{'c': v1}, {'c': v2}]}}, ['a', 'b[]', 'c']) + -> [v1, v2] + """ + if keys == ['_self']: + return data + for i, key in enumerate(keys): + if not data: + return default_value + if key.endswith('[]'): + key_name = key[:-2] + if key_name in data: + return [ + get_value_by_path(d, keys[i + 1 :], default_value=default_value) + for d in data[key_name] + ] + else: + return default_value + elif key.endswith('[0]'): + key_name = key[:-3] + if key_name in data and data[key_name]: + return get_value_by_path( + data[key_name][0], keys[i + 1 :], default_value=default_value + ) + else: + return default_value + else: + if key in data: + data = data[key] + elif isinstance(data, BaseModel) and hasattr(data, key): + data = getattr(data, key) + else: + return default_value + return data + + +def move_value_by_path(data: Any, paths: dict[str, str]) -> None: + """Moves values from source paths to destination paths. + + Examples: + move_value_by_path( + {'requests': [{'content': v1}, {'content': v2}]}, + {'requests[].*': 'requests[].request.*'} + ) + -> {'requests': [{'request': {'content': v1}}, {'request': {'content': + v2}}]} + """ + for source_path, dest_path in paths.items(): + source_keys = source_path.split('.') + dest_keys = dest_path.split('.') + + # Determine keys to exclude from wildcard to avoid cyclic references + exclude_keys = set() + wildcard_idx = -1 + for i, key in enumerate(source_keys): + if key == '*': + wildcard_idx = i + break + + if wildcard_idx != -1 and len(dest_keys) > wildcard_idx: + # Extract the intermediate key between source and dest paths + # Example: source=['requests[]', '*'], dest=['requests[]', 'request', '*'] + # We want to exclude 'request' + for i in range(wildcard_idx, len(dest_keys)): + key = dest_keys[i] + if key != '*' and not key.endswith('[]') and not key.endswith('[0]'): + exclude_keys.add(key) + + # Move values recursively + _move_value_recursive(data, source_keys, dest_keys, 0, exclude_keys) + + +def _move_value_recursive( + data: Any, + source_keys: list[str], + dest_keys: list[str], + key_idx: int, + exclude_keys: set[str], +) -> None: + """Recursively moves values from source path to destination path.""" + if key_idx >= len(source_keys): + return + + key = source_keys[key_idx] + + if key.endswith('[]'): + # Handle array iteration + key_name = key[:-2] + if key_name in data and isinstance(data[key_name], list): + for item in data[key_name]: + _move_value_recursive( + item, source_keys, dest_keys, key_idx + 1, exclude_keys + ) + elif key == '*': + # Handle wildcard - move all fields + if isinstance(data, dict): + # Get all keys to move (excluding specified keys) + keys_to_move = [ + k + for k in list(data.keys()) + if not k.startswith('_') and k not in exclude_keys + ] + + # Collect values to move + values_to_move = {k: data[k] for k in keys_to_move} + + # Set values at destination + for k, v in values_to_move.items(): + # Build destination keys with the field name + new_dest_keys = [] + for dk in dest_keys[key_idx:]: + if dk == '*': + new_dest_keys.append(k) + else: + new_dest_keys.append(dk) + set_value_by_path(data, new_dest_keys, v) + + # Delete from source + for k in keys_to_move: + del data[k] + else: + # Navigate to next level + if key in data: + _move_value_recursive( + data[key], source_keys, dest_keys, key_idx + 1, exclude_keys + ) + + +def maybe_snake_to_camel(snake_str: str, convert: bool = True) -> str: + """Converts a snake_case string to CamelCase, if convert is True.""" + if not convert: + return snake_str + return re.sub(r'_([a-zA-Z])', lambda match: match.group(1).upper(), snake_str) + + +def convert_to_dict(obj: object, convert_keys: bool = False) -> Any: + """Recursively converts a given object to a dictionary. + + If the object is a Pydantic model, it uses the model's `model_dump()` method. + + Args: + obj: The object to convert. + convert_keys: Whether to convert the keys from snake case to camel case. + + Returns: + A dictionary representation of the object, a list of objects if a list is + passed, or the object itself if it is not a dictionary, list, or Pydantic + model. + """ + if isinstance(obj, pydantic.BaseModel): + return convert_to_dict(obj.model_dump(exclude_none=True), convert_keys) + elif isinstance(obj, dict): + return { + maybe_snake_to_camel(key, convert_keys): convert_to_dict(value) + for key, value in obj.items() + } + elif isinstance(obj, list): + return [convert_to_dict(item, convert_keys) for item in obj] + else: + return obj + + +def _is_struct_type(annotation: type) -> bool: + """Checks if the given annotation is list[dict[str, typing.Any]] + + or typing.List[typing.Dict[str, typing.Any]]. + + This maps to Struct type in the API. + """ + outer_origin = get_origin(annotation) + outer_args = get_args(annotation) + + if outer_origin is not list: # Python 3.9+ normalizes list + return False + + if not outer_args or len(outer_args) != 1: + return False + + inner_annotation = outer_args[0] + + inner_origin = get_origin(inner_annotation) + inner_args = get_args(inner_annotation) + + if inner_origin is not dict: # Python 3.9+ normalizes to dict + return False + + if not inner_args or len(inner_args) != 2: + # dict should have exactly two type arguments + return False + + # Check if the dict arguments are str and typing.Any + key_type, value_type = inner_args + return key_type is str and value_type is typing.Any + + +def _remove_extra_fields(model: Any, response: dict[str, object]) -> None: + """Removes extra fields from the response that are not in the model. + + Mutates the response in place. + """ + + key_values = list(response.items()) + + for key, value in key_values: + # Need to convert to snake case to match model fields names + # ex: UsageMetadata + alias_map = { + field_info.alias: key for key, field_info in model.model_fields.items() + } + + if key not in model.model_fields and key not in alias_map: + response.pop(key) + continue + + key = alias_map.get(key, key) + + annotation = model.model_fields[key].annotation + + # Get the BaseModel if Optional + if typing.get_origin(annotation) is Union: + annotation = typing.get_args(annotation)[0] + + # if dict, assume BaseModel but also check that field type is not dict + # example: FunctionCall.args + if isinstance(value, dict) and typing.get_origin(annotation) is not dict: + _remove_extra_fields(annotation, value) + elif isinstance(value, list): + if _is_struct_type(annotation): + continue + + for item in value: + # assume a list of dict is list of BaseModel + if isinstance(item, dict): + _remove_extra_fields(typing.get_args(annotation)[0], item) + + +T = typing.TypeVar('T', bound='BaseModel') + + +def _pretty_repr( + obj: Any, + *, + indent_level: int = 0, + indent_delta: int = 2, + max_len: int = 100, + max_items: int = 5, + depth: int = 6, + visited: Optional[FrozenSet[int]] = None, +) -> str: + """Returns a representation of the given object.""" + if visited is None: + visited = frozenset() + + obj_id = id(obj) + if obj_id in visited: + return '<... Circular reference ...>' + + if depth < 0: + return '<... Max depth ...>' + + visited = frozenset(list(visited) + [obj_id]) + + indent = ' ' * indent_level + next_indent_str = ' ' * (indent_level + indent_delta) + + if isinstance(obj, pydantic.BaseModel): + cls_name = obj.__class__.__name__ + items = [] + # Sort fields for consistent output + fields = sorted(type(obj).model_fields) + + for field_name in fields: + field_info = type(obj).model_fields[field_name] + if not field_info.repr: # Respect Field(repr=False) + continue + + try: + value = getattr(obj, field_name) + except AttributeError: + continue + + if value is None: + continue + + value_repr = _pretty_repr( + value, + indent_level=indent_level + indent_delta, + indent_delta=indent_delta, + max_len=max_len, + max_items=max_items, + depth=depth - 1, + visited=visited, + ) + items.append(f'{next_indent_str}{field_name}={value_repr}') + + if not items: + return f'{cls_name}()' + return f'{cls_name}(\n' + ',\n'.join(items) + f'\n{indent})' + elif isinstance(obj, str): + if '\n' in obj: + escaped = obj.replace('"""', '\\"\\"\\"') + # Indent the multi-line string block contents + return f'"""{escaped}"""' + return repr(obj) + elif isinstance(obj, bytes): + if len(obj) > max_len: + return f"{repr(obj[:max_len-3])[:-1]}...'" + return repr(obj) + elif isinstance(obj, collections.abc.Mapping): + if not obj: + return '{}' + + # Check if the next level of recursion for keys/values will exceed the depth limit. + if depth <= 0: + item_count_str = f"{len(obj)} item{'s' if len(obj) != 1 else ''}" + return f'{{<... {item_count_str} at Max depth ...>}}' + + if len(obj) > max_items: + return f'' + + items = [] + try: + sorted_keys = sorted(obj.keys(), key=str) + except TypeError: + sorted_keys = list(obj.keys()) + + for k in sorted_keys: + v = obj[k] + k_repr = _pretty_repr( + k, + indent_level=indent_level + indent_delta, + indent_delta=indent_delta, + max_len=max_len, + max_items=max_items, + depth=depth - 1, + visited=visited, + ) + v_repr = _pretty_repr( + v, + indent_level=indent_level + indent_delta, + indent_delta=indent_delta, + max_len=max_len, + max_items=max_items, + depth=depth - 1, + visited=visited, + ) + items.append(f'{next_indent_str}{k_repr}: {v_repr}') + return f'{{\n' + ',\n'.join(items) + f'\n{indent}}}' + elif isinstance(obj, (list, tuple, set)): + return _format_collection( + obj, + indent_level=indent_level, + indent_delta=indent_delta, + max_len=max_len, + max_items=max_items, + depth=depth, + visited=visited, + ) + else: + # Fallback to standard repr, indenting subsequent lines only + raw_repr = repr(obj) + # Replace newlines with newline + indent + return raw_repr.replace('\n', f'\n{next_indent_str}') + + +def _format_collection( + obj: Any, + *, + indent_level: int, + indent_delta: int, + max_len: int, + max_items: int, + depth: int, + visited: FrozenSet[int], +) -> str: + """Formats a collection (list, tuple, set).""" + if isinstance(obj, list): + brackets = ('[', ']') + internal_obj = obj + elif isinstance(obj, tuple): + brackets = ('(', ')') + internal_obj = list(obj) + elif isinstance(obj, set): + internal_obj = list(obj) + if obj: + brackets = ('{', '}') + else: + brackets = ('set(', ')') + else: + raise ValueError(f'Unsupported collection type: {type(obj)}') + + if not internal_obj: + return brackets[0] + brackets[1] + + # If the call to _pretty_repr for elements will have depth < 0 + if depth <= 0: + item_count_str = f"{len(internal_obj)} item{'s'*(len(internal_obj)!=1)}" + return f'{brackets[0]}<... {item_count_str} at Max depth ...>{brackets[1]}' + + indent = ' ' * indent_level + next_indent_str = ' ' * (indent_level + indent_delta) + elements = [] + num_to_show = min(len(internal_obj), max_items) + + for i in range(num_to_show): + elem = internal_obj[i] + elements.append( + next_indent_str + + _pretty_repr( + elem, + indent_level=indent_level + indent_delta, + indent_delta=indent_delta, + max_len=max_len, + max_items=max_items, + depth=depth - 1, + visited=visited, + ) + ) + + if len(internal_obj) > max_items: + elements.append( + f'{next_indent_str}<... {len(internal_obj) - max_items} more items ...>' + ) + + return f'{brackets[0]}\n' + ',\n'.join(elements) + f',\n{indent}{brackets[1]}' + + +class BaseModel(pydantic.BaseModel): + + model_config = pydantic.ConfigDict( + alias_generator=alias_generators.to_camel, + populate_by_name=True, + from_attributes=True, + protected_namespaces=(), + extra='forbid', + # This allows us to use arbitrary types in the model. E.g. PIL.Image. + arbitrary_types_allowed=True, + ser_json_bytes='base64', + val_json_bytes='base64', + ignored_types=(typing.TypeVar,), + ) + + @pydantic.model_validator(mode='before') + @classmethod + def _check_field_type_mismatches(cls, data: Any) -> Any: + """Check for type mismatches and warn before Pydantic processes the data.""" + # Handle both dict and Pydantic model inputs + if not isinstance(data, (dict, pydantic.BaseModel)): + return data + + for field_name, field_info in cls.model_fields.items(): + if isinstance(data, dict): + value = data.get(field_name) + else: + value = getattr(data, field_name, None) + + if value is None: + continue + + expected_type = field_info.annotation + origin = get_origin(expected_type) + + if origin is Union: + args = get_args(expected_type) + non_none_types = [arg for arg in args if arg is not type(None)] + if len(non_none_types) == 1: + expected_type = non_none_types[0] + + if (isinstance(expected_type, type) and + get_origin(expected_type) is None and + issubclass(expected_type, pydantic.BaseModel) and + isinstance(value, pydantic.BaseModel) and + not isinstance(value, expected_type)): + logger.warning( + f"Type mismatch in {cls.__name__}.{field_name}: " + f"expected {expected_type.__name__}, got {type(value).__name__}" + ) + + return data + + def __repr__(self) -> str: + try: + return _pretty_repr(self) + except Exception: + return super().__repr__() + + @classmethod + def _from_response( + cls: typing.Type[T], + *, + response: dict[str, object], + kwargs: dict[str, object], + ) -> T: + # To maintain forward compatibility, we need to remove extra fields from + # the response. + # We will provide another mechanism to allow users to access these fields. + + # For Agent Engine we don't want to call _remove_all_fields because the + # user may pass a dict that is not a subclass of BaseModel. + # If more modules require we skip this, we may want a different approach + should_skip_removing_fields = ( + kwargs is not None + and 'config' in kwargs + and kwargs['config'] is not None + and isinstance(kwargs['config'], dict) + and 'include_all_fields' in kwargs['config'] + and kwargs['config']['include_all_fields'] + ) + + if not should_skip_removing_fields: + _remove_extra_fields(cls, response) + validated_response = cls.model_validate(response) + return validated_response + + def to_json_dict(self) -> dict[str, object]: + return self.model_dump(exclude_none=True, mode='json') + + +class CaseInSensitiveEnum(str, enum.Enum): + """Case insensitive enum.""" + + @classmethod + def _missing_(cls, value: Any) -> Any: + try: + return cls[value.upper()] # Try to access directly with uppercase + except KeyError: + try: + return cls[value.lower()] # Try to access directly with lowercase + except KeyError: + warnings.warn(f'{value} is not a valid {cls.__name__}') + try: + # Creating a enum instance based on the value + # We need to use super() to avoid infinite recursion. + unknown_enum_val = super().__new__(cls, value) + unknown_enum_val._name_ = str(value) # pylint: disable=protected-access + unknown_enum_val._value_ = value # pylint: disable=protected-access + return unknown_enum_val + except: + return None + + +def timestamped_unique_name() -> str: + """Composes a timestamped unique name. + + Returns: + A string representing a unique name. + """ + timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + unique_id = uuid.uuid4().hex[0:5] + return f'{timestamp}_{unique_id}' + + +def encode_unserializable_types(data: dict[str, object]) -> dict[str, object]: + """Converts unserializable types in dict to json.dumps() compatible types. + + This function is called in models.py after calling convert_to_dict(). The + convert_to_dict() can convert pydantic object to dict. However, the input to + convert_to_dict() is dict mixed of pydantic object and nested dict(the output + of converters). So they may be bytes in the dict and they are out of + `ser_json_bytes` control in model_dump(mode='json') called in + `convert_to_dict`, as well as datetime deserialization in Pydantic json mode. + + Returns: + A dictionary with json.dumps() incompatible type (e.g. bytes datetime) + to compatible type (e.g. base64 encoded string, isoformat date string). + """ + processed_data: dict[str, object] = {} + if not isinstance(data, dict): + return data + for key, value in data.items(): + if isinstance(value, bytes): + processed_data[key] = base64.urlsafe_b64encode(value).decode('ascii') + elif isinstance(value, datetime.datetime): + processed_data[key] = value.isoformat() + elif isinstance(value, dict): + processed_data[key] = encode_unserializable_types(value) + elif isinstance(value, list): + if all(isinstance(v, bytes) for v in value): + processed_data[key] = [ + base64.urlsafe_b64encode(v).decode('ascii') for v in value + ] + if all(isinstance(v, datetime.datetime) for v in value): + processed_data[key] = [v.isoformat() for v in value] + else: + processed_data[key] = [encode_unserializable_types(v) for v in value] + else: + processed_data[key] = value + return processed_data + + +def experimental_warning( + message: str, +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + """Experimental warning, only warns once.""" + + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + warning_done = False + + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + nonlocal warning_done + if not warning_done: + warning_done = True + warnings.warn( + message=message, + category=ExperimentalWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return wrapper + + return decorator + + +def _normalize_key_for_matching(key_str: str) -> str: + """Normalizes a key for case-insensitive and snake/camel matching.""" + return key_str.replace('_', '').lower() + + +def align_key_case( + target_dict: StringDict, update_dict: StringDict +) -> StringDict: + """Aligns the keys of update_dict to the case of target_dict keys. + + Args: + target_dict: The dictionary with the target key casing. + update_dict: The dictionary whose keys need to be aligned. + + Returns: + A new dictionary with keys aligned to target_dict's key casing. + """ + aligned_update_dict: StringDict = {} + target_keys_map = { + _normalize_key_for_matching(key): key for key in target_dict.keys() + } + + for key, value in update_dict.items(): + normalized_update_key = _normalize_key_for_matching(key) + + if normalized_update_key in target_keys_map: + aligned_key = target_keys_map[normalized_update_key] + else: + aligned_key = key + + if isinstance(value, dict) and isinstance( + target_dict.get(aligned_key), dict + ): + aligned_update_dict[aligned_key] = align_key_case( + target_dict[aligned_key], value + ) + elif isinstance(value, list) and isinstance( + target_dict.get(aligned_key), list + ): + # Direct assign as we treat update_dict list values as golden source. + aligned_update_dict[aligned_key] = value + else: + aligned_update_dict[aligned_key] = value + return aligned_update_dict + + +def recursive_dict_update( + target_dict: StringDict, update_dict: StringDict +) -> None: + """Recursively updates a target dictionary with values from an update dictionary. + + We don't enforce the updated dict values to have the same type with the + target_dict values except log warnings. + Users providing the update_dict should be responsible for constructing correct + data. + + Args: + target_dict (dict): The dictionary to be updated. + update_dict (dict): The dictionary containing updates. + """ + # Python SDK http request may change in camel case or snake case: + # If the field is directly set via setv() function, then it is camel case; + # otherwise it is snake case. + # Align the update_dict key case to target_dict to ensure correct dict update. + aligned_update_dict = align_key_case(target_dict, update_dict) + for key, value in aligned_update_dict.items(): + if ( + key in target_dict + and isinstance(target_dict[key], dict) + and isinstance(value, dict) + ): + recursive_dict_update(target_dict[key], value) + elif key in target_dict and not isinstance(target_dict[key], type(value)): + logger.warning( + f"Type mismatch for key '{key}'. Existing type:" + f' {type(target_dict[key])}, new type: {type(value)}. Overwriting.' + ) + target_dict[key] = value + else: + target_dict[key] = value + + +def is_duck_type_of(obj: Any, cls: type[pydantic.BaseModel]) -> bool: + """Checks if an object has all of the fields of a Pydantic model. + + This is a duck-typing alternative to `isinstance` to solve dual-import + problems. It returns False for dictionaries, which should be handled by + `isinstance(obj, dict)`. + + Args: + obj: The object to check. + cls: The Pydantic model class to duck-type against. + + Returns: + True if the object has all the fields defined in the Pydantic model, False + otherwise. + """ + if isinstance(obj, dict) or not hasattr(cls, 'model_fields'): + return False + + # Check if the object has all of the Pydantic model's defined fields. + all_matched = all(hasattr(obj, field) for field in cls.model_fields) + if not all_matched and isinstance(obj, pydantic.BaseModel): + # Check the other way around if obj is a Pydantic model. + # Check if the Pydantic model has all of the object's defined fields. + try: + obj_private = cls() + all_matched = all(hasattr(obj_private, f) for f in type(obj).model_fields) + except ValueError: + return False + return all_matched diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_extra_utils.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_extra_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..129c05f7d28c5068195bf74338d89c171e3318d1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_extra_utils.py @@ -0,0 +1,679 @@ +# 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. +# + +"""Extra utils depending on types that are shared between sync and async modules.""" + +import asyncio +import inspect +import io +import logging +import sys +import typing +from typing import Any, Callable, Dict, Optional, Union, get_args, get_origin +import mimetypes +import os +import pydantic + +from . import _common +from . import _mcp_utils +from . import _transformers as t +from . import errors +from . import types +from ._adapters import McpToGenAiToolAdapter + + +if sys.version_info >= (3, 10): + from types import UnionType +else: + UnionType = typing._UnionGenericAlias # type: ignore[attr-defined] + +if typing.TYPE_CHECKING: + from mcp import ClientSession as McpClientSession + from mcp.types import Tool as McpTool +else: + McpClientSession: typing.Type = Any + McpTool: typing.Type = Any + try: + from mcp import ClientSession as McpClientSession + from mcp.types import Tool as McpTool + except ImportError: + McpClientSession = None + McpTool = None + +_DEFAULT_MAX_REMOTE_CALLS_AFC = 10 + +logger = logging.getLogger('google_genai.models') + + +def _create_generate_content_config_model( + config: types.GenerateContentConfigOrDict, +) -> types.GenerateContentConfig: + if isinstance(config, dict): + return types.GenerateContentConfig(**config) + else: + return config + + +def _get_gcs_uri( + src: Union[str, types.BatchJobSourceOrDict] +) -> Optional[str]: + """Extracts the first GCS URI from the source, if available.""" + if isinstance(src, str) and src.startswith('gs://'): + return src + elif isinstance(src, dict) and src.get('gcs_uri'): + return src['gcs_uri'][0] if src['gcs_uri'] else None + elif isinstance(src, types.BatchJobSource) and src.gcs_uri: + return src.gcs_uri[0] if src.gcs_uri else None + return None + + +def _get_bigquery_uri( + src: Union[str, types.BatchJobSourceOrDict] +) -> Optional[str]: + """Extracts the BigQuery URI from the source, if available.""" + if isinstance(src, str) and src.startswith('bq://'): + return src + elif isinstance(src, dict) and src.get('bigquery_uri'): + return src['bigquery_uri'] + elif isinstance(src, types.BatchJobSource) and src.bigquery_uri: + return src.bigquery_uri + return None + + +def format_destination( + src: Union[str, types.BatchJobSource], + config: Optional[types.CreateBatchJobConfig] = None, +) -> types.CreateBatchJobConfig: + """Formats the destination uri based on the source uri for Vertex AI.""" + if config is None: + config = types.CreateBatchJobConfig() + + unique_name = None + if not config.display_name: + unique_name = _common.timestamped_unique_name() + config.display_name = f'genai_batch_job_{unique_name}' + + if not config.dest: + gcs_source_uri = _get_gcs_uri(src) + bigquery_source_uri = _get_bigquery_uri(src) + + if gcs_source_uri and gcs_source_uri.endswith('.jsonl'): + config.dest = f'{gcs_source_uri[:-6]}/dest' + elif bigquery_source_uri: + unique_name = unique_name or _common.timestamped_unique_name() + config.dest = f'{bigquery_source_uri}_dest_{unique_name}' + + return config + + +def find_afc_incompatible_tool_indexes( + config: Optional[types.GenerateContentConfigOrDict] = None, +) -> list[int]: + """Checks if the config contains any AFC incompatible tools. + + A `types.Tool` object that contains `function_declarations` is considered a + non-AFC tool for this execution path. + + Args: + config: The GenerateContentConfig to check for incompatible tools. + + Returns: + A list of indexes of the incompatible tools in the config. + """ + if not config: + return [] + config_model = _create_generate_content_config_model(config) + incompatible_tools_indexes: list[int] = [] + + if not config_model or not config_model.tools: + return incompatible_tools_indexes + + for index, tool in enumerate(config_model.tools): + if not isinstance(tool, types.Tool): + continue + if tool.function_declarations: + incompatible_tools_indexes.append(index) + if tool.mcp_servers: + incompatible_tools_indexes.append(index) + return incompatible_tools_indexes + + +def get_function_map( + config: Optional[types.GenerateContentConfigOrDict] = None, + mcp_to_genai_tool_adapters: Optional[ + dict[str, McpToGenAiToolAdapter] + ] = None, + is_caller_method_async: bool = False, +) -> dict[str, Union[Callable[..., Any], McpToGenAiToolAdapter]]: + """Returns a function map from the config.""" + function_map: dict[str, Union[Callable[..., Any], McpToGenAiToolAdapter]] = {} + if not config: + return function_map + config_model = _create_generate_content_config_model(config) + if config_model.tools: + for tool in config_model.tools: + if callable(tool): + if inspect.iscoroutinefunction(tool) and not is_caller_method_async: + raise errors.UnsupportedFunctionError( + f'Function {tool.__name__} is a coroutine function, which is not' + ' supported for automatic function calling. Please manually' + f' invoke {tool.__name__} to get the function response.' + ) + function_map[tool.__name__] = tool + if mcp_to_genai_tool_adapters: + if not is_caller_method_async: + raise errors.UnsupportedFunctionError( + 'MCP tools are not supported in synchronous methods.' + ) + for tool_name, _ in mcp_to_genai_tool_adapters.items(): + if function_map.get(tool_name): + raise ValueError( + f'Tool {tool_name} is already defined for the request.' + ) + function_map.update(mcp_to_genai_tool_adapters) + return function_map + + +def convert_number_values_for_dict_function_call_args( + args: _common.StringDict, +) -> _common.StringDict: + """Converts float values in dict with no decimal to integers.""" + return { + key: convert_number_values_for_function_call_args(value) + for key, value in args.items() + } + + +def convert_number_values_for_function_call_args( + args: Union[dict[str, object], list[object], object], +) -> Union[dict[str, object], list[object], object]: + """Converts float values with no decimal to integers.""" + if isinstance(args, float) and args.is_integer(): + return int(args) + if isinstance(args, dict): + return { + key: convert_number_values_for_function_call_args(value) + for key, value in args.items() + } + if isinstance(args, list): + return [ + convert_number_values_for_function_call_args(value) for value in args + ] + return args + + +def is_annotation_pydantic_model(annotation: Any) -> bool: + try: + return inspect.isclass(annotation) and issubclass( + annotation, pydantic.BaseModel + ) + # for python 3.10 and below, inspect.isclass(annotation) has inconsistent + # results with versions above. for example, inspect.isclass(dict[str, int]) is + # True in 3.10 and below but False in 3.11 and above. + except TypeError: + return False + + +def convert_if_exist_pydantic_model( + value: Any, annotation: Any, param_name: str, func_name: str +) -> Any: + if isinstance(value, dict) and is_annotation_pydantic_model(annotation): + try: + return annotation(**value) + except pydantic.ValidationError as e: + raise errors.UnknownFunctionCallArgumentError( + f'Failed to parse parameter {param_name} for function' + f' {func_name} from function call part because function call argument' + f' value {value} is not compatible with parameter annotation' + f' {annotation}, due to error {e}' + ) + if isinstance(value, list) and get_origin(annotation) == list: + item_type = get_args(annotation)[0] + return [ + convert_if_exist_pydantic_model(item, item_type, param_name, func_name) + for item in value + ] + if isinstance(value, dict) and get_origin(annotation) == dict: + _, value_type = get_args(annotation) + return { + k: convert_if_exist_pydantic_model(v, value_type, param_name, func_name) + for k, v in value.items() + } + # example 1: typing.Union[int, float] + # example 2: int | float equivalent to UnionType[int, float] + if get_origin(annotation) in (Union, UnionType): + for arg in get_args(annotation): + if ( + (get_args(arg) and get_origin(arg) is list) + or isinstance(value, arg) + or (isinstance(value, dict) and is_annotation_pydantic_model(arg)) + ): + try: + return convert_if_exist_pydantic_model( + value, arg, param_name, func_name + ) + # do not raise here because there could be multiple pydantic model types + # in the union type. + except pydantic.ValidationError: + continue + # if none of the union type is matched, raise error + raise errors.UnknownFunctionCallArgumentError( + f'Failed to parse parameter {param_name} for function' + f' {func_name} from function call part because function call argument' + f' value {value} cannot be converted to parameter annotation' + f' {annotation}.' + ) + # the only exception for value and annotation type to be different is int and + # float. see convert_number_values_for_function_call_args function for context + if isinstance(value, int) and annotation is float: + return value + if not isinstance(value, annotation): + raise errors.UnknownFunctionCallArgumentError( + f'Failed to parse parameter {param_name} for function {func_name} from' + f' function call part because function call argument value {value} is' + f' not compatible with parameter annotation {annotation}.' + ) + return value + + +def convert_argument_from_function( + args: _common.StringDict, function: Callable[..., Any] +) -> _common.StringDict: + signature = inspect.signature(function) + func_name = function.__name__ + converted_args = {} + for param_name, param in signature.parameters.items(): + if param_name in args: + converted_args[param_name] = convert_if_exist_pydantic_model( + args[param_name], + param.annotation, + param_name, + func_name, + ) + return converted_args + + +def invoke_function_from_dict_args( + args: _common.StringDict, function_to_invoke: Callable[..., Any] +) -> Any: + converted_args = convert_argument_from_function(args, function_to_invoke) + try: + return function_to_invoke(**converted_args) + except Exception as e: + raise errors.FunctionInvocationError( + f'Failed to invoke function {function_to_invoke.__name__} with' + f' converted arguments {converted_args} from model returned function' + f' call argument {args} because of error {e}' + ) + + +async def invoke_function_from_dict_args_async( + args: _common.StringDict, function_to_invoke: Callable[..., Any] +) -> Any: + converted_args = convert_argument_from_function(args, function_to_invoke) + try: + return await function_to_invoke(**converted_args) + except Exception as e: + raise errors.FunctionInvocationError( + f'Failed to invoke function {function_to_invoke.__name__} with' + f' converted arguments {converted_args} from model returned function' + f' call argument {args} because of error {e}' + ) + + +def get_function_response_parts( + response: types.GenerateContentResponse, + function_map: dict[str, Union[Callable[..., Any], McpToGenAiToolAdapter]], +) -> list[types.Part]: + """Returns the function response parts from the response.""" + func_response_parts = [] + if ( + response.candidates is not None + and isinstance(response.candidates[0].content, types.Content) + and response.candidates[0].content.parts is not None + ): + for part in response.candidates[0].content.parts: + if not part.function_call: + continue + func_name = part.function_call.name + if func_name is not None and part.function_call.args is not None: + func = function_map[func_name] + args = convert_number_values_for_dict_function_call_args( + part.function_call.args + ) + func_response: _common.StringDict + try: + if not isinstance(func, McpToGenAiToolAdapter): + func_response = { + 'result': invoke_function_from_dict_args(args, func) + } + except Exception as e: # pylint: disable=broad-except + func_response = {'error': str(e)} + func_response_part = types.Part.from_function_response( + name=func_name, response=func_response + ) + func_response_parts.append(func_response_part) + return func_response_parts + + +async def get_function_response_parts_async( + response: types.GenerateContentResponse, + function_map: dict[str, Union[Callable[..., Any], McpToGenAiToolAdapter]], +) -> list[types.Part]: + """Returns the function response parts from the response.""" + func_response_parts = [] + if ( + response.candidates is not None + and isinstance(response.candidates[0].content, types.Content) + and response.candidates[0].content.parts is not None + ): + for part in response.candidates[0].content.parts: + if not part.function_call: + continue + func_name = part.function_call.name + if func_name is not None and part.function_call.args is not None: + func = function_map[func_name] + args = convert_number_values_for_dict_function_call_args( + part.function_call.args + ) + func_response: _common.StringDict + try: + if isinstance(func, McpToGenAiToolAdapter): + mcp_tool_response = await func.call_tool( + types.FunctionCall(name=func_name, args=args) + ) + if mcp_tool_response.isError: + func_response = {'error': mcp_tool_response} + else: + func_response = {'result': mcp_tool_response} + elif inspect.iscoroutinefunction(func): + func_response = { + 'result': await invoke_function_from_dict_args_async(args, func) + } + else: + func_response = { + 'result': await asyncio.to_thread( + invoke_function_from_dict_args, args, func + ) + } + except Exception as e: # pylint: disable=broad-except + func_response = {'error': str(e)} + func_response_part = types.Part.from_function_response( + name=func_name, response=func_response + ) + func_response_parts.append(func_response_part) + return func_response_parts + + +def should_disable_afc( + config: Optional[types.GenerateContentConfigOrDict] = None, +) -> bool: + """Returns whether automatic function calling is enabled.""" + if not config: + return False + config_model = _create_generate_content_config_model(config) + # If max_remote_calls is less or equal to 0, warn and disable AFC. + if ( + config_model + and config_model.automatic_function_calling + and config_model.automatic_function_calling.maximum_remote_calls + is not None + and int(config_model.automatic_function_calling.maximum_remote_calls) <= 0 + ): + logger.warning( + 'max_remote_calls in automatic_function_calling_config' + f' {config_model.automatic_function_calling.maximum_remote_calls} is' + ' less than or equal to 0. Disabling automatic function calling.' + ' Please set max_remote_calls to a positive integer.' + ) + return True + + # Default to enable AFC if not specified. + if ( + not config_model.automatic_function_calling + or config_model.automatic_function_calling.disable is None + ): + return False + + if ( + config_model.automatic_function_calling.disable + and config_model.automatic_function_calling.maximum_remote_calls + is not None + # exclude the case where max_remote_calls is set to 10 by default. + and 'maximum_remote_calls' + in config_model.automatic_function_calling.model_fields_set + and int(config_model.automatic_function_calling.maximum_remote_calls) > 0 + ): + logger.warning( + '`automatic_function_calling.disable` is set to `True`. And' + ' `automatic_function_calling.maximum_remote_calls` is a' + ' positive number' + f' {config_model.automatic_function_calling.maximum_remote_calls}.' + ' Disabling automatic function calling. If you want to enable' + ' automatic function calling, please set' + ' `automatic_function_calling.disable` to `False` or leave it unset,' + ' and set `automatic_function_calling.maximum_remote_calls` to a' + ' positive integer or leave' + ' `automatic_function_calling.maximum_remote_calls` unset.' + ) + + return config_model.automatic_function_calling.disable + + +def get_max_remote_calls_afc( + config: Optional[types.GenerateContentConfigOrDict] = None, +) -> int: + if not config: + return _DEFAULT_MAX_REMOTE_CALLS_AFC + """Returns the remaining remote calls for automatic function calling.""" + if should_disable_afc(config): + raise ValueError( + 'automatic function calling is not enabled, but SDK is trying to get' + ' max remote calls.' + ) + config_model = _create_generate_content_config_model(config) + if ( + not config_model.automatic_function_calling + or config_model.automatic_function_calling.maximum_remote_calls is None + ): + return _DEFAULT_MAX_REMOTE_CALLS_AFC + return int(config_model.automatic_function_calling.maximum_remote_calls) + + +def raise_error_for_afc_incompatible_config(config: Optional[types.GenerateContentConfig] +) -> None: + """Raises an error if the config is not compatible with AFC.""" + if ( + not config + or not config.tool_config + or not config.tool_config.function_calling_config + ): + return + afc_config = config.automatic_function_calling + disable_afc_config = afc_config.disable if afc_config else False + stream_function_call = ( + config.tool_config.function_calling_config.stream_function_call_arguments + ) + + if stream_function_call and not disable_afc_config: + raise ValueError( + 'Running in streaming mode with stream_function_call_arguments' + ' enabled, this feature is not compatible with automatic function' + ' calling (AFC). Please set config.automatic_function_calling.disable' + ' to True to disable AFC or leave config.tool_config.' + ' function_calling_config.stream_function_call_arguments to be empty' + ' or set to False to disable streaming function call arguments.' + ) + +def should_append_afc_history( + config: Optional[types.GenerateContentConfigOrDict] = None, +) -> bool: + if not config: + return True + config_model = _create_generate_content_config_model(config) + if not config_model.automatic_function_calling: + return True + return not config_model.automatic_function_calling.ignore_call_history + + +def parse_config_for_mcp_usage( + config: Optional[types.GenerateContentConfigOrDict] = None, +) -> Optional[types.GenerateContentConfig]: + """Returns a parsed config with an appended MCP header if MCP tools or sessions are used.""" + if not config: + return None + config_model = _create_generate_content_config_model(config) + # Create a copy of the config model with the tools field cleared since some + # tools may not be pickleable. + config_model_copy = config_model.model_copy(update={'tools': None}) + config_model_copy.tools = config_model.tools + if config_model.tools and _mcp_utils.has_mcp_tool_usage(config_model.tools): + if config_model_copy.http_options is None: + config_model_copy.http_options = types.HttpOptions(headers={}) + if config_model_copy.http_options.headers is None: + config_model_copy.http_options.headers = {} + _mcp_utils.set_mcp_usage_header(config_model_copy.http_options.headers) + + return config_model_copy + + +async def parse_config_for_mcp_sessions( + config: Optional[types.GenerateContentConfigOrDict] = None, +) -> tuple[ + Optional[types.GenerateContentConfig], + dict[str, McpToGenAiToolAdapter], +]: + """Returns a parsed config with MCP sessions converted to GenAI tools. + + Also returns a map of MCP tools to GenAI tool adapters to be used for AFC. + """ + mcp_to_genai_tool_adapters: dict[str, McpToGenAiToolAdapter] = {} + parsed_config = parse_config_for_mcp_usage(config) + if not parsed_config: + return None, mcp_to_genai_tool_adapters + # Create a copy of the config model with the tools field cleared as they will + # be replaced with the MCP tools converted to GenAI tools. + parsed_config_copy = parsed_config.model_copy(update={'tools': None}) + if parsed_config.tools: + parsed_config_copy.tools = [] + for tool in parsed_config.tools: + if McpClientSession is not None and isinstance(tool, McpClientSession): + mcp_to_genai_tool_adapter = McpToGenAiToolAdapter( + tool, await tool.list_tools() + ) + # Extend the config with the MCP session tools converted to GenAI tools. + parsed_config_copy.tools.extend(mcp_to_genai_tool_adapter.tools) + for genai_tool in mcp_to_genai_tool_adapter.tools: + if genai_tool.function_declarations: + for function_declaration in genai_tool.function_declarations: + if function_declaration.name: + if mcp_to_genai_tool_adapters.get(function_declaration.name): + raise ValueError( + f'Tool {function_declaration.name} is already defined for' + ' the request.' + ) + mcp_to_genai_tool_adapters[function_declaration.name] = ( + mcp_to_genai_tool_adapter + ) + else: + parsed_config_copy.tools.append(tool) + + return parsed_config_copy, mcp_to_genai_tool_adapters + + +def append_chunk_contents( + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + chunk: types.GenerateContentResponse, +) -> Union[types.ContentListUnion, types.ContentListUnionDict]: + """Appends the contents of the chunk to the contents list and returns it.""" + if chunk is not None and chunk.candidates is not None: + chunk_content = chunk.candidates[0].content + contents = t.t_contents(contents) # type: ignore[assignment] + if isinstance(contents, list) and chunk_content is not None: + contents.append(chunk_content) # type: ignore[arg-type] + return contents + + +def prepare_resumable_upload( + file: Union[str, os.PathLike[str], io.IOBase], + user_http_options: Optional[types.HttpOptionsOrDict] = None, + user_mime_type: Optional[str] = None, +) -> tuple[ + types.HttpOptions, + int, + str, +]: + """Prepares the HTTP options, file bytes size and mime type for a resumable upload. + + This function inspects a file (from a path or an in-memory object) to + determine its size and MIME type. It then constructs the necessary HTTP + headers and options required to initiate a resumable upload session. + """ + size_bytes = None + mime_type = user_mime_type + if isinstance(file, io.IOBase): + if mime_type is None: + raise ValueError( + 'Unknown mime type: Could not determine the mimetype for your' + ' file\n please set the `mime_type` argument' + ) + if hasattr(file, 'mode'): + if 'b' not in file.mode: + raise ValueError('The file must be opened in binary mode.') + offset = file.tell() + file.seek(0, os.SEEK_END) + size_bytes = file.tell() - offset + file.seek(offset, os.SEEK_SET) + else: + fs_path = os.fspath(file) + if not fs_path or not os.path.isfile(fs_path): + raise FileNotFoundError(f'{file} is not a valid file path.') + size_bytes = os.path.getsize(fs_path) + if mime_type is None: + mime_type, _ = mimetypes.guess_type(fs_path) + if mime_type is None: + raise ValueError( + 'Unknown mime type: Could not determine the mimetype for your' + ' file\n please set the `mime_type` argument' + ) + http_options: types.HttpOptions + if user_http_options: + if isinstance(user_http_options, dict): + user_http_options = types.HttpOptions(**user_http_options) + http_options = user_http_options + http_options.api_version = '' + http_options.headers = { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': f'{size_bytes}', + 'X-Goog-Upload-Header-Content-Type': f'{mime_type}', + } + else: + http_options = types.HttpOptions( + api_version='', + headers={ + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': f'{size_bytes}', + 'X-Goog-Upload-Header-Content-Type': f'{mime_type}', + }, + ) + if isinstance(file, (str, os.PathLike)): + if http_options.headers is None: + http_options.headers = {} + http_options.headers['X-Goog-Upload-File-Name'] = os.path.basename(file) + return http_options, size_bytes, mime_type diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03f065d92495c47ee1624ba08e7980b58a635680 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__init__.py @@ -0,0 +1,120 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import typing as _t + +from . import types +from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes, omit, not_given +from ._utils import file_from_path +from ._client import ( + Client, + Stream, + Timeout, + Transport, + AsyncClient, + AsyncStream, + RequestOptions, + GeminiNextGenAPIClient, + AsyncGeminiNextGenAPIClient, +) +from ._models import BaseModel +from ._version import __title__, __version__ +from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse +from ._constants import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_CONNECTION_LIMITS +from ._exceptions import ( + APIError, + ConflictError, + NotFoundError, + APIStatusError, + RateLimitError, + APITimeoutError, + BadRequestError, + APIConnectionError, + AuthenticationError, + InternalServerError, + PermissionDeniedError, + UnprocessableEntityError, + APIResponseValidationError, + GeminiNextGenAPIClientError, +) +from ._base_client import DefaultHttpxClient, DefaultAioHttpClient, DefaultAsyncHttpxClient +from ._utils._logs import setup_logging as _setup_logging +from ._client_adapter import GeminiNextGenAPIClientAdapter, AsyncGeminiNextGenAPIClientAdapter + +__all__ = [ + "types", + "__version__", + "__title__", + "NoneType", + "Transport", + "ProxiesTypes", + "NotGiven", + "NOT_GIVEN", + "not_given", + "Omit", + "omit", + "GeminiNextGenAPIClientError", + "APIError", + "APIStatusError", + "APITimeoutError", + "APIConnectionError", + "APIResponseValidationError", + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", + "Timeout", + "RequestOptions", + "Client", + "AsyncClient", + "Stream", + "AsyncStream", + "GeminiNextGenAPIClient", + "AsyncGeminiNextGenAPIClient", + "file_from_path", + "BaseModel", + "DEFAULT_TIMEOUT", + "DEFAULT_MAX_RETRIES", + "DEFAULT_CONNECTION_LIMITS", + "DefaultHttpxClient", + "DefaultAsyncHttpxClient", + "DefaultAioHttpClient", + "AsyncGeminiNextGenAPIClientAdapter", + "GeminiNextGenAPIClientAdapter" +] + +if not _t.TYPE_CHECKING: + from ._utils._resources_proxy import resources as resources + +_setup_logging() + +# Update the __module__ attribute for exported symbols so that +# error messages point to this module instead of the module +# it was originally defined in, e.g. +# google.genai._interactions._exceptions.NotFoundError -> google.genai._interactions.NotFoundError +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + try: + __locals[__name].__module__ = "google.genai._interactions" + except (TypeError, AttributeError): + # Some of our exported symbols are builtins which we can't set attributes for. + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87edde8b5482f3fb9fc17788501e0fc15983e809 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_base_client.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_base_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a7a03a03111e92310d876609e90828738d8ffe2 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_base_client.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_client.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de4908d49ec9ebb8233c4a98445f3b6bc744265b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_client.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_client_adapter.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_client_adapter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11be4102b97d02e3f8661cd22bf4a71222944dd4 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_client_adapter.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_compat.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81fd6096483e44b0fbf964203a286fa557d9e8a1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_compat.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_constants.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b34d9c7d1ee9c6e3ef4f25960bcf0a25d96f1e65 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_constants.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_exceptions.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f898a5e64089ddfd6fba70bcd952f065b99c8e9e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_exceptions.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_files.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62c01feff0b35e1de7986d4bbf3b1e68791a705e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_files.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_models.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bc1ccb187a6d17a2f4d83840175203f98fd40b8 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_models.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_qs.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_qs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15c9e1970e01af5ebaa01bc8a3febb568390533b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_qs.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_resource.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61482d8651b66027ce6f1cf6bc72cad85c74ff14 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_resource.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_response.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ec0c34045ab5291021691d988deb751b11e2e2c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_response.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_streaming.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_streaming.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdf1afffdf862a8891900d437ffd6189ca81cf49 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_streaming.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_types.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daaed12630a9cd356fc9c2189d4e42822e1437fd Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_types.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_version.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a1b061732d1ebfef3b73fddd245708360d28d48 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/__pycache__/_version.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_base_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_base_client.py new file mode 100644 index 0000000000000000000000000000000000000000..580b684316a1e54b195a99d72ed09192cce5c70e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_base_client.py @@ -0,0 +1,2140 @@ +# 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 + +import sys +import json +import time +import uuid +import email +import asyncio +import inspect +import logging +import platform +import warnings +import email.utils +from types import TracebackType +from random import random +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Type, + Union, + Generic, + Mapping, + TypeVar, + Iterable, + Iterator, + Optional, + Generator, + AsyncIterator, + cast, + overload, +) +from typing_extensions import Literal, override, get_origin + +import anyio +import httpx +import distro +import pydantic +from httpx import URL +from pydantic import PrivateAttr + +from . import _exceptions +from ._qs import Querystring +from ._files import to_httpx_files, async_to_httpx_files +from ._types import ( + Body, + Omit, + Query, + Headers, + Timeout, + NotGiven, + ResponseT, + AnyMapping, + PostParser, + BinaryTypes, + RequestFiles, + HttpxSendArgs, + RequestOptions, + AsyncBinaryTypes, + HttpxRequestFiles, + ModelBuilderProtocol, + not_given, +) +from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping +from ._compat import PYDANTIC_V1, model_copy, model_dump +from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type +from ._response import ( + APIResponse, + BaseAPIResponse, + AsyncAPIResponse, + extract_response_type, +) +from ._constants import ( + DEFAULT_TIMEOUT, + MAX_RETRY_DELAY, + DEFAULT_MAX_RETRIES, + INITIAL_RETRY_DELAY, + RAW_RESPONSE_HEADER, + OVERRIDE_CAST_TO_HEADER, + DEFAULT_CONNECTION_LIMITS, +) +from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder +from ._exceptions import ( + APIStatusError, + APITimeoutError, + APIConnectionError, + APIResponseValidationError, +) +from ._utils._json import openapi_dumps + +log: logging.Logger = logging.getLogger(__name__) + +# TODO: make base page type vars covariant +SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]") +AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]") + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +_StreamT = TypeVar("_StreamT", bound=Stream[Any]) +_AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any]) + +if TYPE_CHECKING: + from httpx._config import ( + DEFAULT_TIMEOUT_CONFIG, # pyright: ignore[reportPrivateImportUsage] + ) + + HTTPX_DEFAULT_TIMEOUT = DEFAULT_TIMEOUT_CONFIG +else: + try: + from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT + except ImportError: + # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366 + HTTPX_DEFAULT_TIMEOUT = Timeout(5.0) + + +class PageInfo: + """Stores the necessary information to build the request to retrieve the next page. + + Either `url` or `params` must be set. + """ + + url: URL | NotGiven + params: Query | NotGiven + json: Body | NotGiven + + @overload + def __init__( + self, + *, + url: URL, + ) -> None: ... + + @overload + def __init__( + self, + *, + params: Query, + ) -> None: ... + + @overload + def __init__( + self, + *, + json: Body, + ) -> None: ... + + def __init__( + self, + *, + url: URL | NotGiven = not_given, + json: Body | NotGiven = not_given, + params: Query | NotGiven = not_given, + ) -> None: + self.url = url + self.json = json + self.params = params + + @override + def __repr__(self) -> str: + if self.url: + return f"{self.__class__.__name__}(url={self.url})" + if self.json: + return f"{self.__class__.__name__}(json={self.json})" + return f"{self.__class__.__name__}(params={self.params})" + + +class BasePage(GenericModel, Generic[_T]): + """ + Defines the core interface for pagination. + + Type Args: + ModelT: The pydantic model that represents an item in the response. + + Methods: + has_next_page(): Check if there is another page available + next_page_info(): Get the necessary information to make a request for the next page + """ + + _options: FinalRequestOptions = PrivateAttr() + _model: Type[_T] = PrivateAttr() + + def has_next_page(self) -> bool: + items = self._get_page_items() + if not items: + return False + return self.next_page_info() is not None + + def next_page_info(self) -> Optional[PageInfo]: ... + + def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body] + ... + + def _params_from_url(self, url: URL) -> httpx.QueryParams: + # TODO: do we have to preprocess params here? + return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params) + + def _info_to_options(self, info: PageInfo) -> FinalRequestOptions: + options = model_copy(self._options) + options._strip_raw_response_header() + + if not isinstance(info.params, NotGiven): + options.params = {**options.params, **info.params} + return options + + if not isinstance(info.url, NotGiven): + params = self._params_from_url(info.url) + url = info.url.copy_with(params=params) + options.params = dict(url.params) + options.url = str(url) + return options + + if not isinstance(info.json, NotGiven): + if not is_mapping(info.json): + raise TypeError("Pagination is only supported with mappings") + + if not options.json_data: + options.json_data = {**info.json} + else: + if not is_mapping(options.json_data): + raise TypeError("Pagination is only supported with mappings") + + options.json_data = {**options.json_data, **info.json} + return options + + raise ValueError("Unexpected PageInfo state") + + +class BaseSyncPage(BasePage[_T], Generic[_T]): + _client: SyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + client: SyncAPIClient, + model: Type[_T], + options: FinalRequestOptions, + ) -> None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + + self._model = model + self._client = client + self._options = options + + # Pydantic uses a custom `__iter__` method to support casting BaseModels + # to dictionaries. e.g. dict(model). + # As we want to support `for item in page`, this is inherently incompatible + # with the default pydantic behaviour. It is not possible to support both + # use cases at once. Fortunately, this is not a big deal as all other pydantic + # methods should continue to work as expected as there is an alternative method + # to cast a model to a dictionary, model.dict(), which is used internally + # by pydantic. + def __iter__(self) -> Iterator[_T]: # type: ignore + for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = page.get_next_page() + else: + return + + def get_next_page(self: SyncPageT) -> SyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return self._client._request_api_list(self._model, page=self.__class__, options=options) + + +class AsyncPaginator(Generic[_T, AsyncPageT]): + def __init__( + self, + client: AsyncAPIClient, + options: FinalRequestOptions, + page_cls: Type[AsyncPageT], + model: Type[_T], + ) -> None: + self._model = model + self._client = client + self._options = options + self._page_cls = page_cls + + def __await__(self) -> Generator[Any, None, AsyncPageT]: + return self._get_page().__await__() + + async def _get_page(self) -> AsyncPageT: + def _parser(resp: AsyncPageT) -> AsyncPageT: + resp._set_private_attributes( + model=self._model, + options=self._options, + client=self._client, + ) + return resp + + self._options.post_parser = _parser + + return await self._client.request(self._page_cls, self._options) + + async def __aiter__(self) -> AsyncIterator[_T]: + # https://github.com/microsoft/pyright/issues/3464 + page = cast( + AsyncPageT, + await self, # type: ignore + ) + async for item in page: + yield item + + +class BaseAsyncPage(BasePage[_T], Generic[_T]): + _client: AsyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + model: Type[_T], + client: AsyncAPIClient, + options: FinalRequestOptions, + ) -> None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + + self._model = model + self._client = client + self._options = options + + async def __aiter__(self) -> AsyncIterator[_T]: + async for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = await page.get_next_page() + else: + return + + async def get_next_page(self: AsyncPageT) -> AsyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return await self._client._request_api_list(self._model, page=self.__class__, options=options) + + +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]): + _client: _HttpxClientT + _version: str + _base_url: URL + max_retries: int + timeout: Union[float, Timeout, None] + _strict_response_validation: bool + _idempotency_header: str | None + _default_stream_cls: type[_DefaultStreamT] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None = DEFAULT_TIMEOUT, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + self._version = version + self._base_url = self._enforce_trailing_slash(URL(base_url)) + self.max_retries = max_retries + self.timeout = timeout + self._custom_headers = custom_headers or {} + self._custom_query = custom_query or {} + self._strict_response_validation = _strict_response_validation + self._idempotency_header = None + self._platform: Platform | None = None + self._is_vertex: bool = False + self._vertex_project: str | None = None + self._vertex_location: str | None = None + + if max_retries is None: # pyright: ignore[reportUnnecessaryComparison] + raise TypeError( + "max_retries cannot be None. If you want to disable retries, pass `0`; if you want unlimited retries, pass `math.inf` or a very high number; if you want the default behavior, pass `google.genai._interactions.DEFAULT_MAX_RETRIES`" + ) + + def _build_maybe_vertex_path(self, *, api_version: str, path: str) -> str: + if not self._is_vertex or not self._vertex_location or not self._vertex_project: + return f'/{api_version}/{path}' + + return f'{api_version}/projects/{self._vertex_project}/locations/{self._vertex_location}/{path}' + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _make_status_error_from_response( + self, + response: httpx.Response, + ) -> APIStatusError: + if response.is_closed and not response.is_stream_consumed: + # We can't read the response body as it has been closed + # before it was read. This can happen if an event hook + # raises a status error. + body = None + err_msg = f"Error code: {response.status_code}" + else: + err_text = response.text.strip() + body = err_text + + try: + body = json.loads(err_text) + err_msg = f"Error code: {response.status_code} - {body}" + except Exception: + err_msg = err_text or f"Error code: {response.status_code}" + + return self._make_status_error(err_msg, body=body, response=response) + + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> _exceptions.APIStatusError: + raise NotImplementedError() + + def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers: + custom_headers = options.headers or {} + headers_dict = _merge_mappings(self.default_headers, custom_headers) + self._validate_headers(headers_dict, custom_headers) + + # headers are case-insensitive while dictionaries are not. + headers = httpx.Headers(headers_dict) + + idempotency_header = self._idempotency_header + if idempotency_header and options.idempotency_key and idempotency_header not in headers: + headers[idempotency_header] = options.idempotency_key + + return headers + + def _prepare_url(self, url: str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + # Copied from httpx's `_merge_url` method. + merge_url = URL(url) + if merge_url.is_relative_url: + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + + return merge_url + + def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder: + return SSEDecoder() + + def _build_request( + self, + options: FinalRequestOptions, + ) -> httpx.Request: + if log.isEnabledFor(logging.DEBUG): + log.debug( + "Request options: %s", + model_dump( + options, + exclude_unset=True, + # Pydantic v1 can't dump every type we support in content, so we exclude it for now. + exclude={ + "content", + } + if PYDANTIC_V1 + else {}, + ), + ) + kwargs: dict[str, Any] = {} + + json_data = options.json_data + if options.extra_json is not None: + if json_data is None: + json_data = cast(Body, options.extra_json) + elif is_mapping(json_data): + json_data = _merge_mappings(json_data, options.extra_json) + else: + raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`") + + headers = self._build_headers(options) + params = _merge_mappings(self.default_query, options.params) + content_type = headers.get("Content-Type") + files = options.files + + # If the given Content-Type header is multipart/form-data then it + # has to be removed so that httpx can generate the header with + # additional information for us as it has to be in this form + # for the server to be able to correctly parse the request: + # multipart/form-data; boundary=---abc-- + if content_type is not None and content_type.startswith("multipart/form-data"): + if "boundary" not in content_type: + # only remove the header if the boundary hasn't been explicitly set + # as the caller doesn't want httpx to come up with their own boundary + headers.pop("Content-Type") + + # As we are now sending multipart/form-data instead of application/json + # we need to tell httpx to use it, https://www.python-httpx.org/advanced/clients/#multipart-file-encoding + if json_data: + if not is_dict(json_data): + raise TypeError( + f"Expected query input to be a dictionary for multipart requests but got {type(json_data)} instead." + ) + kwargs["data"] = self._serialize_multipartform(json_data) + + # httpx determines whether or not to send a "multipart/form-data" + # request based on the truthiness of the "files" argument. + # This gets around that issue by generating a dict value that + # evaluates to true. + # + # https://github.com/encode/httpx/discussions/2399#discussioncomment-3814186 + if not files: + files = cast(HttpxRequestFiles, ForceMultipartDict()) + + prepared_url = self._prepare_url(options.url) + # preserve hard-coded query params from the url + if params and prepared_url.query: + params = {**dict(prepared_url.params.items()), **params} + prepared_url = prepared_url.copy_with(raw_path=prepared_url.raw_path.split(b"?", 1)[0]) + if "_" in prepared_url.host: + # work around https://github.com/encode/httpx/discussions/2880 + kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")} + + is_body_allowed = options.method.lower() != "get" + + if is_body_allowed: + if options.content is not None and json_data is not None: + raise TypeError("Passing both `content` and `json_data` is not supported") + if options.content is not None and files is not None: + raise TypeError("Passing both `content` and `files` is not supported") + if options.content is not None: + kwargs["content"] = options.content + elif isinstance(json_data, bytes): + kwargs["content"] = json_data + elif not files: + # Don't set content when JSON is sent as multipart/form-data, + # since httpx's content param overrides other body arguments + kwargs["content"] = openapi_dumps(json_data) if is_given(json_data) and json_data is not None else None + kwargs["files"] = files + else: + headers.pop("Content-Type", None) + kwargs.pop("data", None) + + # TODO: report this error to httpx + return self._client.build_request( # pyright: ignore[reportUnknownMemberType] + headers=headers, + timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout, + method=options.method, + url=prepared_url, + # the `Query` type that we use is incompatible with qs' + # `Params` type as it needs to be typed as `Mapping[str, object]` + # so that passing a `TypedDict` doesn't cause an error. + # https://github.com/microsoft/pyright/issues/3526#event-6715453066 + params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None, + **kwargs, + ) + + def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]: + items = self.qs.stringify_items( + # TODO: type ignore is required as stringify_items is well typed but we can't be + # well typed without heavy validation. + data, # type: ignore + array_format="brackets", + ) + serialized: dict[str, object] = {} + for key, value in items: + existing = serialized.get(key) + + if not existing: + serialized[key] = value + continue + + # If a value has already been set for this key then that + # means we're sending data like `array[]=[1, 2, 3]` and we + # need to tell httpx that we want to send multiple values with + # the same key which is done by using a list or a tuple. + # + # Note: 2d arrays should never result in the same key at both + # levels so it's safe to assume that if the value is a list, + # it was because we changed it to be a list. + if is_list(existing): + existing.append(value) + else: + serialized[key] = [existing, value] + + return serialized + + def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]: + if not is_given(options.headers): + return cast_to + + # make a copy of the headers so we don't mutate user-input + headers = dict(options.headers) + + # we internally support defining a temporary header to override the + # default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response` + # see _response.py for implementation details + override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, not_given) + if is_given(override_cast_to): + options.headers = headers + return cast(Type[ResponseT], override_cast_to) + + return cast_to + + def _should_stream_response_body(self, request: httpx.Request) -> bool: + return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return] + + def _process_response_data( + self, + *, + data: object, + cast_to: type[ResponseT], + response: httpx.Response, + ) -> ResponseT: + if data is None: + return cast(ResponseT, None) + + if cast_to is object: + return cast(ResponseT, data) + + try: + if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol): + return cast(ResponseT, cast_to.build(response=response, data=data)) + + if self._strict_response_validation: + return cast(ResponseT, validate_type(type_=cast_to, value=data)) + + return cast(ResponseT, construct_type(type_=cast_to, value=data)) + except pydantic.ValidationError as err: + raise APIResponseValidationError(response=response, body=data) from err + + @property + def qs(self) -> Querystring: + return Querystring() + + @property + def custom_auth(self) -> httpx.Auth | None: + return None + + @property + def auth_headers(self) -> dict[str, str]: + return {} + + @property + def default_headers(self) -> dict[str, str | Omit]: + return { + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": self.user_agent, + **self.auth_headers, + **self._custom_headers, + } + + @property + def default_query(self) -> dict[str, object]: + return { + **self._custom_query, + } + + def _validate_headers( + self, + headers: Headers, # noqa: ARG002 + custom_headers: Headers, # noqa: ARG002 + ) -> None: + """Validate the given default headers and custom headers. + + Does nothing by default. + """ + return + + @property + def user_agent(self) -> str: + return f"{self.__class__.__name__}/Python {self._version}" + + @property + def base_url(self) -> URL: + return self._base_url + + @base_url.setter + def base_url(self, url: URL | str) -> None: + self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url)) + + def platform_headers(self) -> Dict[str, str]: + # the actual implementation is in a separate `lru_cache` decorated + # function because adding `lru_cache` to methods will leak memory + # https://github.com/python/cpython/issues/88476 + return platform_headers(self._version, platform=self._platform) + + def _parse_retry_after_header(self, response_headers: Optional[httpx.Headers] = None) -> float | None: + """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified. + + About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax + """ + if response_headers is None: + return None + + # First, try the non-standard `retry-after-ms` header for milliseconds, + # which is more precise than integer-seconds `retry-after` + try: + retry_ms_header = response_headers.get("retry-after-ms", None) + return float(retry_ms_header) / 1000 + except (TypeError, ValueError): + pass + + # Next, try parsing `retry-after` header as seconds (allowing nonstandard floats). + retry_header = response_headers.get("retry-after") + try: + # note: the spec indicates that this should only ever be an integer + # but if someone sends a float there's no reason for us to not respect it + return float(retry_header) + except (TypeError, ValueError): + pass + + # Last, try parsing `retry-after` as a date. + retry_date_tuple = email.utils.parsedate_tz(retry_header) + if retry_date_tuple is None: + return None + + retry_date = email.utils.mktime_tz(retry_date_tuple) + return float(retry_date - time.time()) + + def _calculate_retry_timeout( + self, + remaining_retries: int, + options: FinalRequestOptions, + response_headers: Optional[httpx.Headers] = None, + ) -> float: + max_retries = options.get_max_retries(self.max_retries) + + # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says. + retry_after = self._parse_retry_after_header(response_headers) + if retry_after is not None and 0 < retry_after <= 60: + return retry_after + + # Also cap retry count to 1000 to avoid any potential overflows with `pow` + nb_retries = min(max_retries - remaining_retries, 1000) + + # Apply exponential backoff, but not more than the max. + sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY) + + # Apply some jitter, plus-or-minus half a second. + jitter = 1 - 0.25 * random() + timeout = sleep_seconds * jitter + return timeout if timeout >= 0 else 0 + + def _should_retry(self, response: httpx.Response) -> bool: + # Note: this is not a standard header + should_retry_header = response.headers.get("x-should-retry") + + # If the server explicitly says whether or not to retry, obey. + if should_retry_header == "true": + log.debug("Retrying as header `x-should-retry` is set to `true`") + return True + if should_retry_header == "false": + log.debug("Not retrying as header `x-should-retry` is set to `false`") + return False + + # Retry on request timeouts. + if response.status_code == 408: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry on lock timeouts. + if response.status_code == 409: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry on rate limits. + if response.status_code == 429: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry internal errors. + if response.status_code >= 500: + log.debug("Retrying due to status code %i", response.status_code) + return True + + log.debug("Not retrying") + return False + + def _idempotency_key(self) -> str: + return f"stainless-python-retry-{uuid.uuid4()}" + + +class _DefaultHttpxClient(httpx.Client): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultHttpxClient = httpx.Client + """An alias to `httpx.Client` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.Client` will result in httpx's defaults being used, not ours. + """ +else: + DefaultHttpxClient = _DefaultHttpxClient + + +class SyncHttpxClientWrapper(DefaultHttpxClient): + def __del__(self) -> None: + if self.is_closed: + return + + try: + self.close() + except Exception: + pass + + +class SyncAPIClient(BaseClient[httpx.Client, Stream[Any]]): + _client: httpx.Client + _default_stream_cls: type[Stream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.Client | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + _strict_response_validation: bool, + ) -> None: + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + if http_client is not None and not isinstance(http_client, httpx.Client): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}" + ) + + super().__init__( + version=version, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + base_url=base_url, + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or SyncHttpxClientWrapper( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + ) + + def is_closed(self) -> bool: + return self._client.is_closed + + def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + # If an error is thrown while constructing a client, self._client + # may not be present + if hasattr(self, "_client"): + self._client.close() + + def __enter__(self: _T) -> _T: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> FinalRequestOptions: + """Hook for mutating the given options""" + return options + + def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[True], + stream_cls: Type[_StreamT], + ) -> _StreamT: ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: Type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + cast_to = self._maybe_override_cast_to(cast_to, options) + + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + if input_options.idempotency_key is None and input_options.method.lower() != "get": + # ensure the idempotency key is reused between requests + input_options.idempotency_key = self._idempotency_key() + + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) + + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = self._prepare_options(options) + + remaining_retries = max_retries - retries_taken + request = self._build_request(options) + self._prepare_request(request) + + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + + if options.follow_redirects is not None: + kwargs["follow_redirects"] = options.follow_redirects + + log.debug("Sending HTTP Request: %s %s", request.method, request.url) + + response = None + try: + response = self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, + ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + err.response.close() + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + err.response.read() + + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None + + break + + assert response is not None, "could not resolve response (should never happen)" + return self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + retries_taken=retries_taken, + ) + + def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken + if remaining_retries == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining_retries) + + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + time.sleep(timeout) + + def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, + ) -> ResponseT: + origin = get_origin(cast_to) or cast_to + + if ( + inspect.isclass(origin) + and issubclass(origin, BaseAPIResponse) + # we only want to actually return the custom BaseAPIResponse class if we're + # returning the raw response, or if we're not streaming SSE, as if we're streaming + # SSE then `cast_to` doesn't actively reflect the type we need to parse into + and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER))) + ): + if not issubclass(origin, APIResponse): + raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + ResponseT, + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = APIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return api_response.parse() + + def _request_api_list( + self, + model: Type[object], + page: Type[SyncPageT], + options: FinalRequestOptions, + ) -> SyncPageT: + def _parser(resp: SyncPageT) -> SyncPageT: + resp._set_private_attributes( + client=self, + model=model, + options=options, + ) + return resp + + options.post_parser = _parser + + return self.request(page, options, stream=False) + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + # cast is required because mypy complains about returning Any even though + # it understands the type variables + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="patch", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return self.request(cast_to, opts) + + def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return self.request(cast_to, opts) + + def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options) + return self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + model: Type[object], + page: Type[SyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> SyncPageT: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +class _DefaultAsyncHttpxClient(httpx.AsyncClient): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + super().__init__(**kwargs) + + +try: + import httpx_aiohttp +except ImportError: + + class _DefaultAioHttpClient(httpx.AsyncClient): + def __init__(self, **_kwargs: Any) -> None: + raise RuntimeError("To use the aiohttp client you must have installed the package with the `aiohttp` extra") +else: + + class _DefaultAioHttpClient(httpx_aiohttp.HttpxAiohttpClient): # type: ignore + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultAsyncHttpxClient = httpx.AsyncClient + """An alias to `httpx.AsyncClient` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.AsyncClient` will result in httpx's defaults being used, not ours. + """ + + DefaultAioHttpClient = httpx.AsyncClient + """An alias to `httpx.AsyncClient` that changes the default HTTP transport to `aiohttp`.""" +else: + DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient + DefaultAioHttpClient = _DefaultAioHttpClient + + +class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient): + def __del__(self) -> None: + if self.is_closed: + return + + try: + # TODO(someday): support non asyncio runtimes here + asyncio.get_running_loop().create_task(self.aclose()) + except Exception: + pass + + +class AsyncAPIClient(BaseClient[httpx.AsyncClient, AsyncStream[Any]]): + _client: httpx.AsyncClient + _default_stream_cls: type[AsyncStream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.AsyncClient | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + if http_client is not None and not isinstance(http_client, httpx.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.AsyncClient` but got {type(http_client)}" + ) + + super().__init__( + version=version, + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or AsyncHttpxClientWrapper( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + ) + + def is_closed(self) -> bool: + return self._client.is_closed + + async def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + await self._client.aclose() + + async def __aenter__(self: _T) -> _T: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> FinalRequestOptions: + """Hook for mutating the given options""" + return options + + async def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + if self._platform is None: + # `get_platform` can make blocking IO calls so we + # execute it earlier while we are in an async context + self._platform = await asyncify(get_platform)() + + cast_to = self._maybe_override_cast_to(cast_to, options) + + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + if input_options.idempotency_key is None and input_options.method.lower() != "get": + # ensure the idempotency key is reused between requests + input_options.idempotency_key = self._idempotency_key() + + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) + + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = await self._prepare_options(options) + + remaining_retries = max_retries - retries_taken + request = self._build_request(options) + await self._prepare_request(request) + + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + + if options.follow_redirects is not None: + kwargs["follow_redirects"] = options.follow_redirects + + log.debug("Sending HTTP Request: %s %s", request.method, request.url) + + response = None + try: + response = await self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, + ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + await err.response.aclose() + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + await err.response.aread() + + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None + + break + + assert response is not None, "could not resolve response (should never happen)" + return await self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + retries_taken=retries_taken, + ) + + async def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken + if remaining_retries == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining_retries) + + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + await anyio.sleep(timeout) + + async def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, + ) -> ResponseT: + origin = get_origin(cast_to) or cast_to + + if ( + inspect.isclass(origin) + and issubclass(origin, BaseAPIResponse) + # we only want to actually return the custom BaseAPIResponse class if we're + # returning the raw response, or if we're not streaming SSE, as if we're streaming + # SSE then `cast_to` doesn't actively reflect the type we need to parse into + and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER))) + ): + if not issubclass(origin, AsyncAPIResponse): + raise TypeError(f"API Response types must subclass {AsyncAPIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + "ResponseT", + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = AsyncAPIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return await api_response.parse() + + def _request_api_list( + self, + model: Type[_T], + page: Type[AsyncPageT], + options: FinalRequestOptions, + ) -> AsyncPaginator[_T, AsyncPageT]: + return AsyncPaginator(client=self, options=options, page_cls=page, model=model) + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + async def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="patch", + url=path, + json_data=body, + content=content, + files=await async_to_httpx_files(files), + **options, + ) + return await self.request(cast_to, opts) + + async def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts) + + async def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options) + return await self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + model: Type[_T], + page: Type[AsyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> AsyncPaginator[_T, AsyncPageT]: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +def make_request_options( + *, + query: Query | None = None, + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + idempotency_key: str | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + post_parser: PostParser | NotGiven = not_given, +) -> RequestOptions: + """Create a dict of type RequestOptions without keys of NotGiven values.""" + options: RequestOptions = {} + if extra_headers is not None: + options["headers"] = extra_headers + + if extra_body is not None: + options["extra_json"] = cast(AnyMapping, extra_body) + + if query is not None: + options["params"] = query + + if extra_query is not None: + options["params"] = {**options.get("params", {}), **extra_query} + + if not isinstance(timeout, NotGiven): + options["timeout"] = timeout + + if idempotency_key is not None: + options["idempotency_key"] = idempotency_key + + if is_given(post_parser): + # internal + options["post_parser"] = post_parser # type: ignore + + return options + + +class ForceMultipartDict(Dict[str, None]): + def __bool__(self) -> bool: + return True + + +class OtherPlatform: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"Other:{self.name}" + + +Platform = Union[ + OtherPlatform, + Literal[ + "MacOS", + "Linux", + "Windows", + "FreeBSD", + "OpenBSD", + "iOS", + "Android", + "Unknown", + ], +] + + +def get_platform() -> Platform: + try: + system = platform.system().lower() + platform_name = platform.platform().lower() + except Exception: + return "Unknown" + + if "iphone" in platform_name or "ipad" in platform_name: + # Tested using Python3IDE on an iPhone 11 and Pythonista on an iPad 7 + # system is Darwin and platform_name is a string like: + # - Darwin-21.6.0-iPhone12,1-64bit + # - Darwin-21.6.0-iPad7,11-64bit + return "iOS" + + if system == "darwin": + return "MacOS" + + if system == "windows": + return "Windows" + + if "android" in platform_name: + # Tested using Pydroid 3 + # system is Linux and platform_name is a string like 'Linux-5.10.81-android12-9-00001-geba40aecb3b7-ab8534902-aarch64-with-libc' + return "Android" + + if system == "linux": + # https://distro.readthedocs.io/en/latest/#distro.id + distro_id = distro.id() + if distro_id == "freebsd": + return "FreeBSD" + + if distro_id == "openbsd": + return "OpenBSD" + + return "Linux" + + if platform_name: + return OtherPlatform(platform_name) + + return "Unknown" + + +@lru_cache(maxsize=None) +def platform_headers(version: str, *, platform: Platform | None) -> Dict[str, str]: + return { + "X-Stainless-Lang": "python", + "X-Stainless-Package-Version": version, + "X-Stainless-OS": str(platform or get_platform()), + "X-Stainless-Arch": str(get_architecture()), + "X-Stainless-Runtime": get_python_runtime(), + "X-Stainless-Runtime-Version": get_python_version(), + } + + +class OtherArch: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"other:{self.name}" + + +Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]] + + +def get_python_runtime() -> str: + try: + return platform.python_implementation() + except Exception: + return "unknown" + + +def get_python_version() -> str: + try: + return platform.python_version() + except Exception: + return "unknown" + + +def get_architecture() -> Arch: + try: + machine = platform.machine().lower() + except Exception: + return "unknown" + + if machine in ("arm64", "aarch64"): + return "arm64" + + # TODO: untested + if machine == "arm": + return "arm" + + if machine == "x86_64": + return "x64" + + # TODO: untested + if sys.maxsize <= 2**32: + return "x32" + + if machine: + return OtherArch(machine) + + return "unknown" + + +def _merge_mappings( + obj1: Mapping[_T_co, Union[_T, Omit]], + obj2: Mapping[_T_co, Union[_T, Omit]], +) -> Dict[_T_co, _T]: + """Merge two mappings of the same type, removing any values that are instances of `Omit`. + + In cases with duplicate keys the second mapping takes precedence. + """ + merged = {**obj1, **obj2} + return {key: value for key, value in merged.items() if not isinstance(value, Omit)} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..badceaead45b7d8f77ca0eb4fdb20ece34cbf916 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_client.py @@ -0,0 +1,600 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING, Any, Mapping +from typing_extensions import Self, override + +import httpx + +from . import _exceptions +from ._qs import Querystring +from ._types import ( + Omit, + Headers, + Timeout, + NotGiven, + Transport, + ProxiesTypes, + RequestOptions, + not_given, +) +from ._utils import is_given +from ._compat import cached_property +from ._models import FinalRequestOptions +from ._version import __version__ +from ._streaming import Stream as Stream, AsyncStream as AsyncStream +from ._exceptions import APIStatusError +from ._base_client import ( + DEFAULT_MAX_RETRIES, + SyncAPIClient, + AsyncAPIClient, +) +from ._client_adapter import GeminiNextGenAPIClientAdapter, AsyncGeminiNextGenAPIClientAdapter + +if TYPE_CHECKING: + from .resources import webhooks, interactions + from .resources.webhooks import WebhooksResource, AsyncWebhooksResource + from .resources.interactions import InteractionsResource, AsyncInteractionsResource + +__all__ = [ + "Timeout", + "Transport", + "ProxiesTypes", + "RequestOptions", + "GeminiNextGenAPIClient", + "AsyncGeminiNextGenAPIClient", + "Client", + "AsyncClient", +] + + +class GeminiNextGenAPIClient(SyncAPIClient): + # client options + api_key: str | None + api_version: str + client_adapter: GeminiNextGenAPIClientAdapter | None + + def __init__( + self, + *, + api_key: str | None = None, + api_version: str | None = "v1beta", + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. + # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.Client | None = None, + client_adapter: GeminiNextGenAPIClientAdapter | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new synchronous GeminiNextGenAPIClient client instance. + + This automatically infers the `api_key` argument from the `GEMINI_API_KEY` environment variable if it is not provided. + """ + if api_key is None: + api_key = os.environ.get("GEMINI_API_KEY") + self.api_key = api_key + + if api_version is None: + api_version = "v1beta" + self.api_version = api_version + + if base_url is None: + base_url = os.environ.get("GEMINI_NEXT_GEN_API_BASE_URL") + if base_url is None: + base_url = f"https://generativelanguage.googleapis.com" + + self.client_adapter = client_adapter + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + self._default_stream_cls = Stream + + @cached_property + def interactions(self) -> InteractionsResource: + from .resources.interactions import InteractionsResource + + return InteractionsResource(self) + + @cached_property + def webhooks(self) -> WebhooksResource: + from .resources.webhooks import WebhooksResource + + return WebhooksResource(self) + + @cached_property + def with_raw_response(self) -> GeminiNextGenAPIClientWithRawResponse: + return GeminiNextGenAPIClientWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> GeminiNextGenAPIClientWithStreamedResponse: + return GeminiNextGenAPIClientWithStreamedResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + api_key = self.api_key + if api_key is None: + return {} + return {"x-goog-api-key": api_key} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + **self._custom_headers, + } + + @override + def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None: + if headers.get("Authorization") or custom_headers.get("Authorization") or isinstance(custom_headers.get("Authorization"), Omit): + return + if self.api_key and headers.get("x-goog-api-key"): + return + if custom_headers.get("x-goog-api-key") or isinstance(custom_headers.get("x-goog-api-key"), Omit): + return + + raise TypeError( + '"Could not resolve authentication method. Expected the api_key to be set. Or for the `x-goog-api-key` headers to be explicitly omitted"' + ) + + @override + def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + if not self.client_adapter or not self.client_adapter.is_vertex_ai(): + return options + + headers = options.headers or {} + has_auth = headers.get("Authorization") or headers.get("x-goog-api-key") # pytype: disable=attribute-error + if has_auth: + return options + + adapted_headers = self.client_adapter.get_auth_headers() + if adapted_headers: + options.headers = { + **adapted_headers, + **headers + } + return options + + def copy( + self, + *, + api_key: str | None = None, + api_version: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = not_given, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + client_adapter: GeminiNextGenAPIClientAdapter | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + api_version=api_version or self.api_version, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + client_adapter=self.client_adapter or client_adapter, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + def _get_api_version_path_param(self) -> str: + return self.api_version + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class AsyncGeminiNextGenAPIClient(AsyncAPIClient): + # client options + api_key: str | None + api_version: str + client_adapter: AsyncGeminiNextGenAPIClientAdapter | None + + def __init__( + self, + *, + api_key: str | None = None, + api_version: str | None = "v1beta", + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. + # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details. + http_client: httpx.AsyncClient | None = None, + client_adapter: AsyncGeminiNextGenAPIClientAdapter | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new async AsyncGeminiNextGenAPIClient client instance. + + This automatically infers the `api_key` argument from the `GEMINI_API_KEY` environment variable if it is not provided. + """ + if api_key is None: + api_key = os.environ.get("GEMINI_API_KEY") + self.api_key = api_key + + if api_version is None: + api_version = "v1beta" + self.api_version = api_version + + if base_url is None: + base_url = os.environ.get("GEMINI_NEXT_GEN_API_BASE_URL") + if base_url is None: + base_url = f"https://generativelanguage.googleapis.com" + + self.client_adapter = client_adapter + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + self._default_stream_cls = AsyncStream + + @cached_property + def interactions(self) -> AsyncInteractionsResource: + from .resources.interactions import AsyncInteractionsResource + + return AsyncInteractionsResource(self) + + @cached_property + def webhooks(self) -> AsyncWebhooksResource: + from .resources.webhooks import AsyncWebhooksResource + + return AsyncWebhooksResource(self) + + @cached_property + def with_raw_response(self) -> AsyncGeminiNextGenAPIClientWithRawResponse: + return AsyncGeminiNextGenAPIClientWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncGeminiNextGenAPIClientWithStreamedResponse: + return AsyncGeminiNextGenAPIClientWithStreamedResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + api_key = self.api_key + if api_key is None: + return {} + return {"x-goog-api-key": api_key} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + **self._custom_headers, + } + + @override + def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None: + if headers.get("Authorization") or custom_headers.get("Authorization") or isinstance(custom_headers.get("Authorization"), Omit): + return + if self.api_key and headers.get("x-goog-api-key"): + return + if custom_headers.get("x-goog-api-key") or isinstance(custom_headers.get("x-goog-api-key"), Omit): + return + + raise TypeError( + '"Could not resolve authentication method. Expected the api_key to be set. Or for the `x-goog-api-key` headers to be explicitly omitted"' + ) + + @override + async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + if not self.client_adapter or not self.client_adapter.is_vertex_ai(): + return options + + headers = options.headers or {} + has_auth = headers.get("Authorization") or headers.get("x-goog-api-key") # pytype: disable=attribute-error + if has_auth: + return options + + adapted_headers = await self.client_adapter.async_get_auth_headers() + if adapted_headers: + options.headers = { + **adapted_headers, + **headers + } + return options + + def copy( + self, + *, + api_key: str | None = None, + api_version: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = not_given, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + client_adapter: AsyncGeminiNextGenAPIClientAdapter | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + api_version=api_version or self.api_version, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + client_adapter=self.client_adapter or client_adapter, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + def _get_api_version_path_param(self) -> str: + return self.api_version + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class GeminiNextGenAPIClientWithRawResponse: + _client: GeminiNextGenAPIClient + + def __init__(self, client: GeminiNextGenAPIClient) -> None: + self._client = client + + @cached_property + def interactions(self) -> interactions.InteractionsResourceWithRawResponse: + from .resources.interactions import InteractionsResourceWithRawResponse + + return InteractionsResourceWithRawResponse(self._client.interactions) + + @cached_property + def webhooks(self) -> webhooks.WebhooksResourceWithRawResponse: + from .resources.webhooks import WebhooksResourceWithRawResponse + + return WebhooksResourceWithRawResponse(self._client.webhooks) + + +class AsyncGeminiNextGenAPIClientWithRawResponse: + _client: AsyncGeminiNextGenAPIClient + + def __init__(self, client: AsyncGeminiNextGenAPIClient) -> None: + self._client = client + + @cached_property + def interactions(self) -> interactions.AsyncInteractionsResourceWithRawResponse: + from .resources.interactions import AsyncInteractionsResourceWithRawResponse + + return AsyncInteractionsResourceWithRawResponse(self._client.interactions) + + @cached_property + def webhooks(self) -> webhooks.AsyncWebhooksResourceWithRawResponse: + from .resources.webhooks import AsyncWebhooksResourceWithRawResponse + + return AsyncWebhooksResourceWithRawResponse(self._client.webhooks) + + +class GeminiNextGenAPIClientWithStreamedResponse: + _client: GeminiNextGenAPIClient + + def __init__(self, client: GeminiNextGenAPIClient) -> None: + self._client = client + + @cached_property + def interactions(self) -> interactions.InteractionsResourceWithStreamingResponse: + from .resources.interactions import InteractionsResourceWithStreamingResponse + + return InteractionsResourceWithStreamingResponse(self._client.interactions) + + @cached_property + def webhooks(self) -> webhooks.WebhooksResourceWithStreamingResponse: + from .resources.webhooks import WebhooksResourceWithStreamingResponse + + return WebhooksResourceWithStreamingResponse(self._client.webhooks) + + +class AsyncGeminiNextGenAPIClientWithStreamedResponse: + _client: AsyncGeminiNextGenAPIClient + + def __init__(self, client: AsyncGeminiNextGenAPIClient) -> None: + self._client = client + + @cached_property + def interactions(self) -> interactions.AsyncInteractionsResourceWithStreamingResponse: + from .resources.interactions import AsyncInteractionsResourceWithStreamingResponse + + return AsyncInteractionsResourceWithStreamingResponse(self._client.interactions) + + @cached_property + def webhooks(self) -> webhooks.AsyncWebhooksResourceWithStreamingResponse: + from .resources.webhooks import AsyncWebhooksResourceWithStreamingResponse + + return AsyncWebhooksResourceWithStreamingResponse(self._client.webhooks) + + +Client = GeminiNextGenAPIClient + +AsyncClient = AsyncGeminiNextGenAPIClient diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_client_adapter.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_client_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..32c4750c237b0ee7cbec81c079f0ac82f517a7cd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_client_adapter.py @@ -0,0 +1,48 @@ +# 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 abc import ABC, abstractmethod + +__all__ = [ + "GeminiNextGenAPIClientAdapter", + "AsyncGeminiNextGenAPIClientAdapter" +] + +class BaseGeminiNextGenAPIClientAdapter(ABC): + @abstractmethod + def is_vertex_ai(self) -> bool: + ... + + @abstractmethod + def get_project(self) -> str | None: + ... + + @abstractmethod + def get_location(self) -> str | None: + ... + + +class AsyncGeminiNextGenAPIClientAdapter(BaseGeminiNextGenAPIClientAdapter): + @abstractmethod + async def async_get_auth_headers(self) -> dict[str, str] | None: + ... + + +class GeminiNextGenAPIClientAdapter(BaseGeminiNextGenAPIClientAdapter): + @abstractmethod + def get_auth_headers(self) -> dict[str, str] | None: + ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_compat.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..d00a0df9cbae0aa13eb14be564769c2373e0d044 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_compat.py @@ -0,0 +1,241 @@ +# 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 TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload +from datetime import date, datetime +from typing_extensions import Self, Literal, TypedDict + +import pydantic +from pydantic.fields import FieldInfo + +from ._types import IncEx, StrBytesIntFloat + +_T = TypeVar("_T") +_ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel) + +# --------------- Pydantic v2, v3 compatibility --------------- + +# Pyright incorrectly reports some of our functions as overriding a method when they don't +# pyright: reportIncompatibleMethodOverride=false + +PYDANTIC_V1 = pydantic.VERSION.startswith("1.") + +if TYPE_CHECKING: + + def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001 + ... + + def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001 + ... + + def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001 + ... + + def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001 + ... + + def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001 + ... + + def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001 + ... + + def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 + ... + +else: + # v1 re-exports + if PYDANTIC_V1: + from pydantic.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime + else: + from ._utils import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + parse_date as parse_date, + is_typeddict as is_typeddict, + parse_datetime as parse_datetime, + is_literal_type as is_literal_type, + ) + + +# refactored config +if TYPE_CHECKING: + from pydantic import ConfigDict as ConfigDict +else: + if PYDANTIC_V1: + # TODO: provide an error message here? + ConfigDict = None + else: + from pydantic import ConfigDict as ConfigDict + + +# renamed methods / properties +def parse_obj(model: type[_ModelT], value: object) -> _ModelT: + if PYDANTIC_V1: + return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + else: + return model.model_validate(value) + + +def field_is_required(field: FieldInfo) -> bool: + if PYDANTIC_V1: + return field.required # type: ignore + return field.is_required() + + +def field_get_default(field: FieldInfo) -> Any: + value = field.get_default() + if PYDANTIC_V1: + return value + from pydantic_core import PydanticUndefined + + if value == PydanticUndefined: + return None + return value + + +def field_outer_type(field: FieldInfo) -> Any: + if PYDANTIC_V1: + return field.outer_type_ # type: ignore + return field.annotation + + +def get_model_config(model: type[pydantic.BaseModel]) -> Any: + if PYDANTIC_V1: + return model.__config__ # type: ignore + return model.model_config + + +def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]: + if PYDANTIC_V1: + return model.__fields__ # type: ignore + return model.model_fields + + +def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT: + if PYDANTIC_V1: + return model.copy(deep=deep) # type: ignore + return model.model_copy(deep=deep) + + +def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: + if PYDANTIC_V1: + return model.json(indent=indent) # type: ignore + return model.model_dump_json(indent=indent) + + +class _ModelDumpKwargs(TypedDict, total=False): + by_alias: bool + + +def model_dump( + model: pydantic.BaseModel, + *, + exclude: IncEx | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + warnings: bool = True, + mode: Literal["json", "python"] = "python", + by_alias: bool | None = None, +) -> dict[str, Any]: + if (not PYDANTIC_V1) or hasattr(model, "model_dump"): + kwargs: _ModelDumpKwargs = {} + if by_alias is not None: + kwargs["by_alias"] = by_alias + return model.model_dump( + mode=mode, + exclude=exclude, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + # warnings are not supported in Pydantic v1 + warnings=True if PYDANTIC_V1 else warnings, + **kwargs, + ) + return cast( + "dict[str, Any]", + model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias) + ), + ) + + +def model_parse(model: type[_ModelT], data: Any) -> _ModelT: + if PYDANTIC_V1: + return model.parse_obj(data) # pyright: ignore[reportDeprecated] + return model.model_validate(data) + + +# generic models +if TYPE_CHECKING: + + class GenericModel(pydantic.BaseModel): ... + +else: + if PYDANTIC_V1: + import pydantic.generics + + class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... + else: + # there no longer needs to be a distinction in v2 but + # we still have to create our own subclass to avoid + # inconsistent MRO ordering errors + class GenericModel(pydantic.BaseModel): ... + + +# cached properties +if TYPE_CHECKING: + cached_property = property + + # we define a separate type (copied from typeshed) + # that represents that `cached_property` is `set`able + # at runtime, which differs from `@property`. + # + # this is a separate type as editors likely special case + # `@property` and we don't want to cause issues just to have + # more helpful internal types. + + class typed_cached_property(Generic[_T]): + func: Callable[[Any], _T] + attrname: str | None + + def __init__(self, func: Callable[[Any], _T]) -> None: ... + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... + + @overload + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ... + + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self: + raise NotImplementedError() + + def __set_name__(self, owner: type[Any], name: str) -> None: ... + + # __set__ is not defined at runtime, but @cached_property is designed to be settable + def __set__(self, instance: object, value: _T) -> None: ... +else: + from functools import cached_property as cached_property + + typed_cached_property = cached_property diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_constants.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..7241594a620131e001a3180e0e2b626c41946d60 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_constants.py @@ -0,0 +1,29 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import httpx + +RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response" +OVERRIDE_CAST_TO_HEADER = "____stainless_override_cast_to" + +# default timeout is 1 minute +DEFAULT_TIMEOUT = httpx.Timeout(timeout=60, connect=5.0) +DEFAULT_MAX_RETRIES = 2 +DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20) + +INITIAL_RETRY_DELAY = 0.5 +MAX_RETRY_DELAY = 8.0 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_exceptions.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..0b8bc6eb02deb7406a23115ef8fd29436abc42d1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_exceptions.py @@ -0,0 +1,123 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +import httpx + +__all__ = [ + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", +] + + +class GeminiNextGenAPIClientError(Exception): + pass + + +class APIError(GeminiNextGenAPIClientError): + message: str + request: httpx.Request + + body: object | None + """The API response body. + + If the API responded with a valid JSON structure then this property will be the + decoded result. + + If it isn't a valid JSON structure then this will be the raw response. + + If there was no response associated with this error then it will be `None`. + """ + + def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: # noqa: ARG002 + super().__init__(message) + self.request = request + self.message = message + self.body = body + + +class APIResponseValidationError(APIError): + response: httpx.Response + status_code: int + + def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None: + super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body) + self.response = response + self.status_code = response.status_code + + +class APIStatusError(APIError): + """Raised when an API response has a status code of 4xx or 5xx.""" + + response: httpx.Response + status_code: int + + def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None: + super().__init__(message, response.request, body=body) + self.response = response + self.status_code = response.status_code + + +class APIConnectionError(APIError): + def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None: + super().__init__(message, request, body=None) + + +class APITimeoutError(APIConnectionError): + def __init__(self, request: httpx.Request) -> None: + super().__init__(message="Request timed out.", request=request) + + +class BadRequestError(APIStatusError): + status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride] + + +class AuthenticationError(APIStatusError): + status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride] + + +class PermissionDeniedError(APIStatusError): + status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride] + + +class NotFoundError(APIStatusError): + status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride] + + +class ConflictError(APIStatusError): + status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride] + + +class UnprocessableEntityError(APIStatusError): + status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride] + + +class RateLimitError(APIStatusError): + status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride] + + +class InternalServerError(APIStatusError): + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_files.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_files.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ddd9cc5dcb9be0421384987a167485c448c8d2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_files.py @@ -0,0 +1,139 @@ +# 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. +# + +# mypy: ignore-errors +from __future__ import annotations + +import io +import os +import pathlib +from typing import overload +from typing_extensions import TypeGuard + +import anyio + +from ._types import ( + FileTypes, + FileContent, + RequestFiles, + HttpxFileTypes, + Base64FileInput, + HttpxFileContent, + HttpxRequestFiles, +) +from ._utils import is_tuple_t, is_mapping_t, is_sequence_t + + +def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]: + return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + + +def is_file_content(obj: object) -> TypeGuard[FileContent]: + return ( + isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + ) + + +def assert_is_file_content(obj: object, *, key: str | None = None) -> None: + if not is_file_content(obj): + prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`" + raise RuntimeError( + f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead." + ) from None + + +@overload +def to_httpx_files(files: None) -> None: ... + + +@overload +def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... + + +def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: _transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, _transform_file(file)) for key, file in files] + else: + raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +def _transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = pathlib.Path(file) + return (path.name, path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +def read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return pathlib.Path(file).read_bytes() + return file + + +@overload +async def async_to_httpx_files(files: None) -> None: ... + + +@overload +async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... + + +async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: await _async_transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, await _async_transform_file(file)) for key, file in files] + else: + raise TypeError("Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +async def _async_transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = anyio.Path(file) + return (path.name, await path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], await async_read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +async def async_read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return await anyio.Path(file).read_bytes() + + return file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_models.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..f09924cc5d1c10a8328bb02ff287940639d550d1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_models.py @@ -0,0 +1,888 @@ +# 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. +# + +# mypy: ignore-errors +from __future__ import annotations + +import os +import inspect +import weakref +from typing import ( + IO, + TYPE_CHECKING, + Any, + Type, + Union, + Generic, + TypeVar, + Callable, + Iterable, + Optional, + AsyncIterable, + cast, +) +from datetime import date, datetime +from typing_extensions import ( + List, + Unpack, + Literal, + ClassVar, + Protocol, + Required, + ParamSpec, + TypedDict, + TypeGuard, + final, + override, + runtime_checkable, +) + +import pydantic +from pydantic.fields import FieldInfo + +from ._types import ( + Body, + IncEx, + Query, + ModelT, + Headers, + Timeout, + NotGiven, + AnyMapping, + HttpxRequestFiles, +) +from ._utils import ( + PropertyInfo, + is_list, + is_given, + json_safe, + lru_cache, + is_mapping, + parse_date, + coerce_boolean, + parse_datetime, + strip_not_given, + extract_type_arg, + is_annotated_type, + is_type_alias_type, + strip_annotated_type, +) +from ._compat import ( + PYDANTIC_V1, + ConfigDict, + GenericModel as BaseGenericModel, + get_args, + is_union, + parse_obj, + get_origin, + is_literal_type, + get_model_config, + get_model_fields, + field_get_default, +) +from ._constants import RAW_RESPONSE_HEADER + +if TYPE_CHECKING: + from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema + +__all__ = ["BaseModel", "GenericModel"] + +_T = TypeVar("_T") +_BaseModelT = TypeVar("_BaseModelT", bound="BaseModel") + +P = ParamSpec("P") + + +@runtime_checkable +class _ConfigProtocol(Protocol): + allow_population_by_field_name: bool + + +class BaseModel(pydantic.BaseModel): + if PYDANTIC_V1: + + @property + @override + def model_fields_set(self) -> set[str]: + # a forwards-compat shim for pydantic v2 + return self.__fields_set__ # type: ignore + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + extra: Any = pydantic.Extra.allow # type: ignore + else: + model_config: ClassVar[ConfigDict] = ConfigDict( + extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")) + ) + + def to_dict( + self, + *, + mode: Literal["json", "python"] = "python", + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> dict[str, object]: + """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + mode: + If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`. + If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)` + + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value from the output. + exclude_none: Whether to exclude fields that have a value of `None` from the output. + warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2. + """ + return self.model_dump( + mode=mode, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + + def to_json( + self, + *, + indent: int | None = 2, + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> str: + """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation). + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2` + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2. + """ + return self.model_dump_json( + indent=indent, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + + @override + def __str__(self) -> str: + # mypy complains about an invalid self arg + return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc] + + # Override the 'construct' method in a way that supports recursive parsing without validation. + # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836. + @classmethod + @override + def construct( # pyright: ignore[reportIncompatibleMethodOverride] + __cls: Type[ModelT], + _fields_set: set[str] | None = None, + **values: object, + ) -> ModelT: + m = __cls.__new__(__cls) + fields_values: dict[str, object] = {} + + config = get_model_config(__cls) + populate_by_name = ( + config.allow_population_by_field_name + if isinstance(config, _ConfigProtocol) + else config.get("populate_by_name") + ) + + if _fields_set is None: + _fields_set = set() + + model_fields = get_model_fields(__cls) + for name, field in model_fields.items(): + key = field.alias + if key is None or (key not in values and populate_by_name): + key = name + + if key in values: + fields_values[name] = _construct_field(value=values[key], field=field, key=key) + _fields_set.add(name) + else: + fields_values[name] = field_get_default(field) + + extra_field_type = _get_extra_fields_type(__cls) + + _extra = {} + for key, value in values.items(): + if key not in model_fields: + parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value + + if PYDANTIC_V1: + _fields_set.add(key) + fields_values[key] = parsed + else: + _extra[key] = parsed + + object.__setattr__(m, "__dict__", fields_values) + + if PYDANTIC_V1: + # init_private_attributes() does not exist in v2 + m._init_private_attributes() # type: ignore + + # copied from Pydantic v1's `construct()` method + object.__setattr__(m, "__fields_set__", _fields_set) + else: + # these properties are copied from Pydantic's `model_construct()` method + object.__setattr__(m, "__pydantic_private__", None) + object.__setattr__(m, "__pydantic_extra__", _extra) + object.__setattr__(m, "__pydantic_fields_set__", _fields_set) + + return m + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + # because the type signatures are technically different + # although not in practice + model_construct = construct + + if PYDANTIC_V1: + # we define aliases for some of the new pydantic v2 methods so + # that we can just document these methods without having to specify + # a specific pydantic version as some users may not know which + # pydantic version they are currently using + + @override + def model_dump( + self, + *, + mode: Literal["json", "python"] | str = "python", + include: IncEx | None = None, + exclude: IncEx | None = None, + context: Any | None = None, + by_alias: bool | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + exclude_computed_fields: bool = False, + round_trip: bool = False, + warnings: bool | Literal["none", "warn", "error"] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + ) -> dict[str, Any]: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump + + Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + Args: + mode: The mode in which `to_python` should run. + If mode is 'json', the output will only contain JSON serializable types. + If mode is 'python', the output may contain non-JSON-serializable Python objects. + include: A set of fields to include in the output. + exclude: A set of fields to exclude from the output. + context: Additional context to pass to the serializer. + by_alias: Whether to use the field's alias in the dictionary key if defined. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value. + exclude_none: Whether to exclude fields that have a value of `None`. + exclude_computed_fields: Whether to exclude computed fields. + While this can be useful for round-tripping, it is usually recommended to use the dedicated + `round_trip` parameter instead. + round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. + warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + fallback: A function to call when an unknown value is encountered. If not provided, + a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + + Returns: + A dictionary representation of the model. + """ + if mode not in {"json", "python"}: + raise ValueError("mode must be either 'json' or 'python'") + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") + if fallback is not None: + raise ValueError("fallback is only supported in Pydantic v2") + if exclude_computed_fields != False: + raise ValueError("exclude_computed_fields is only supported in Pydantic v2") + dumped = super().dict( # pyright: ignore[reportDeprecated] + include=include, + exclude=exclude, + by_alias=by_alias if by_alias is not None else False, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped + + @override + def model_dump_json( + self, + *, + indent: int | None = None, + ensure_ascii: bool = False, + include: IncEx | None = None, + exclude: IncEx | None = None, + context: Any | None = None, + by_alias: bool | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + exclude_computed_fields: bool = False, + round_trip: bool = False, + warnings: bool | Literal["none", "warn", "error"] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + ) -> str: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json + + Generates a JSON representation of the model using Pydantic's `to_json` method. + + Args: + indent: Indentation to use in the JSON output. If None is passed, the output will be compact. + include: Field(s) to include in the JSON output. Can take either a string or set of strings. + exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings. + by_alias: Whether to serialize using field aliases. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to use serialization/deserialization between JSON and class instance. + warnings: Whether to show any warnings that occurred during serialization. + + Returns: + A JSON string representation of the model. + """ + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") + if fallback is not None: + raise ValueError("fallback is only supported in Pydantic v2") + if ensure_ascii != False: + raise ValueError("ensure_ascii is only supported in Pydantic v2") + if exclude_computed_fields != False: + raise ValueError("exclude_computed_fields is only supported in Pydantic v2") + return super().json( # type: ignore[reportDeprecated] + indent=indent, + include=include, + exclude=exclude, + by_alias=by_alias if by_alias is not None else False, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + +def _construct_field(value: object, field: FieldInfo, key: str) -> object: + if value is None: + return field_get_default(field) + + if PYDANTIC_V1: + type_ = cast(type, field.outer_type_) # type: ignore + else: + type_ = field.annotation # type: ignore + + if type_ is None: + raise RuntimeError(f"Unexpected field type is None for {key}") + + return construct_type(value=value, type_=type_, metadata=getattr(field, "metadata", None)) + + +def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None: + if PYDANTIC_V1: + # TODO + return None + + schema = cls.__pydantic_core_schema__ + if schema["type"] == "model": + fields = schema["schema"] + if fields["type"] == "model-fields": + extras = fields.get("extras_schema") + if extras and "cls" in extras: + # mypy can't narrow the type + return extras["cls"] # type: ignore[no-any-return] + + return None + + +def is_basemodel(type_: type) -> bool: + """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`""" + if is_union(type_): + for variant in get_args(type_): + if is_basemodel(variant): + return True + + return False + + return is_basemodel_type(type_) + + +def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]: + origin = get_origin(type_) or type_ + if not inspect.isclass(origin): + return False + return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) + + +def build( + base_model_cls: Callable[P, _BaseModelT], + *args: P.args, + **kwargs: P.kwargs, +) -> _BaseModelT: + """Construct a BaseModel class without validation. + + This is useful for cases where you need to instantiate a `BaseModel` + from an API response as this provides type-safe params which isn't supported + by helpers like `construct_type()`. + + ```py + build(MyModel, my_field_a="foo", my_field_b=123) + ``` + """ + if args: + raise TypeError( + "Received positional arguments which are not supported; Keyword arguments must be used instead", + ) + + return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs)) + + +def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T: + """Loose coercion to the expected type with construction of nested values. + + Note: the returned value from this function is not guaranteed to match the + given type. + """ + return cast(_T, construct_type(value=value, type_=type_)) + + +def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]] = None) -> object: + """Loose coercion to the expected type with construction of nested values. + + If the given value does not match the expected type then it is returned as-is. + """ + + # store a reference to the original type we were given before we extract any inner + # types so that we can properly resolve forward references in `TypeAliasType` annotations + original_type = None + + # we allow `object` as the input type because otherwise, passing things like + # `Literal['value']` will be reported as a type error by type checkers + type_ = cast("type[object]", type_) + if is_type_alias_type(type_): + original_type = type_ # type: ignore[unreachable] + type_ = type_.__value__ # type: ignore[unreachable] + + # unwrap `Annotated[T, ...]` -> `T` + if metadata is not None and len(metadata) > 0: + meta: tuple[Any, ...] = tuple(metadata) + elif is_annotated_type(type_): + meta = get_args(type_)[1:] + type_ = extract_type_arg(type_, 0) + else: + meta = tuple() + + # we need to use the origin class for any types that are subscripted generics + # e.g. Dict[str, object] + origin = get_origin(type_) or type_ + args = get_args(type_) + + if is_union(origin): + try: + return validate_type(type_=cast("type[object]", original_type or type_), value=value) + except Exception: + pass + + # if the type is a discriminated union then we want to construct the right variant + # in the union, even if the data doesn't match exactly, otherwise we'd break code + # that relies on the constructed class types, e.g. + # + # class FooType: + # kind: Literal['foo'] + # value: str + # + # class BarType: + # kind: Literal['bar'] + # value: int + # + # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then + # we'd end up constructing `FooType` when it should be `BarType`. + discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta) + if discriminator and is_mapping(value): + variant_value = value.get(discriminator.field_alias_from or discriminator.field_name) + if variant_value and isinstance(variant_value, str): + variant_type = discriminator.mapping.get(variant_value) + if variant_type: + return construct_type(type_=variant_type, value=value) + + # if the data is not valid, use the first variant that doesn't fail while deserializing + for variant in args: + try: + return construct_type(value=value, type_=variant) + except Exception: + continue + + raise RuntimeError(f"Could not convert data into a valid instance of {type_}") + + if origin == dict: + if not is_mapping(value): + return value + + _, items_type = get_args(type_) # Dict[_, items_type] + return {key: construct_type(value=item, type_=items_type) for key, item in value.items()} + + if ( + not is_literal_type(type_) + and inspect.isclass(origin) + and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)) + ): + if is_list(value): + return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value] + + if is_mapping(value): + if issubclass(type_, BaseModel): + return type_.construct(**value) # type: ignore[arg-type] + + return cast(Any, type_).construct(**value) + + if origin == list: + if not is_list(value): + return value + + inner_type = args[0] # List[inner_type] + return [construct_type(value=entry, type_=inner_type) for entry in value] + + if origin == float: + if isinstance(value, int): + coerced = float(value) + if coerced != value: + return value + return coerced + + return value + + if type_ == datetime: + try: + return parse_datetime(value) # type: ignore + except Exception: + return value + + if type_ == date: + try: + return parse_date(value) # type: ignore + except Exception: + return value + + return value + + +@runtime_checkable +class CachedDiscriminatorType(Protocol): + __discriminator__: DiscriminatorDetails + + +DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary() + + +class DiscriminatorDetails: + field_name: str + """The name of the discriminator field in the variant class, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] + ``` + + Will result in field_name='type' + """ + + field_alias_from: str | None + """The name of the discriminator field in the API response, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] = Field(alias='type_from_api') + ``` + + Will result in field_alias_from='type_from_api' + """ + + mapping: dict[str, type] + """Mapping of discriminator value to variant type, e.g. + + {'foo': FooVariant, 'bar': BarVariant} + """ + + def __init__( + self, + *, + mapping: dict[str, type], + discriminator_field: str, + discriminator_alias: str | None, + ) -> None: + self.mapping = mapping + self.field_name = discriminator_field + self.field_alias_from = discriminator_alias + + +def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None: + cached = DISCRIMINATOR_CACHE.get(union) + if cached is not None: + return cached + + discriminator_field_name: str | None = None + + for annotation in meta_annotations: + if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None: + discriminator_field_name = annotation.discriminator + break + + if not discriminator_field_name: + return None + + mapping: dict[str, type] = {} + discriminator_alias: str | None = None + + for variant in get_args(union): + variant = strip_annotated_type(variant) + if is_basemodel_type(variant): + if PYDANTIC_V1: + field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + if not field_info: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field_info.alias + + if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): + for entry in get_args(annotation): + if isinstance(entry, str): + mapping[entry] = variant + else: + field = _extract_field_schema_pv2(variant, discriminator_field_name) + if not field: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field.get("serialization_alias") + + field_schema = field["schema"] + + if field_schema["type"] == "literal": + for entry in cast("LiteralSchema", field_schema)["expected"]: + if isinstance(entry, str): + mapping[entry] = variant + + if not mapping: + return None + + details = DiscriminatorDetails( + mapping=mapping, + discriminator_field=discriminator_field_name, + discriminator_alias=discriminator_alias, + ) + DISCRIMINATOR_CACHE.setdefault(union, details) + return details + + +def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None: + schema = model.__pydantic_core_schema__ + if schema["type"] == "definitions": + schema = schema["schema"] + + if schema["type"] != "model": + return None + + schema = cast("ModelSchema", schema) + fields_schema = schema["schema"] + if fields_schema["type"] != "model-fields": + return None + + fields_schema = cast("ModelFieldsSchema", fields_schema) + field = fields_schema["fields"].get(field_name) + if not field: + return None + + return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast] + + +def validate_type(*, type_: type[_T], value: object) -> _T: + """Strict validation that the given value matches the expected type""" + if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel): + return cast(_T, parse_obj(type_, value)) + + return cast(_T, _validate_non_model_type(type_=type_, value=value)) + + +def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None: + """Add a pydantic config for the given type. + + Note: this is a no-op on Pydantic v1. + """ + setattr(typ, "__pydantic_config__", config) # noqa: B010 + + +# our use of subclassing here causes weirdness for type checkers, +# so we just pretend that we don't subclass +if TYPE_CHECKING: + GenericModel = BaseModel +else: + + class GenericModel(BaseGenericModel, BaseModel): + pass + + +if not PYDANTIC_V1: + from pydantic import TypeAdapter as _TypeAdapter + + _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter)) + + if TYPE_CHECKING: + from pydantic import TypeAdapter + else: + TypeAdapter = _CachedTypeAdapter + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + return TypeAdapter(type_).validate_python(value) + +elif not TYPE_CHECKING: # TODO: condition is weird + + class RootModel(GenericModel, Generic[_T]): + """Used as a placeholder to easily convert runtime types to a Pydantic format + to provide validation. + + For example: + ```py + validated = RootModel[int](__root__="5").__root__ + # validated: 5 + ``` + """ + + __root__: _T + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + model = _create_pydantic_model(type_).validate(value) + return cast(_T, model.__root__) + + def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]: + return RootModel[type_] # type: ignore + + +class FinalRequestOptionsInput(TypedDict, total=False): + method: Required[str] + url: Required[str] + params: Query + headers: Headers + max_retries: int + timeout: float | Timeout | None + files: HttpxRequestFiles | None + idempotency_key: str + content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] + json_data: Body + extra_json: AnyMapping + follow_redirects: bool + + +@final +class FinalRequestOptions(pydantic.BaseModel): + method: str + url: str + params: Query = {} + headers: Union[Headers, NotGiven] = NotGiven() + max_retries: Union[int, NotGiven] = NotGiven() + timeout: Union[float, Timeout, None, NotGiven] = NotGiven() + files: Union[HttpxRequestFiles, None] = None + idempotency_key: Union[str, None] = None + post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven() + follow_redirects: Union[bool, None] = None + + content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] = None + # It should be noted that we cannot use `json` here as that would override + # a BaseModel method in an incompatible fashion. + json_data: Union[Body, None] = None + extra_json: Union[AnyMapping, None] = None + + if PYDANTIC_V1: + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + arbitrary_types_allowed: bool = True + else: + model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) + + def get_max_retries(self, max_retries: int) -> int: + if isinstance(self.max_retries, NotGiven): + return max_retries + return self.max_retries + + def _strip_raw_response_header(self) -> None: + if not is_given(self.headers): + return + + if self.headers.get(RAW_RESPONSE_HEADER): + self.headers = {**self.headers} + self.headers.pop(RAW_RESPONSE_HEADER) + + # override the `construct` method so that we can run custom transformations. + # this is necessary as we don't want to do any actual runtime type checking + # (which means we can't use validators) but we do want to ensure that `NotGiven` + # values are not present + # + # type ignore required because we're adding explicit types to `**values` + @classmethod + def construct( # type: ignore + cls, + _fields_set: set[str] | None = None, + **values: Unpack[FinalRequestOptionsInput], + ) -> FinalRequestOptions: + kwargs: dict[str, Any] = { + # we unconditionally call `strip_not_given` on any value + # as it will just ignore any non-mapping types + key: strip_not_given(value) + for key, value in values.items() + } + if PYDANTIC_V1: + return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated] + return super().model_construct(_fields_set, **kwargs) + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + model_construct = construct diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_qs.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_qs.py new file mode 100644 index 0000000000000000000000000000000000000000..64261b4573d171140e6f8203280e196171368fa6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_qs.py @@ -0,0 +1,168 @@ +# 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 Any, List, Tuple, Union, Mapping, TypeVar +from urllib.parse import parse_qs, urlencode +from typing_extensions import Literal, get_args + +from ._types import NotGiven, not_given +from ._utils import flatten + +_T = TypeVar("_T") + + +ArrayFormat = Literal["comma", "repeat", "indices", "brackets"] +NestedFormat = Literal["dots", "brackets"] + +PrimitiveData = Union[str, int, float, bool, None] +# this should be Data = Union[PrimitiveData, "List[Data]", "Tuple[Data]", "Mapping[str, Data]"] +# https://github.com/microsoft/pyright/issues/3555 +Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"] +Params = Mapping[str, Data] + + +class Querystring: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + *, + array_format: ArrayFormat = "repeat", + nested_format: NestedFormat = "brackets", + ) -> None: + self.array_format = array_format + self.nested_format = nested_format + + def parse(self, query: str) -> Mapping[str, object]: + # Note: custom format syntax is not supported yet + return parse_qs(query) + + def stringify( + self, + params: Params, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> str: + return urlencode( + self.stringify_items( + params, + array_format=array_format, + nested_format=nested_format, + ) + ) + + def stringify_items( + self, + params: Params, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> list[tuple[str, str]]: + opts = Options( + qs=self, + array_format=array_format, + nested_format=nested_format, + ) + return flatten([self._stringify_item(key, value, opts) for key, value in params.items()]) + + def _stringify_item( + self, + key: str, + value: Data, + opts: Options, + ) -> list[tuple[str, str]]: + if isinstance(value, Mapping): + items: list[tuple[str, str]] = [] + nested_format = opts.nested_format + for subkey, subvalue in value.items(): + items.extend( + self._stringify_item( + # TODO: error if unknown format + f"{key}.{subkey}" if nested_format == "dots" else f"{key}[{subkey}]", + subvalue, + opts, + ) + ) + return items + + if isinstance(value, (list, tuple)): + array_format = opts.array_format + if array_format == "comma": + return [ + ( + key, + ",".join(self._primitive_value_to_str(item) for item in value if item is not None), + ), + ] + elif array_format == "repeat": + items = [] + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + elif array_format == "indices": + items = [] + for i, item in enumerate(value): + items.extend(self._stringify_item(f"{key}[{i}]", item, opts)) + return items + elif array_format == "brackets": + items = [] + key = key + "[]" + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + else: + raise NotImplementedError( + f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}" + ) + + serialised = self._primitive_value_to_str(value) + if not serialised: + return [] + return [(key, serialised)] + + def _primitive_value_to_str(self, value: PrimitiveData) -> str: + # copied from httpx + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +_qs = Querystring() +parse = _qs.parse +stringify = _qs.stringify +stringify_items = _qs.stringify_items + + +class Options: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + qs: Querystring = _qs, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> None: + self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format + self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_resource.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..4739db925d689377230c08bef236d9712b70f896 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_resource.py @@ -0,0 +1,58 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +import anyio + +if TYPE_CHECKING: + from ._client import GeminiNextGenAPIClient, AsyncGeminiNextGenAPIClient + + +class SyncAPIResource: + _client: GeminiNextGenAPIClient + + def __init__(self, client: GeminiNextGenAPIClient) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + def _sleep(self, seconds: float) -> None: + time.sleep(seconds) + + +class AsyncAPIResource: + _client: AsyncGeminiNextGenAPIClient + + def __init__(self, client: AsyncGeminiNextGenAPIClient) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + async def _sleep(self, seconds: float) -> None: + await anyio.sleep(seconds) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_response.py new file mode 100644 index 0000000000000000000000000000000000000000..12077e04986741907e25b8e0c07b82f2c5a8ea77 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_response.py @@ -0,0 +1,850 @@ +# 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 + +import os +import inspect +import logging +import datetime +import functools +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Union, + Generic, + TypeVar, + Callable, + Iterator, + AsyncIterator, + cast, + overload, +) +from typing_extensions import Awaitable, ParamSpec, override, get_origin + +import anyio +import httpx +import pydantic + +from ._types import NoneType +from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base +from ._models import BaseModel, is_basemodel +from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER +from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type +from ._exceptions import APIResponseValidationError, GeminiNextGenAPIClientError + +if TYPE_CHECKING: + from ._models import FinalRequestOptions + from ._base_client import BaseClient + + +P = ParamSpec("P") +R = TypeVar("R") +_T = TypeVar("_T") +_APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]") +_AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]") + +log: logging.Logger = logging.getLogger(__name__) + + +class BaseAPIResponse(Generic[R]): + _cast_to: type[R] + _client: BaseClient[Any, Any] + _parsed_by_type: dict[type[Any], Any] + _is_sse_stream: bool + _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None + _options: FinalRequestOptions + + http_response: httpx.Response + + retries_taken: int + """The number of retries made. If no retries happened this will be `0`""" + + def __init__( + self, + *, + raw: httpx.Response, + cast_to: type[R], + client: BaseClient[Any, Any], + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + options: FinalRequestOptions, + retries_taken: int = 0, + ) -> None: + self._cast_to = cast_to + self._client = client + self._parsed_by_type = {} + self._is_sse_stream = stream + self._stream_cls = stream_cls + self._options = options + self.http_response = raw + self.retries_taken = retries_taken + + @property + def headers(self) -> httpx.Headers: + return self.http_response.headers + + @property + def http_request(self) -> httpx.Request: + """Returns the httpx Request instance associated with the current response.""" + return self.http_response.request + + @property + def status_code(self) -> int: + return self.http_response.status_code + + @property + def url(self) -> httpx.URL: + """Returns the URL for which the request was made.""" + return self.http_response.url + + @property + def method(self) -> str: + return self.http_request.method + + @property + def http_version(self) -> str: + return self.http_response.http_version + + @property + def elapsed(self) -> datetime.timedelta: + """The time taken for the complete request/response cycle to complete.""" + return self.http_response.elapsed + + @property + def is_closed(self) -> bool: + """Whether or not the response body has been closed. + + If this is False then there is response data that has not been read yet. + You must either fully consume the response body or call `.close()` + before discarding the response to prevent resource leaks. + """ + return self.http_response.is_closed + + @override + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>" + ) + + def _parse(self, *, to: type[_T] | None = None) -> R | _T: + cast_to = to if to is not None else self._cast_to + + # unwrap `TypeAlias('Name', T)` -> `T` + if is_type_alias_type(cast_to): + cast_to = cast_to.__value__ # type: ignore[unreachable] + + # unwrap `Annotated[T, ...]` -> `T` + if cast_to and is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) + + origin = get_origin(cast_to) or cast_to + + if self._is_sse_stream: + if to: + if not is_stream_class_type(to): + raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}") + + return cast( + _T, + to( + cast_to=extract_stream_chunk_type( + to, + failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]", + ), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if self._stream_cls: + return cast( + R, + self._stream_cls( + cast_to=extract_stream_chunk_type(self._stream_cls), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls) + if stream_cls is None: + raise MissingStreamClassError() + + return cast( + R, + stream_cls( + cast_to=cast_to, + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if cast_to is NoneType: + return cast(R, None) + + response = self.http_response + if cast_to == str: + return cast(R, response.text) + + if cast_to == bytes: + return cast(R, response.content) + + if cast_to == int: + return cast(R, int(response.text)) + + if cast_to == float: + return cast(R, float(response.text)) + + if cast_to == bool: + return cast(R, response.text.lower() == "true") + + if origin == APIResponse: + raise RuntimeError("Unexpected state - cast_to is `APIResponse`") + + if inspect.isclass(origin) and issubclass(origin, httpx.Response): + # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response + # and pass that class to our request functions. We cannot change the variance to be either + # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct + # the response class ourselves but that is something that should be supported directly in httpx + # as it would be easy to incorrectly construct the Response object due to the multitude of arguments. + if cast_to != httpx.Response: + raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") + return cast(R, response) + + if ( + inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) + and not issubclass(origin, BaseModel) + and issubclass(origin, pydantic.BaseModel) + ): + raise TypeError( + "Pydantic models must subclass our base model type, e.g. `from google.genai._interactions import BaseModel`" + ) + + if ( + cast_to is not object + and not origin is list + and not origin is dict + and not origin is Union + and not issubclass(origin, BaseModel) + ): + raise RuntimeError( + f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}." + ) + + # split is required to handle cases where additional information is included + # in the response, e.g. application/json; charset=utf-8 + content_type, *_ = response.headers.get("content-type", "*").split(";") + if not content_type.endswith("json"): + if is_basemodel(cast_to): + try: + data = response.json() + except Exception as exc: + log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc) + else: + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + if self._client._strict_response_validation: + raise APIResponseValidationError( + response=response, + message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.", + body=response.text, + ) + + # If the API responds with content that isn't JSON then we just return + # the (decoded) text without performing any parsing so that you can still + # handle the response however you need to. + return response.text # type: ignore + + data = response.json() + + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + +class APIResponse(BaseAPIResponse[R]): + @overload + def parse(self, *, to: type[_T]) -> _T: ... + + @overload + def parse(self) -> R: ... + + def parse(self, *, to: type[_T] | None = None) -> R | _T: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from google.genai._interactions import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `int` + - `float` + - `httpx.Response` + """ + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] + + if not self._is_sse_stream: + self.read() + + parsed = self._parse(to=to) + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed_by_type[cache_key] = parsed + return parsed + + def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return self.http_response.read() + except httpx.StreamConsumed as exc: + # The default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message. + raise StreamAlreadyConsumed() from exc + + def text(self) -> str: + """Read and decode the response content into a string.""" + self.read() + return self.http_response.text + + def json(self) -> object: + """Read and decode the JSON response content.""" + self.read() + return self.http_response.json() + + def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.http_response.close() + + def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + for chunk in self.http_response.iter_bytes(chunk_size): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> Iterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + for chunk in self.http_response.iter_text(chunk_size): + yield chunk + + def iter_lines(self) -> Iterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + for chunk in self.http_response.iter_lines(): + yield chunk + + +class AsyncAPIResponse(BaseAPIResponse[R]): + @overload + async def parse(self, *, to: type[_T]) -> _T: ... + + @overload + async def parse(self) -> R: ... + + async def parse(self, *, to: type[_T] | None = None) -> R | _T: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from google.genai._interactions import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `httpx.Response` + """ + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] + + if not self._is_sse_stream: + await self.read() + + parsed = self._parse(to=to) + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed_by_type[cache_key] = parsed + return parsed + + async def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return await self.http_response.aread() + except httpx.StreamConsumed as exc: + # the default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message + raise StreamAlreadyConsumed() from exc + + async def text(self) -> str: + """Read and decode the response content into a string.""" + await self.read() + return self.http_response.text + + async def json(self) -> object: + """Read and decode the JSON response content.""" + await self.read() + return self.http_response.json() + + async def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.http_response.aclose() + + async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + async for chunk in self.http_response.aiter_bytes(chunk_size): + yield chunk + + async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + async for chunk in self.http_response.aiter_text(chunk_size): + yield chunk + + async def iter_lines(self) -> AsyncIterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + async for chunk in self.http_response.aiter_lines(): + yield chunk + + +class BinaryAPIResponse(APIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(): + f.write(data) + + +class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + async def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(): + await f.write(data) + + +class StreamedBinaryAPIResponse(APIResponse[bytes]): + def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(chunk_size): + f.write(data) + + +class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]): + async def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(chunk_size): + await f.write(data) + + +class MissingStreamClassError(TypeError): + def __init__(self) -> None: + super().__init__( + "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `google.genai._interactions._streaming` for reference", + ) + + +class StreamAlreadyConsumed(GeminiNextGenAPIClientError): + """ + Attempted to read or stream content, but the content has already + been streamed. + + This can happen if you use a method like `.iter_lines()` and then attempt + to read th entire response body afterwards, e.g. + + ```py + response = await client.post(...) + async for line in response.iter_lines(): + ... # do something with `line` + + content = await response.read() + # ^ error + ``` + + If you want this behaviour you'll need to either manually accumulate the response + content or call `await response.read()` before iterating over the stream. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. " + "This could be due to attempting to stream the response " + "content more than once." + "\n\n" + "You can fix this by manually accumulating the response content while streaming " + "or by calling `.read()` before starting to stream." + ) + super().__init__(message) + + +class ResponseContextManager(Generic[_APIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, request_func: Callable[[], _APIResponseT]) -> None: + self._request_func = request_func + self.__response: _APIResponseT | None = None + + def __enter__(self) -> _APIResponseT: + self.__response = self._request_func() + return self.__response + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + self.__response.close() + + +class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None: + self._api_request = api_request + self.__response: _AsyncAPIResponseT | None = None + + async def __aenter__(self) -> _AsyncAPIResponseT: + self.__response = await self._api_request + return self.__response + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + await self.__response.close() + + +def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request)) + + return wrapped + + +def async_to_streamed_response_wrapper( + func: Callable[P, Awaitable[R]], +) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request)) + + return wrapped + + +def to_custom_streamed_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, ResponseContextManager[_APIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request)) + + return wrapped + + +def async_to_custom_streamed_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request)) + + return wrapped + + +def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + + kwargs["extra_headers"] = extra_headers + + return cast(APIResponse[R], func(*args, **kwargs)) + + return wrapped + + +def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + + kwargs["extra_headers"] = extra_headers + + return cast(AsyncAPIResponse[R], await func(*args, **kwargs)) + + return wrapped + + +def to_custom_raw_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, _APIResponseT]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(_APIResponseT, func(*args, **kwargs)) + + return wrapped + + +def async_to_custom_raw_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, Awaitable[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs)) + + return wrapped + + +def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type: + """Given a type like `APIResponse[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyResponse(APIResponse[bytes]): + ... + + extract_response_type(MyResponse) -> bytes + ``` + """ + return extract_type_var_from_base( + typ, + generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)), + index=0, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_streaming.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..4888afe857145623ac69ce3e0cd1429c0aff1d21 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_streaming.py @@ -0,0 +1,359 @@ +# 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. +# + +# Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py +from __future__ import annotations + +import json +import inspect +from types import TracebackType +from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast +from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable + +import httpx + +from ._utils import extract_type_var_from_base + +if TYPE_CHECKING: + from ._client import GeminiNextGenAPIClient, AsyncGeminiNextGenAPIClient + from ._models import FinalRequestOptions + + +_T = TypeVar("_T") + + +class Stream(Generic[_T]): + """Provides the core interface to iterate over a synchronous stream response.""" + + response: httpx.Response + _options: Optional[FinalRequestOptions] = None + _decoder: SSEBytesDecoder + + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: GeminiNextGenAPIClient, + options: Optional[FinalRequestOptions] = None, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._options = options + self._decoder = client._make_sse_decoder() + self._iterator = self.__stream__() + + def __next__(self) -> _T: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[_T]: + for item in self._iterator: + yield item + + def _iter_events(self) -> Iterator[ServerSentEvent]: + yield from self._decoder.iter_bytes(self.response.iter_bytes()) + + def __stream__(self) -> Iterator[_T]: + cast_to = cast(Any, self._cast_to) + response = self.response + process_data = self._client._process_response_data + iterator = self._iter_events() + + try: + for sse in iterator: + if sse.data.startswith("[DONE]"): + break + + yield process_data(data=sse.json(), cast_to=cast_to, response=response) + finally: + # Ensure the response is closed even if the consumer doesn't read all data + response.close() + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.response.close() + + +class AsyncStream(Generic[_T]): + """Provides the core interface to iterate over an asynchronous stream response.""" + + response: httpx.Response + _options: Optional[FinalRequestOptions] = None + _decoder: SSEDecoder | SSEBytesDecoder + + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: AsyncGeminiNextGenAPIClient, + options: Optional[FinalRequestOptions] = None, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._options = options + self._decoder = client._make_sse_decoder() + self._iterator = self.__stream__() + + async def __anext__(self) -> _T: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[_T]: + async for item in self._iterator: + yield item + + async def _iter_events(self) -> AsyncIterator[ServerSentEvent]: + async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()): + yield sse + + async def __stream__(self) -> AsyncIterator[_T]: + cast_to = cast(Any, self._cast_to) + response = self.response + process_data = self._client._process_response_data + iterator = self._iter_events() + + try: + async for sse in iterator: + if sse.data.startswith("[DONE]"): + break + + yield process_data(data=sse.json(), cast_to=cast_to, response=response) + finally: + # Ensure the response is closed even if the consumer doesn't read all data + await response.aclose() + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.response.aclose() + + +class ServerSentEvent: + def __init__( + self, + *, + event: str | None = None, + data: str | None = None, + id: str | None = None, + retry: int | None = None, + ) -> None: + if data is None: + data = "" + + self._id = id + self._data = data + self._event = event or None + self._retry = retry + + @property + def event(self) -> str | None: + return self._event + + @property + def id(self) -> str | None: + return self._id + + @property + def retry(self) -> int | None: + return self._retry + + @property + def data(self) -> str: + return self._data + + def json(self) -> Any: + return json.loads(self.data) + + @override + def __repr__(self) -> str: + return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})" + + +class SSEDecoder: + _data: list[str] + _event: str | None + _retry: int | None + _last_event_id: str | None + + def __init__(self) -> None: + self._event = None + self._data = [] + self._last_event_id = None + self._retry = None + + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + for chunk in self._iter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data + + async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + async for chunk in self._aiter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + async for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data + + def decode(self, line: str) -> ServerSentEvent | None: + # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501 + + if not line: + if not self._event and not self._data and not self._last_event_id and self._retry is None: + return None + + sse = ServerSentEvent( + event=self._event, + data="\n".join(self._data), + id=self._last_event_id, + retry=self._retry, + ) + + # NOTE: as per the SSE spec, do not reset last_event_id. + self._event = None + self._data = [] + self._retry = None + + return sse + + if line.startswith(":"): + return None + + fieldname, _, value = line.partition(":") + + if value.startswith(" "): + value = value[1:] + + if fieldname == "event": + self._event = value + elif fieldname == "data": + self._data.append(value) + elif fieldname == "id": + if "\0" in value: + pass + else: + self._last_event_id = value + elif fieldname == "retry": + try: + self._retry = int(value) + except (TypeError, ValueError): + pass + else: + pass # Field is ignored. + + return None + + +@runtime_checkable +class SSEBytesDecoder(Protocol): + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + +def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]: + """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`""" + origin = get_origin(typ) or typ + return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream)) + + +def extract_stream_chunk_type( + stream_cls: type, + *, + failure_message: str | None = None, +) -> type: + """Given a type like `Stream[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyStream(Stream[bytes]): + ... + + extract_stream_chunk_type(MyStream) -> bytes + ``` + """ + from ._base_client import Stream, AsyncStream + + return extract_type_var_from_base( + stream_cls, + index=0, + generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), + failure_message=failure_message, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_types.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c759d09cf04324543933ec40f2b1265f73c9bd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_types.py @@ -0,0 +1,285 @@ +# 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 os import PathLike +from typing import ( + IO, + TYPE_CHECKING, + Any, + Dict, + List, + Type, + Tuple, + Union, + Mapping, + TypeVar, + Callable, + Iterable, + Iterator, + Optional, + Sequence, + AsyncIterable, +) +from typing_extensions import ( + Set, + Literal, + Protocol, + TypeAlias, + TypedDict, + SupportsIndex, + overload, + override, + runtime_checkable, +) + +import httpx +import pydantic +from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport + +if TYPE_CHECKING: + from ._models import BaseModel + from ._response import APIResponse, AsyncAPIResponse + +Transport = BaseTransport +AsyncTransport = AsyncBaseTransport +Query = Mapping[str, object] +Body = object +AnyMapping = Mapping[str, object] +ModelT = TypeVar("ModelT", bound=pydantic.BaseModel) +_T = TypeVar("_T") + + +# Approximates httpx internal ProxiesTypes and RequestFiles types +# while adding support for `PathLike` instances +ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]] +ProxiesTypes = Union[str, Proxy, ProxiesDict] +if TYPE_CHECKING: + Base64FileInput = Union[IO[bytes], PathLike[str]] + FileContent = Union[IO[bytes], bytes, PathLike[str]] +else: + Base64FileInput = Union[IO[bytes], PathLike] + FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8. + + +# Used for sending raw binary data / streaming data in request bodies +# e.g. for file uploads without multipart encoding +BinaryTypes = Union[bytes, bytearray, IO[bytes], Iterable[bytes]] +AsyncBinaryTypes = Union[bytes, bytearray, IO[bytes], AsyncIterable[bytes]] + +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +# duplicate of the above but without our custom file support +HttpxFileContent = Union[IO[bytes], bytes] +HttpxFileTypes = Union[ + # file (or bytes) + HttpxFileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], HttpxFileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], HttpxFileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]], +] +HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]] + +# Workaround to support (cast_to: Type[ResponseT]) -> ResponseT +# where ResponseT includes `None`. In order to support directly +# passing `None`, overloads would have to be defined for every +# method that uses `ResponseT` which would lead to an unacceptable +# amount of code duplication and make it unreadable. See _base_client.py +# for example usage. +# +# This unfortunately means that you will either have +# to import this type and pass it explicitly: +# +# from google.genai._interactions import NoneType +# client.get('/foo', cast_to=NoneType) +# +# or build it yourself: +# +# client.get('/foo', cast_to=type(None)) +if TYPE_CHECKING: + NoneType: Type[None] +else: + NoneType = type(None) + + +class RequestOptions(TypedDict, total=False): + headers: Headers + max_retries: int + timeout: float | Timeout | None + params: Query + extra_json: AnyMapping + idempotency_key: str + follow_redirects: bool + + +# Sentinel class used until PEP 0661 is accepted +class NotGiven: + """ + For parameters with a meaningful None value, we need to distinguish between + the user explicitly passing None, and the user not passing the parameter at + all. + + User code shouldn't need to use not_given directly. + + For example: + + ```py + def create(timeout: Timeout | None | NotGiven = not_given): ... + + + create(timeout=1) # 1s timeout + create(timeout=None) # No timeout + create() # Default timeout behavior + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + @override + def __repr__(self) -> str: + return "NOT_GIVEN" + + +not_given = NotGiven() +# for backwards compatibility: +NOT_GIVEN = NotGiven() + + +class Omit: + """ + To explicitly omit something from being sent in a request, use `omit`. + + ```py + # as the default `Content-Type` header is `application/json` that will be sent + client.post("/upload/files", files={"file": b"my raw file content"}) + + # you can't explicitly override the header as it has to be dynamically generated + # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983' + client.post(..., headers={"Content-Type": "multipart/form-data"}) + + # instead you can remove the default `application/json` header by passing omit + client.post(..., headers={"Content-Type": omit}) + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + +omit = Omit() + + +@runtime_checkable +class ModelBuilderProtocol(Protocol): + @classmethod + def build( + cls: type[_T], + *, + response: Response, + data: object, + ) -> _T: ... + + +Headers = Mapping[str, Union[str, Omit]] + + +class HeadersLikeProtocol(Protocol): + def get(self, __key: str) -> str | None: ... + + +HeadersLike = Union[Headers, HeadersLikeProtocol] + +ResponseT = TypeVar( + "ResponseT", + bound=Union[ + object, + str, + None, + "BaseModel", + List[Any], + Dict[str, Any], + Response, + ModelBuilderProtocol, + "APIResponse[Any]", + "AsyncAPIResponse[Any]", + ], +) + +StrBytesIntFloat = Union[str, bytes, int, float] + +# Note: copied from Pydantic +# https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79 +IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]] + +PostParser = Callable[[Any], Any] + + +@runtime_checkable +class InheritsGeneric(Protocol): + """Represents a type that has inherited from `Generic` + + The `__orig_bases__` property can be used to determine the resolved + type variable for a given base class. + """ + + __orig_bases__: tuple[_GenericAlias] + + +class _GenericAlias(Protocol): + __origin__: type[object] + + +class HttpxSendArgs(TypedDict, total=False): + auth: httpx.Auth + follow_redirects: bool + + +_T_co = TypeVar("_T_co", covariant=True) + + +if TYPE_CHECKING: + # This works because str.__contains__ does not accept object (either in typeshed or at runtime) + # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285 + # + # Note: index() and count() methods are intentionally omitted to allow pyright to properly + # infer TypedDict types when dict literals are used in lists assigned to SequenceNotStr. + class SequenceNotStr(Protocol[_T_co]): + @overload + def __getitem__(self, index: SupportsIndex, /) -> _T_co: ... + @overload + def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ... + def __contains__(self, value: object, /) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... +else: + # just point this to a normal `Sequence` at runtime to avoid having to special case + # deserializing our custom sequence type + SequenceNotStr = Sequence diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a263e1fa36da862b5817b5a64f54d493cdd42604 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__init__.py @@ -0,0 +1,80 @@ +# 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 ._path import path_template as path_template +from ._sync import asyncify as asyncify +from ._proxy import LazyProxy as LazyProxy +from ._utils import ( + flatten as flatten, + is_dict as is_dict, + is_list as is_list, + is_given as is_given, + is_tuple as is_tuple, + json_safe as json_safe, + lru_cache as lru_cache, + is_mapping as is_mapping, + is_tuple_t as is_tuple_t, + is_iterable as is_iterable, + is_sequence as is_sequence, + coerce_float as coerce_float, + is_mapping_t as is_mapping_t, + removeprefix as removeprefix, + removesuffix as removesuffix, + extract_files as extract_files, + is_sequence_t as is_sequence_t, + required_args as required_args, + coerce_boolean as coerce_boolean, + coerce_integer as coerce_integer, + file_from_path as file_from_path, + strip_not_given as strip_not_given, + deepcopy_minimal as deepcopy_minimal, + get_async_library as get_async_library, + maybe_coerce_float as maybe_coerce_float, + get_required_header as get_required_header, + maybe_coerce_boolean as maybe_coerce_boolean, + maybe_coerce_integer as maybe_coerce_integer, +) +from ._compat import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, +) +from ._typing import ( + is_list_type as is_list_type, + is_union_type as is_union_type, + extract_type_arg as extract_type_arg, + is_iterable_type as is_iterable_type, + is_required_type as is_required_type, + is_sequence_type as is_sequence_type, + is_annotated_type as is_annotated_type, + is_type_alias_type as is_type_alias_type, + strip_annotated_type as strip_annotated_type, + extract_type_var_from_base as extract_type_var_from_base, +) +from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator +from ._transform import ( + PropertyInfo as PropertyInfo, + transform as transform, + async_transform as async_transform, + maybe_transform as maybe_transform, + async_maybe_transform as async_maybe_transform, +) +from ._reflection import ( + function_has_argument as function_has_argument, + assert_signatures_in_sync as assert_signatures_in_sync, +) +from ._datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93a21e6a8a5c118d5e1506e39398b114eed309a0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_compat.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f2234cee6316c943fa731def377be711e1536af Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_compat.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_datetime_parse.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_datetime_parse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfb57142c196ca9803c8f54dddc104da8c87b4d0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_datetime_parse.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_json.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_json.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..847560b00cb2daadfc193cb11664590469fccd1a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_json.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_logs.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_logs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..431e68cd419b14697d5e087729fd46929b3c481e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_logs.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_path.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_path.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be1ebb656160caaadcb033dedbd43eaa26067daf Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_path.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_proxy.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_proxy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ac6ea284c9830701b751662bbf6081749356800 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_proxy.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_reflection.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_reflection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00268ebf2ccf05d65a16ef8d0f5b8866ec9e6da5 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_reflection.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_resources_proxy.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_resources_proxy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6384c20521c55a9043c416db92a6f053a3c7442 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_resources_proxy.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_streams.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..365a372087dc1358c93db715289d8d858b830fc3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_streams.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_sync.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_sync.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8c630bffffae64485a93e0fc23f587468f3b894 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_sync.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_transform.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fde5677a05dc95e45c186f5532628c2000a5bbe Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_transform.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_typing.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55b57c4e04731164a8822318b3441d716b4a5d19 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_typing.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_utils.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c114d4051b5a5e706d926c0fc31625c871b9ca1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/__pycache__/_utils.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_compat.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2386df6c2706d2c514a64c159f929fb95b1bab --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_compat.py @@ -0,0 +1,61 @@ +# 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. +# + +# mypy: ignore-errors +from __future__ import annotations + +import sys +import typing_extensions +from typing import Any, Type, Union, Literal, Optional +from datetime import date, datetime +from typing_extensions import get_args as _get_args, get_origin as _get_origin + +from .._types import StrBytesIntFloat +from ._datetime_parse import parse_date as _parse_date, parse_datetime as _parse_datetime + +_LITERAL_TYPES = {Literal, typing_extensions.Literal} + + +def get_args(tp: type[Any]) -> tuple[Any, ...]: + return _get_args(tp) + + +def get_origin(tp: type[Any]) -> type[Any] | None: + return _get_origin(tp) + + +def is_union(tp: Optional[Type[Any]]) -> bool: + if sys.version_info < (3, 10): + return tp is Union # type: ignore[comparison-overlap] + else: + import types + + return tp is Union or tp is types.UnionType # type: ignore[comparison-overlap] + + +def is_typeddict(tp: Type[Any]) -> bool: + return typing_extensions.is_typeddict(tp) + + +def is_literal_type(tp: Type[Any]) -> bool: + return get_origin(tp) in _LITERAL_TYPES + + +def parse_date(value: Union[date, StrBytesIntFloat]) -> date: + return _parse_date(value) + + +def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: + return _parse_datetime(value) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_datetime_parse.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_datetime_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..3630bda2dc4b9dabfd88f10b5ac742dec35f5e9b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_datetime_parse.py @@ -0,0 +1,151 @@ +# 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. +# + +""" +This file contains code from https://github.com/pydantic/pydantic/blob/main/pydantic/v1/datetime_parse.py +without the Pydantic v1 specific errors. +""" + +from __future__ import annotations + +import re +from typing import Dict, Union, Optional +from datetime import date, datetime, timezone, timedelta + +from .._types import StrBytesIntFloat + +date_expr = r"(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})" +time_expr = ( + r"(?P\d{1,2}):(?P\d{1,2})" + r"(?::(?P\d{1,2})(?:\.(?P\d{1,6})\d{0,6})?)?" + r"(?PZ|[+-]\d{2}(?::?\d{2})?)?$" +) + +date_re = re.compile(f"{date_expr}$") +datetime_re = re.compile(f"{date_expr}[T ]{time_expr}") + + +EPOCH = datetime(1970, 1, 1) +# if greater than this, the number is in ms, if less than or equal it's in seconds +# (in seconds this is 11th October 2603, in ms it's 20th August 1970) +MS_WATERSHED = int(2e10) +# slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9 +MAX_NUMBER = int(3e20) + + +def _get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[None, int, float]: + if isinstance(value, (int, float)): + return value + try: + return float(value) + except ValueError: + return None + except TypeError: + raise TypeError(f"invalid type; expected {native_expected_type}, string, bytes, int or float") from None + + +def _from_unix_seconds(seconds: Union[int, float]) -> datetime: + if seconds > MAX_NUMBER: + return datetime.max + elif seconds < -MAX_NUMBER: + return datetime.min + + while abs(seconds) > MS_WATERSHED: + seconds /= 1000 + dt = EPOCH + timedelta(seconds=seconds) + return dt.replace(tzinfo=timezone.utc) + + +def _parse_timezone(value: Optional[str]) -> Union[None, int, timezone]: + if value == "Z": + return timezone.utc + elif value is not None: + offset_mins = int(value[-2:]) if len(value) > 3 else 0 + offset = 60 * int(value[1:3]) + offset_mins + if value[0] == "-": + offset = -offset + return timezone(timedelta(minutes=offset)) + else: + return None + + +def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: + """ + Parse a datetime/int/float/string and return a datetime.datetime. + + This function supports time zone offsets. When the input contains one, + the output uses a timezone with a fixed offset from UTC. + + Raise ValueError if the input is well formatted but not a valid datetime. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, datetime): + return value + + number = _get_numeric(value, "datetime") + if number is not None: + return _from_unix_seconds(number) + + if isinstance(value, bytes): + value = value.decode() + + assert not isinstance(value, (float, int)) + + match = datetime_re.match(value) + if match is None: + raise ValueError("invalid datetime format") + + kw = match.groupdict() + if kw["microsecond"]: + kw["microsecond"] = kw["microsecond"].ljust(6, "0") + + tzinfo = _parse_timezone(kw.pop("tzinfo")) + kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} + kw_["tzinfo"] = tzinfo + + return datetime(**kw_) # type: ignore + + +def parse_date(value: Union[date, StrBytesIntFloat]) -> date: + """ + Parse a date/int/float/string and return a datetime.date. + + Raise ValueError if the input is well formatted but not a valid date. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, date): + if isinstance(value, datetime): + return value.date() + else: + return value + + number = _get_numeric(value, "date") + if number is not None: + return _from_unix_seconds(number).date() + + if isinstance(value, bytes): + value = value.decode() + + assert not isinstance(value, (float, int)) + match = date_re.match(value) + if match is None: + raise ValueError("invalid date format") + + kw = {k: int(v) for k, v in match.groupdict().items()} + + try: + return date(**kw) + except ValueError: + raise ValueError("invalid date format") from None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_json.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_json.py new file mode 100644 index 0000000000000000000000000000000000000000..d54cafcc31da7c09310833eee09b1bf7c84a9c02 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_json.py @@ -0,0 +1,50 @@ +# 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 +from typing import Any +from datetime import datetime +from typing_extensions import override + +import pydantic + +from .._compat import model_dump + + +def openapi_dumps(obj: Any) -> bytes: + """ + Serialize an object to UTF-8 encoded JSON bytes. + + Extends the standard json.dumps with support for additional types + commonly used in the SDK, such as `datetime`, `pydantic.BaseModel`, etc. + """ + return json.dumps( + obj, + cls=_CustomEncoder, + # Uses the same defaults as httpx's JSON serialization + ensure_ascii=False, + separators=(",", ":"), + allow_nan=False, + ).encode() + + +class _CustomEncoder(json.JSONEncoder): + @override + def default(self, o: Any) -> Any: + if isinstance(o, datetime): + return o.isoformat() + if isinstance(o, pydantic.BaseModel): + return model_dump(o, exclude_unset=True, mode="json", by_alias=True) + return super().default(o) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_logs.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..a16f723383f413004628d75168bed6a6d60b69ab --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_logs.py @@ -0,0 +1,40 @@ +# 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 os +import logging + +logger: logging.Logger = logging.getLogger("google.genai._interactions") +httpx_logger: logging.Logger = logging.getLogger("httpx") + + +def _basic_config() -> None: + # e.g. [2023-10-05 14:12:26 - google.genai._interactions._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK" + logging.basicConfig( + format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + +def setup_logging() -> None: + env = os.environ.get("GEMINI_NEXT_GEN_API_LOG") + if env == "debug": + _basic_config() + logger.setLevel(logging.DEBUG) + httpx_logger.setLevel(logging.DEBUG) + elif env == "info": + _basic_config() + logger.setLevel(logging.INFO) + httpx_logger.setLevel(logging.INFO) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_path.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..5a8171b101dc25eb05bd8291831be6520f37d328 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_path.py @@ -0,0 +1,142 @@ +# 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 + +import re +from typing import ( + Any, + Mapping, + Callable, +) +from urllib.parse import quote + +# Matches '.' or '..' where each dot is either literal or percent-encoded (%2e / %2E). +_DOT_SEGMENT_RE = re.compile(r"^(?:\.|%2[eE]){1,2}$") + +_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}") + + +def _quote_path_segment_part(value: str) -> str: + """Percent-encode `value` for use in a URI path segment. + + Considers characters not in `pchar` set from RFC 3986 §3.3 to be unsafe. + https://datatracker.ietf.org/doc/html/rfc3986#section-3.3 + """ + # quote() already treats unreserved characters (letters, digits, and -._~) + # as safe, so we only need to add sub-delims, ':', and '@'. + # Notably, unlike the default `safe` for quote(), / is unsafe and must be quoted. + return quote(value, safe="!$&'()*+,;=:@") + + +def _quote_query_part(value: str) -> str: + """Percent-encode `value` for use in a URI query string. + + Considers &, = and characters not in `query` set from RFC 3986 §3.4 to be unsafe. + https://datatracker.ietf.org/doc/html/rfc3986#section-3.4 + """ + return quote(value, safe="!$'()*+,;:@/?") + + +def _quote_fragment_part(value: str) -> str: + """Percent-encode `value` for use in a URI fragment. + + Considers characters not in `fragment` set from RFC 3986 §3.5 to be unsafe. + https://datatracker.ietf.org/doc/html/rfc3986#section-3.5 + """ + return quote(value, safe="!$&'()*+,;=:@/?") + + +def _interpolate( + template: str, + values: Mapping[str, Any], + quoter: Callable[[str], str], +) -> str: + """Replace {name} placeholders in `template`, quoting each value with `quoter`. + + Placeholder names are looked up in `values`. + + Raises: + KeyError: If a placeholder is not found in `values`. + """ + # re.split with a capturing group returns alternating + # [text, name, text, name, ..., text] elements. + parts = _PLACEHOLDER_RE.split(template) + + for i in range(1, len(parts), 2): + name = parts[i] + if name not in values: + raise KeyError(f"a value for placeholder {{{name}}} was not provided") + val = values[name] + if val is None: + parts[i] = "null" + elif isinstance(val, bool): + parts[i] = "true" if val else "false" + else: + parts[i] = quoter(str(values[name])) + + return "".join(parts) + + +def path_template(template: str, /, **kwargs: Any) -> str: + """Interpolate {name} placeholders in `template` from keyword arguments. + + Args: + template: The template string containing {name} placeholders. + **kwargs: Keyword arguments to interpolate into the template. + + Returns: + The template with placeholders interpolated and percent-encoded. + + Safe characters for percent-encoding are dependent on the URI component. + Placeholders in path and fragment portions are percent-encoded where the `segment` + and `fragment` sets from RFC 3986 respectively are considered safe. + Placeholders in the query portion are percent-encoded where the `query` set from + RFC 3986 §3.3 is considered safe except for = and & characters. + + Raises: + KeyError: If a placeholder is not found in `kwargs`. + ValueError: If resulting path contains /./ or /../ segments (including percent-encoded dot-segments). + """ + # Split the template into path, query, and fragment portions. + fragment_template: str | None = None + query_template: str | None = None + + rest = template + if "#" in rest: + rest, fragment_template = rest.split("#", 1) + if "?" in rest: + rest, query_template = rest.split("?", 1) + path_template = rest + + # Interpolate each portion with the appropriate quoting rules. + path_result = _interpolate(path_template, kwargs, _quote_path_segment_part) + + # Reject dot-segments (. and ..) in the final assembled path. The check + # runs after interpolation so that adjacent placeholders or a mix of static + # text and placeholders that together form a dot-segment are caught. + # Also reject percent-encoded dot-segments to protect against incorrectly + # implemented normalization in servers/proxies. + for segment in path_result.split("/"): + if _DOT_SEGMENT_RE.match(segment): + raise ValueError(f"Constructed path {path_result!r} contains dot-segment {segment!r} which is not allowed") + + result = path_result + if query_template is not None: + result += "?" + _interpolate(query_template, kwargs, _quote_query_part) + if fragment_template is not None: + result += "#" + _interpolate(fragment_template, kwargs, _quote_fragment_part) + + return result diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_proxy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..b667fa2067f93b130388e6ffb8255314daf6c701 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_proxy.py @@ -0,0 +1,80 @@ +# 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 abc import ABC, abstractmethod +from typing import Generic, TypeVar, Iterable, cast +from typing_extensions import override + +T = TypeVar("T") + + +class LazyProxy(Generic[T], ABC): + """Implements data methods to pretend that an instance is another instance. + + This includes forwarding attribute access and other methods. + """ + + # Note: we have to special case proxies that themselves return proxies + # to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz` + + def __getattr__(self, attr: str) -> object: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied # pyright: ignore + return getattr(proxied, attr) + + @override + def __repr__(self) -> str: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied.__class__.__name__ + return repr(self.__get_proxied__()) + + @override + def __str__(self) -> str: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied.__class__.__name__ + return str(proxied) + + @override + def __dir__(self) -> Iterable[str]: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return [] + return proxied.__dir__() + + @property # type: ignore + @override + def __class__(self) -> type: # pyright: ignore + try: + proxied = self.__get_proxied__() + except Exception: + return type(self) + if issubclass(type(proxied), LazyProxy): + return type(proxied) + return proxied.__class__ + + def __get_proxied__(self) -> T: + return self.__load__() + + def __as_proxied__(self) -> T: + """Helper method that returns the current proxy, typed as the loaded object""" + return cast(T, self) + + @abstractmethod + def __load__(self) -> T: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_reflection.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..4b96a00174e979ffc23e3a8cb401cbbf565267a6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_reflection.py @@ -0,0 +1,57 @@ +# 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 + +import inspect +from typing import Any, Callable + + +def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool: + """Returns whether or not the given function has a specific parameter""" + sig = inspect.signature(func) + return arg_name in sig.parameters + + +def assert_signatures_in_sync( + source_func: Callable[..., Any], + check_func: Callable[..., Any], + *, + exclude_params: set[str] = set(), +) -> None: + """Ensure that the signature of the second function matches the first.""" + + check_sig = inspect.signature(check_func) + source_sig = inspect.signature(source_func) + + errors: list[str] = [] + + for name, source_param in source_sig.parameters.items(): + if name in exclude_params: + continue + + custom_param = check_sig.parameters.get(name) + if not custom_param: + errors.append(f"the `{name}` param is missing") + continue + + if custom_param.annotation != source_param.annotation: + errors.append( + f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}" + ) + continue + + if errors: + raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_resources_proxy.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_resources_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..324e75b8f8e6c9e36f564454dad7eca3c297bd69 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_resources_proxy.py @@ -0,0 +1,39 @@ +# 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 Any +from typing_extensions import override + +from ._proxy import LazyProxy + + +class ResourcesProxy(LazyProxy[Any]): + """A proxy for the `google.genai._interactions.resources` module. + + This is used so that we can lazily import `google.genai._interactions.resources` only when + needed *and* so that users can just import `google.genai._interactions` and reference `google.genai._interactions.resources` + """ + + @override + def __load__(self) -> Any: + import importlib + + mod = importlib.import_module("google.genai._interactions.resources") + return mod + + +resources = ResourcesProxy().__as_proxied__() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_streams.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..c17a2dee5d0e6972888b249e0173c3a7b8367e33 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_streams.py @@ -0,0 +1,27 @@ +# 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 +from typing_extensions import Iterator, AsyncIterator + + +def consume_sync_iterator(iterator: Iterator[Any]) -> None: + for _ in iterator: + ... + + +async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None: + async for _ in iterator: + ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_sync.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..bc95bf30d57308a17c8364740c14837b7f410ffd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_sync.py @@ -0,0 +1,73 @@ +# 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 + +import asyncio +import functools +from typing import TypeVar, Callable, Awaitable +from typing_extensions import ParamSpec + +import anyio +import sniffio +import anyio.to_thread + +T_Retval = TypeVar("T_Retval") +T_ParamSpec = ParamSpec("T_ParamSpec") + + +async def to_thread( + func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs +) -> T_Retval: + if sniffio.current_async_library() == "asyncio": + return await asyncio.to_thread(func, *args, **kwargs) + + return await anyio.to_thread.run_sync( + functools.partial(func, *args, **kwargs), + ) + + +# inspired by `asyncer`, https://github.com/tiangolo/asyncer +def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: + """ + Take a blocking function and create an async one that receives the same + positional and keyword arguments. + + Usage: + + ```python + def blocking_func(arg1, arg2, kwarg1=None): + # blocking code + return result + + + result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1) + ``` + + ## Arguments + + `function`: a blocking regular callable (e.g. a function) + + ## Return + + An async function that takes the same positional and keyword arguments as the + original one, that when called runs the same original function in a thread worker + and returns the result. + """ + + async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: + return await to_thread(function, *args, **kwargs) + + return wrapper diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_transform.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..bb7db1865426f180612a3941e17d7562569f77c0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_transform.py @@ -0,0 +1,472 @@ +# 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 + +import io +import base64 +import pathlib +from typing import Any, Mapping, TypeVar, cast +from datetime import date, datetime +from typing_extensions import Literal, get_args, override, get_type_hints as _get_type_hints + +import anyio +import pydantic + +from ._utils import ( + is_list, + is_given, + lru_cache, + is_mapping, + is_iterable, + is_sequence, +) +from .._files import is_base64_file_input +from ._compat import get_origin, is_typeddict +from ._typing import ( + is_list_type, + is_union_type, + extract_type_arg, + is_iterable_type, + is_required_type, + is_sequence_type, + is_annotated_type, + strip_annotated_type, +) + +_T = TypeVar("_T") + + +# TODO: support for drilling globals() and locals() +# TODO: ensure works correctly with forward references in all cases + + +PropertyFormat = Literal["iso8601", "base64", "custom"] + + +class PropertyInfo: + """Metadata class to be used in Annotated types to provide information about a given type. + + For example: + + class MyParams(TypedDict): + account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')] + + This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API. + """ + + alias: str | None + format: PropertyFormat | None + format_template: str | None + discriminator: str | None + + def __init__( + self, + *, + alias: str | None = None, + format: PropertyFormat | None = None, + format_template: str | None = None, + discriminator: str | None = None, + ) -> None: + self.alias = alias + self.format = format + self.format_template = format_template + self.discriminator = discriminator + + @override + def __repr__(self) -> str: + return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')" + + +def maybe_transform( + data: object, + expected_type: object, +) -> Any | None: + """Wrapper over `transform()` that allows `None` to be passed. + + See `transform()` for more details. + """ + if data is None: + return None + return transform(data, expected_type) + + +# Wrapper over _transform_recursive providing fake types +def transform( + data: _T, + expected_type: object, +) -> _T: + """Transform dictionaries based off of type information from the given type, for example: + + ```py + class Params(TypedDict, total=False): + card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]] + + + transformed = transform({"card_id": ""}, Params) + # {'cardID': ''} + ``` + + Any keys / data that does not have type information given will be included as is. + + It should be noted that the transformations that this function does are not represented in the type system. + """ + transformed = _transform_recursive(data, annotation=cast(type, expected_type)) + return cast(_T, transformed) + + +@lru_cache(maxsize=8096) +def _get_annotated_type(type_: type) -> type | None: + """If the given type is an `Annotated` type then it is returned, if not `None` is returned. + + This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]` + """ + if is_required_type(type_): + # Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]` + type_ = get_args(type_)[0] + + if is_annotated_type(type_): + return type_ + + return None + + +def _maybe_transform_key(key: str, type_: type) -> str: + """Transform the given `data` based on the annotations provided in `type_`. + + Note: this function only looks at `Annotated` types that contain `PropertyInfo` metadata. + """ + annotated_type = _get_annotated_type(type_) + if annotated_type is None: + # no `Annotated` definition for this type, no transformation needed + return key + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.alias is not None: + return annotation.alias + + return key + + +def _no_transform_needed(annotation: type) -> bool: + return annotation == float or annotation == int + + +def _transform_recursive( + data: object, + *, + annotation: type, + inner_type: type | None = None, +) -> object: + """Transform the given data against the expected type. + + Args: + annotation: The direct type annotation given to the particular piece of data. + This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc + + inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type + is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in + the list can be transformed using the metadata from the container type. + + Defaults to the same value as the `annotation` argument. + """ + from .._compat import model_dump + + if inner_type is None: + inner_type = annotation + + stripped_type = strip_annotated_type(inner_type) + origin = get_origin(stripped_type) or stripped_type + if is_typeddict(stripped_type) and is_mapping(data): + return _transform_typeddict(data, stripped_type) + + if origin == dict and is_mapping(data): + items_type = get_args(stripped_type)[1] + return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()} + + if ( + # List[T] + (is_list_type(stripped_type) and is_list(data)) + # Iterable[T] + or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + # Sequence[T] + or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str)) + ): + # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually + # intended as an iterable, so we don't transform it. + if isinstance(data, dict): + return cast(object, data) + + inner_type = extract_type_arg(stripped_type, 0) + if _no_transform_needed(inner_type): + # for some types there is no need to transform anything, so we can get a small + # perf boost from skipping that work. + # + # but we still need to convert to a list to ensure the data is json-serializable + if is_list(data): + return data + return list(data) + + return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] + + if is_union_type(stripped_type): + # For union types we run the transformation against all subtypes to ensure that everything is transformed. + # + # TODO: there may be edge cases where the same normalized field name will transform to two different names + # in different subtypes. + for subtype in get_args(stripped_type): + data = _transform_recursive(data, annotation=annotation, inner_type=subtype) + return data + + if isinstance(data, pydantic.BaseModel): + return model_dump(data, exclude_unset=True, mode="json") + + annotated_type = _get_annotated_type(annotation) + if annotated_type is None: + return data + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.format is not None: + return _format_data(data, annotation.format, annotation.format_template) + + return data + + +def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object: + if isinstance(data, (date, datetime)): + if format_ == "iso8601": + return data.isoformat() + + if format_ == "custom" and format_template is not None: + return data.strftime(format_template) + + if format_ == "base64" and is_base64_file_input(data): + binary: str | bytes | None = None + + if isinstance(data, pathlib.Path): + binary = data.read_bytes() + elif isinstance(data, io.IOBase): + binary = data.read() + + if isinstance(binary, str): # type: ignore[unreachable] + binary = binary.encode() + + if not isinstance(binary, bytes): + raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}") + + return base64.b64encode(binary).decode("ascii") + + return data + + +def _transform_typeddict( + data: Mapping[str, object], + expected_type: type, +) -> Mapping[str, object]: + result: dict[str, object] = {} + annotations = get_type_hints(expected_type, include_extras=True) + for key, value in data.items(): + if not is_given(value): + # we don't need to include omitted values here as they'll + # be stripped out before the request is sent anyway + continue + + type_ = annotations.get(key) + if type_ is None: + # we do not have a type annotation for this field, leave it as is + result[key] = value + else: + result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_) + return result + + +async def async_maybe_transform( + data: object, + expected_type: object, +) -> Any | None: + """Wrapper over `async_transform()` that allows `None` to be passed. + + See `async_transform()` for more details. + """ + if data is None: + return None + return await async_transform(data, expected_type) + + +async def async_transform( + data: _T, + expected_type: object, +) -> _T: + """Transform dictionaries based off of type information from the given type, for example: + + ```py + class Params(TypedDict, total=False): + card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]] + + + transformed = transform({"card_id": ""}, Params) + # {'cardID': ''} + ``` + + Any keys / data that does not have type information given will be included as is. + + It should be noted that the transformations that this function does are not represented in the type system. + """ + transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type)) + return cast(_T, transformed) + + +async def _async_transform_recursive( + data: object, + *, + annotation: type, + inner_type: type | None = None, +) -> object: + """Transform the given data against the expected type. + + Args: + annotation: The direct type annotation given to the particular piece of data. + This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc + + inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type + is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in + the list can be transformed using the metadata from the container type. + + Defaults to the same value as the `annotation` argument. + """ + from .._compat import model_dump + + if inner_type is None: + inner_type = annotation + + stripped_type = strip_annotated_type(inner_type) + origin = get_origin(stripped_type) or stripped_type + if is_typeddict(stripped_type) and is_mapping(data): + return await _async_transform_typeddict(data, stripped_type) + + if origin == dict and is_mapping(data): + items_type = get_args(stripped_type)[1] + return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()} + + if ( + # List[T] + (is_list_type(stripped_type) and is_list(data)) + # Iterable[T] + or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + # Sequence[T] + or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str)) + ): + # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually + # intended as an iterable, so we don't transform it. + if isinstance(data, dict): + return cast(object, data) + + inner_type = extract_type_arg(stripped_type, 0) + if _no_transform_needed(inner_type): + # for some types there is no need to transform anything, so we can get a small + # perf boost from skipping that work. + # + # but we still need to convert to a list to ensure the data is json-serializable + if is_list(data): + return data + return list(data) + + return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] + + if is_union_type(stripped_type): + # For union types we run the transformation against all subtypes to ensure that everything is transformed. + # + # TODO: there may be edge cases where the same normalized field name will transform to two different names + # in different subtypes. + for subtype in get_args(stripped_type): + data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype) + return data + + if isinstance(data, pydantic.BaseModel): + return model_dump(data, exclude_unset=True, mode="json") + + annotated_type = _get_annotated_type(annotation) + if annotated_type is None: + return data + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.format is not None: + return await _async_format_data(data, annotation.format, annotation.format_template) + + return data + + +async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object: + if isinstance(data, (date, datetime)): + if format_ == "iso8601": + return data.isoformat() + + if format_ == "custom" and format_template is not None: + return data.strftime(format_template) + + if format_ == "base64" and is_base64_file_input(data): + binary: str | bytes | None = None + + if isinstance(data, pathlib.Path): + binary = await anyio.Path(data).read_bytes() + elif isinstance(data, io.IOBase): + binary = data.read() + + if isinstance(binary, str): # type: ignore[unreachable] + binary = binary.encode() + + if not isinstance(binary, bytes): + raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}") + + return base64.b64encode(binary).decode("ascii") + + return data + + +async def _async_transform_typeddict( + data: Mapping[str, object], + expected_type: type, +) -> Mapping[str, object]: + result: dict[str, object] = {} + annotations = get_type_hints(expected_type, include_extras=True) + for key, value in data.items(): + if not is_given(value): + # we don't need to include omitted values here as they'll + # be stripped out before the request is sent anyway + continue + + type_ = annotations.get(key) + if type_ is None: + # we do not have a type annotation for this field, leave it as is + result[key] = value + else: + result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_) + return result + + +@lru_cache(maxsize=8096) +def get_type_hints( + obj: Any, + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, +) -> dict[str, Any]: + return _get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_typing.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..246a19761c500ec4b848c97eb1ce9d3f50b1154a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_typing.py @@ -0,0 +1,172 @@ +# 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. +# + +# mypy: ignore-errors +from __future__ import annotations + +import sys +import typing +import typing_extensions +from typing import Any, TypeVar, Iterable, cast +from collections import abc as _c_abc +from typing_extensions import ( + TypeIs, + Required, + Annotated, + get_args, + get_origin, +) + +from ._utils import lru_cache +from .._types import InheritsGeneric +from ._compat import is_union as _is_union + + +def is_annotated_type(typ: type) -> bool: + return get_origin(typ) == Annotated + + +def is_list_type(typ: type) -> bool: + return (get_origin(typ) or typ) == list + + +def is_sequence_type(typ: type) -> bool: + origin = get_origin(typ) or typ + return origin == typing_extensions.Sequence or origin == typing.Sequence or origin == _c_abc.Sequence + + +def is_iterable_type(typ: type) -> bool: + """If the given type is `typing.Iterable[T]`""" + origin = get_origin(typ) or typ + return origin == Iterable or origin == _c_abc.Iterable + + +def is_union_type(typ: type) -> bool: + return _is_union(get_origin(typ)) + + +def is_required_type(typ: type) -> bool: + return get_origin(typ) == Required + + +def is_typevar(typ: type) -> bool: + # type ignore is required because type checkers + # think this expression will always return False + return type(typ) == TypeVar # type: ignore + + +_TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (typing_extensions.TypeAliasType,) +if sys.version_info >= (3, 12): + _TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType) + + +def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]: + """Return whether the provided argument is an instance of `TypeAliasType`. + + ```python + type Int = int + is_type_alias_type(Int) + # > True + Str = TypeAliasType("Str", str) + is_type_alias_type(Str) + # > True + ``` + """ + return isinstance(tp, _TYPE_ALIAS_TYPES) + + +# Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] +@lru_cache(maxsize=8096) +def strip_annotated_type(typ: type) -> type: + if is_required_type(typ) or is_annotated_type(typ): + return strip_annotated_type(cast(type, get_args(typ)[0])) + + return typ + + +def extract_type_arg(typ: type, index: int) -> type: + args = get_args(typ) + try: + return cast(type, args[index]) + except IndexError as err: + raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err + + +def extract_type_var_from_base( + typ: type, + *, + generic_bases: tuple[type, ...], + index: int, + failure_message: str | None = None, +) -> type: + """Given a type like `Foo[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyResponse(Foo[bytes]): + ... + + extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes + ``` + + And where a generic subclass is given: + ```py + _T = TypeVar('_T') + class MyResponse(Foo[_T]): + ... + + extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes + ``` + """ + cls = cast(object, get_origin(typ) or typ) + if cls in generic_bases: # pyright: ignore[reportUnnecessaryContains] + # we're given the class directly + return extract_type_arg(typ, index) + + # if a subclass is given + # --- + # this is needed as __orig_bases__ is not present in the typeshed stubs + # because it is intended to be for internal use only, however there does + # not seem to be a way to resolve generic TypeVars for inherited subclasses + # without using it. + if isinstance(cls, InheritsGeneric): + target_base_class: Any | None = None + for base in cls.__orig_bases__: + if base.__origin__ in generic_bases: + target_base_class = base + break + + if target_base_class is None: + raise RuntimeError( + "Could not find the generic base class;\n" + "This should never happen;\n" + f"Does {cls} inherit from one of {generic_bases} ?" + ) + + extracted = extract_type_arg(target_base_class, index) + if is_typevar(extracted): + # If the extracted type argument is itself a type variable + # then that means the subclass itself is generic, so we have + # to resolve the type argument from the class itself, not + # the base class. + # + # Note: if there is more than 1 type argument, the subclass could + # change the ordering of the type arguments, this is not currently + # supported. + return extract_type_arg(typ, index) + + return extracted + + raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}") diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_utils.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7ba9e5e94c44c3753335cc4a040d73661d9e8b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_utils/_utils.py @@ -0,0 +1,438 @@ +# 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. +# + +# mypy: ignore-errors +from __future__ import annotations + +import os +import re +import inspect +import functools +from typing import ( + Any, + Tuple, + Mapping, + TypeVar, + Callable, + Iterable, + Sequence, + cast, + overload, +) +from pathlib import Path +from datetime import date, datetime +from typing_extensions import TypeGuard + +import sniffio + +from .._types import Omit, NotGiven, FileTypes, HeadersLike + +_T = TypeVar("_T") +_TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) +_MappingT = TypeVar("_MappingT", bound=Mapping[str, object]) +_SequenceT = TypeVar("_SequenceT", bound=Sequence[object]) +CallableT = TypeVar("CallableT", bound=Callable[..., Any]) + + +def flatten(t: Iterable[Iterable[_T]]) -> list[_T]: + return [item for sublist in t for item in sublist] + + +def extract_files( + # TODO: this needs to take Dict but variance issues..... + # create protocol type ? + query: Mapping[str, object], + *, + paths: Sequence[Sequence[str]], +) -> list[tuple[str, FileTypes]]: + """Recursively extract files from the given dictionary based on specified paths. + + A path may look like this ['foo', 'files', '', 'data']. + + Note: this mutates the given dictionary. + """ + files: list[tuple[str, FileTypes]] = [] + for path in paths: + files.extend(_extract_items(query, path, index=0, flattened_key=None)) + return files + + +def _extract_items( + obj: object, + path: Sequence[str], + *, + index: int, + flattened_key: str | None, +) -> list[tuple[str, FileTypes]]: + try: + key = path[index] + except IndexError: + if not is_given(obj): + # no value was provided - we can safely ignore + return [] + + # cyclical import + from .._files import assert_is_file_content + + # We have exhausted the path, return the entry we found. + assert flattened_key is not None + + if is_list(obj): + files: list[tuple[str, FileTypes]] = [] + for entry in obj: + assert_is_file_content(entry, key=flattened_key + "[]" if flattened_key else "") + files.append((flattened_key + "[]", cast(FileTypes, entry))) + return files + + assert_is_file_content(obj, key=flattened_key) + return [(flattened_key, cast(FileTypes, obj))] + + index += 1 + if is_dict(obj): + try: + # Remove the field if there are no more dict keys in the path, + # only "" traversal markers or end. + if all(p == "" for p in path[index:]): + item = obj.pop(key) + else: + item = obj[key] + except KeyError: + # Key was not present in the dictionary, this is not indicative of an error + # as the given path may not point to a required field. We also do not want + # to enforce required fields as the API may differ from the spec in some cases. + return [] + if flattened_key is None: + flattened_key = key + else: + flattened_key += f"[{key}]" + return _extract_items( + item, + path, + index=index, + flattened_key=flattened_key, + ) + elif is_list(obj): + if key != "": + return [] + + return flatten( + [ + _extract_items( + item, + path, + index=index, + flattened_key=flattened_key + "[]" if flattened_key is not None else "[]", + ) + for item in obj + ] + ) + + # Something unexpected was passed, just ignore it. + return [] + + +def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]: + return not isinstance(obj, NotGiven) and not isinstance(obj, Omit) + + +# Type safe methods for narrowing types with TypeVars. +# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown], +# however this cause Pyright to rightfully report errors. As we know we don't +# care about the contained types we can safely use `object` in its place. +# +# There are two separate functions defined, `is_*` and `is_*_t` for different use cases. +# `is_*` is for when you're dealing with an unknown input +# `is_*_t` is for when you're narrowing a known union type to a specific subset + + +def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]: + return isinstance(obj, tuple) + + +def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]: + return isinstance(obj, tuple) + + +def is_sequence(obj: object) -> TypeGuard[Sequence[object]]: + return isinstance(obj, Sequence) + + +def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]: + return isinstance(obj, Sequence) + + +def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]: + return isinstance(obj, Mapping) + + +def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]: + return isinstance(obj, Mapping) + + +def is_dict(obj: object) -> TypeGuard[dict[object, object]]: + return isinstance(obj, dict) + + +def is_list(obj: object) -> TypeGuard[list[object]]: + return isinstance(obj, list) + + +def is_iterable(obj: object) -> TypeGuard[Iterable[object]]: + return isinstance(obj, Iterable) + + +def deepcopy_minimal(item: _T) -> _T: + """Minimal reimplementation of copy.deepcopy() that will only copy certain object types: + + - mappings, e.g. `dict` + - list + + This is done for performance reasons. + """ + if is_mapping(item): + return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()}) + if is_list(item): + return cast(_T, [deepcopy_minimal(entry) for entry in item]) + return item + + +# copied from https://github.com/Rapptz/RoboDanny +def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str: + size = len(seq) + if size == 0: + return "" + + if size == 1: + return seq[0] + + if size == 2: + return f"{seq[0]} {final} {seq[1]}" + + return delim.join(seq[:-1]) + f" {final} {seq[-1]}" + + +def quote(string: str) -> str: + """Add single quotation marks around the given string. Does *not* do any escaping.""" + return f"'{string}'" + + +def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]: + """Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function. + + Useful for enforcing runtime validation of overloaded functions. + + Example usage: + ```py + @overload + def foo(*, a: str) -> str: ... + + + @overload + def foo(*, b: bool) -> str: ... + + + # This enforces the same constraints that a static type checker would + # i.e. that either a or b must be passed to the function + @required_args(["a"], ["b"]) + def foo(*, a: str | None = None, b: bool | None = None) -> str: ... + ``` + """ + + def inner(func: CallableT) -> CallableT: + params = inspect.signature(func).parameters + positional = [ + name + for name, param in params.items() + if param.kind + in { + param.POSITIONAL_ONLY, + param.POSITIONAL_OR_KEYWORD, + } + ] + + @functools.wraps(func) + def wrapper(*args: object, **kwargs: object) -> object: + given_params: set[str] = set() + for i, _ in enumerate(args): + try: + given_params.add(positional[i]) + except IndexError: + raise TypeError( + f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given" + ) from None + + for key in kwargs.keys(): + given_params.add(key) + + for variant in variants: + matches = all((param in given_params for param in variant)) + if matches: + break + else: # no break + if len(variants) > 1: + variations = human_join( + ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants] + ) + msg = f"Missing required arguments; Expected either {variations} arguments to be given" + else: + assert len(variants) > 0 + + # TODO: this error message is not deterministic + missing = list(set(variants[0]) - given_params) + if len(missing) > 1: + msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}" + else: + msg = f"Missing required argument: {quote(missing[0])}" + raise TypeError(msg) + return func(*args, **kwargs) + + return wrapper # type: ignore + + return inner + + +_K = TypeVar("_K") +_V = TypeVar("_V") + + +@overload +def strip_not_given(obj: None) -> None: ... + + +@overload +def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: ... + + +@overload +def strip_not_given(obj: object) -> object: ... + + +def strip_not_given(obj: object | None) -> object: + """Remove all top-level keys where their values are instances of `NotGiven`""" + if obj is None: + return None + + if not is_mapping(obj): + return obj + + return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)} + + +def coerce_integer(val: str) -> int: + return int(val, base=10) + + +def coerce_float(val: str) -> float: + return float(val) + + +def coerce_boolean(val: str) -> bool: + return val == "true" or val == "1" or val == "on" + + +def maybe_coerce_integer(val: str | None) -> int | None: + if val is None: + return None + return coerce_integer(val) + + +def maybe_coerce_float(val: str | None) -> float | None: + if val is None: + return None + return coerce_float(val) + + +def maybe_coerce_boolean(val: str | None) -> bool | None: + if val is None: + return None + return coerce_boolean(val) + + +def removeprefix(string: str, prefix: str) -> str: + """Remove a prefix from a string. + + Backport of `str.removeprefix` for Python < 3.9 + """ + if string.startswith(prefix): + return string[len(prefix) :] + return string + + +def removesuffix(string: str, suffix: str) -> str: + """Remove a suffix from a string. + + Backport of `str.removesuffix` for Python < 3.9 + """ + if string.endswith(suffix): + return string[: -len(suffix)] + return string + + +def file_from_path(path: str) -> FileTypes: + contents = Path(path).read_bytes() + file_name = os.path.basename(path) + return (file_name, contents) + + +def get_required_header(headers: HeadersLike, header: str) -> str: + lower_header = header.lower() + if is_mapping_t(headers): + # mypy doesn't understand the type narrowing here + for k, v in headers.items(): # type: ignore + if k.lower() == lower_header and isinstance(v, str): + return v + + # to deal with the case where the header looks like Stainless-Event-Id + intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize()) + + for normalized_header in [header, lower_header, header.upper(), intercaps_header]: + value = headers.get(normalized_header) + if value: + return value + + raise ValueError(f"Could not find {header} header") + + +def get_async_library() -> str: + try: + return sniffio.current_async_library() + except Exception: + return "false" + + +def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]: + """A version of functools.lru_cache that retains the type signature + for the wrapped function arguments. + """ + wrapper = functools.lru_cache( # noqa: TID251 + maxsize=maxsize, + ) + return cast(Any, wrapper) # type: ignore[no-any-return] + + +def json_safe(data: object) -> object: + """Translates a mapping / sequence recursively in the same fashion + as `pydantic` v2's `model_dump(mode="json")`. + """ + if is_mapping(data): + return {json_safe(key): json_safe(value) for key, value in data.items()} + + if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)): + return [json_safe(item) for item in data] + + if isinstance(data, (datetime, date)): + return data.isoformat() + + return data diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..f7466773c654f878555e5c3b48c737dc8781481f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/_version.py @@ -0,0 +1,18 @@ +# 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 ..version import __version__ as __version__ + +__title__ = "google.genai._interactions" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02807630b160fe9386aee4aeafd572afd470b6be --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__init__.py @@ -0,0 +1,48 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .webhooks import ( + WebhooksResource, + AsyncWebhooksResource, + WebhooksResourceWithRawResponse, + AsyncWebhooksResourceWithRawResponse, + WebhooksResourceWithStreamingResponse, + AsyncWebhooksResourceWithStreamingResponse, +) +from .interactions import ( + InteractionsResource, + AsyncInteractionsResource, + InteractionsResourceWithRawResponse, + AsyncInteractionsResourceWithRawResponse, + InteractionsResourceWithStreamingResponse, + AsyncInteractionsResourceWithStreamingResponse, +) + +__all__ = [ + "InteractionsResource", + "AsyncInteractionsResource", + "InteractionsResourceWithRawResponse", + "AsyncInteractionsResourceWithRawResponse", + "InteractionsResourceWithStreamingResponse", + "AsyncInteractionsResourceWithStreamingResponse", + "WebhooksResource", + "AsyncWebhooksResource", + "WebhooksResourceWithRawResponse", + "AsyncWebhooksResourceWithRawResponse", + "WebhooksResourceWithStreamingResponse", + "AsyncWebhooksResourceWithStreamingResponse", +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e67a28328d6d7ba4bc141b669320747e503065a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/interactions.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/interactions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0ed0421d5a86e33bdc8c445d4fdbec93a927fe5 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/interactions.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/webhooks.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/webhooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eaeffbf893cb865db0d64fff516ea5f232a122e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/__pycache__/webhooks.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/interactions.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/interactions.py new file mode 100644 index 0000000000000000000000000000000000000000..adf175a2d8c6f311f9e6fbd9f819299faa8e42b5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/interactions.py @@ -0,0 +1,1465 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal, overload + +import httpx + +from ..types import interaction_get_params, interaction_create_params +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import required_args, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._streaming import Stream, AsyncStream +from .._base_client import make_request_options +from ..types.tool_param import ToolParam +from ..types.interaction import Interaction +from ..types.model_param import ModelParam +from ..types.webhook_config_param import WebhookConfigParam +from ..types.interaction_sse_event import InteractionSSEEvent +from ..types.generation_config_param import GenerationConfigParam + +__all__ = ["InteractionsResource", "AsyncInteractionsResource"] + + +class InteractionsResource(SyncAPIResource): + @cached_property + def with_raw_response(self) -> InteractionsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#accessing-raw-response-data-eg-headers + """ + return InteractionsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> InteractionsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#with_streaming_response + """ + return InteractionsResourceWithStreamingResponse(self) + + @overload + def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam, + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + stream: Literal[False] | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """ + Creates a new interaction. + + Args: + input: The input for the interaction. + + model: The name of the `Model` used for generating the interaction. + + background: Input only. Whether to run the model interaction in the background. + + generation_config: Input only. Configuration parameters for the model interaction. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + stream: Input only. Whether the interaction will be streamed. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam, + stream: Literal[True], + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Stream[InteractionSSEEvent]: + """ + Creates a new interaction. + + Args: + input: The input for the interaction. + + model: The name of the `Model` used for generating the interaction. + + stream: Input only. Whether the interaction will be streamed. + + background: Input only. Whether to run the model interaction in the background. + + generation_config: Input only. Configuration parameters for the model interaction. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + api_version: str | None = None, + agent: Union[str, Literal["deep-research-pro-preview-12-2025"]], + input: interaction_create_params.Input, + agent_config: interaction_create_params.AgentConfig | Omit = omit, + background: bool | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + stream: Literal[False] | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """ + Creates a new interaction. + + Args: + agent: The name of the `Agent` used for generating the interaction. + + input: The input for the interaction. + + agent_config: Configuration parameters for the agent interaction. + + background: Input only. Whether to run the model interaction in the background. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + stream: Input only. Whether the interaction will be streamed. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + api_version: str | None = None, + agent: Union[str, Literal["deep-research-pro-preview-12-2025"]], + input: interaction_create_params.Input, + stream: Literal[True], + agent_config: interaction_create_params.AgentConfig | Omit = omit, + background: bool | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Stream[InteractionSSEEvent]: + """ + Creates a new interaction. + + Args: + agent: The name of the `Agent` used for generating the interaction. + + input: The input for the interaction. + + stream: Input only. Whether the interaction will be streamed. + + agent_config: Configuration parameters for the agent interaction. + + background: Input only. Whether to run the model interaction in the background. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam, + stream: bool, + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | Stream[InteractionSSEEvent]: + """ + Creates a new interaction. + + Args: + input: The input for the interaction. + + model: The name of the `Model` used for generating the interaction. + + stream: Input only. Whether the interaction will be streamed. + + background: Input only. Whether to run the model interaction in the background. + + generation_config: Input only. Configuration parameters for the model interaction. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["input", "model"], ["input", "model", "stream"], ["agent", "input"], ["agent", "input", "stream"]) + def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam | Omit = omit, + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + stream: Literal[False] | Literal[True] | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + agent: Union[str, Literal["deep-research-pro-preview-12-2025"]] | Omit = omit, + agent_config: interaction_create_params.AgentConfig | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | Stream[InteractionSSEEvent]: + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if model is not omit and agent_config is not omit: + raise ValueError("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.") + if agent is not omit and generation_config is not omit: + raise ValueError("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.") + return self._post( + self._client._build_maybe_vertex_path(api_version=api_version, path='interactions'), + body=maybe_transform( + { + "input": input, + "model": model, + "background": background, + "generation_config": generation_config, + "previous_interaction_id": previous_interaction_id, + "response_format": response_format, + "response_mime_type": response_mime_type, + "response_modalities": response_modalities, + "service_tier": service_tier, + "store": store, + "stream": stream, + "system_instruction": system_instruction, + "tools": tools, + "webhook_config": webhook_config, + "agent": agent, + "agent_config": agent_config, + }, + interaction_create_params.CreateModelInteractionParamsStreaming + if stream + else interaction_create_params.CreateModelInteractionParamsNonStreaming, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Interaction, + stream=stream or False, + stream_cls=Stream[InteractionSSEEvent], + ) + + def delete( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> object: + """ + Deletes the interaction by id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._delete( + self._client._build_maybe_vertex_path(api_version=api_version, path=f'interactions/{id}'), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=object, + ) + + def cancel( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """Cancels an interaction by id. + + This only applies to background interactions that + are still running. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._post( + self._client._build_maybe_vertex_path(api_version=api_version, path=f'interactions/{id}/cancel'), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Interaction, + ) + + @overload + def get( + self, + id: str, + *, + api_version: str | None = None, + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + stream: Literal[False] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """ + Retrieves the full details of a single interaction based on its + `Interaction.id`. + + Args: + include_input: If set to true, includes the input in the response. + + last_event_id: Optional. If set, resumes the interaction stream from the next chunk after the + event marked by the event id. Can only be used if `stream` is true. + + stream: If set to true, the generated content will be streamed incrementally. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def get( + self, + id: str, + *, + api_version: str | None = None, + stream: Literal[True], + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Stream[InteractionSSEEvent]: + """ + Retrieves the full details of a single interaction based on its + `Interaction.id`. + + Args: + stream: If set to true, the generated content will be streamed incrementally. + + include_input: If set to true, includes the input in the response. + + last_event_id: Optional. If set, resumes the interaction stream from the next chunk after the + event marked by the event id. Can only be used if `stream` is true. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def get( + self, + id: str, + *, + api_version: str | None = None, + stream: bool, + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | Stream[InteractionSSEEvent]: + """ + Retrieves the full details of a single interaction based on its + `Interaction.id`. + + Args: + stream: If set to true, the generated content will be streamed incrementally. + + include_input: If set to true, includes the input in the response. + + last_event_id: Optional. If set, resumes the interaction stream from the next chunk after the + event marked by the event id. Can only be used if `stream` is true. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + def get( + self, + id: str, + *, + api_version: str | None = None, + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + stream: Literal[False] | Literal[True] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | Stream[InteractionSSEEvent]: + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._get( + self._client._build_maybe_vertex_path(api_version=api_version, path=f'interactions/{id}'), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "include_input": include_input, + "last_event_id": last_event_id, + "stream": stream, + }, + interaction_get_params.InteractionGetParams, + ), + ), + cast_to=Interaction, + stream=stream or False, + stream_cls=Stream[InteractionSSEEvent], + ) + + +class AsyncInteractionsResource(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncInteractionsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#accessing-raw-response-data-eg-headers + """ + return AsyncInteractionsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncInteractionsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#with_streaming_response + """ + return AsyncInteractionsResourceWithStreamingResponse(self) + + @overload + async def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam, + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + stream: Literal[False] | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """ + Creates a new interaction. + + Args: + input: The input for the interaction. + + model: The name of the `Model` used for generating the interaction. + + background: Input only. Whether to run the model interaction in the background. + + generation_config: Input only. Configuration parameters for the model interaction. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + stream: Input only. Whether the interaction will be streamed. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam, + stream: Literal[True], + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AsyncStream[InteractionSSEEvent]: + """ + Creates a new interaction. + + Args: + input: The input for the interaction. + + model: The name of the `Model` used for generating the interaction. + + stream: Input only. Whether the interaction will be streamed. + + background: Input only. Whether to run the model interaction in the background. + + generation_config: Input only. Configuration parameters for the model interaction. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + api_version: str | None = None, + agent: Union[str, Literal["deep-research-pro-preview-12-2025"]], + input: interaction_create_params.Input, + agent_config: interaction_create_params.AgentConfig | Omit = omit, + background: bool | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + stream: Literal[False] | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """ + Creates a new interaction. + + Args: + agent: The name of the `Agent` used for generating the interaction. + + input: The input for the interaction. + + agent_config: Configuration parameters for the agent interaction. + + background: Input only. Whether to run the model interaction in the background. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + stream: Input only. Whether the interaction will be streamed. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + api_version: str | None = None, + agent: Union[str, Literal["deep-research-pro-preview-12-2025"]], + input: interaction_create_params.Input, + stream: Literal[True], + agent_config: interaction_create_params.AgentConfig | Omit = omit, + background: bool | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AsyncStream[InteractionSSEEvent]: + """ + Creates a new interaction. + + Args: + agent: The name of the `Agent` used for generating the interaction. + + input: The input for the interaction. + + stream: Input only. Whether the interaction will be streamed. + + agent_config: Configuration parameters for the agent interaction. + + background: Input only. Whether to run the model interaction in the background. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam, + stream: bool, + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | AsyncStream[InteractionSSEEvent]: + """ + Creates a new interaction. + + Args: + input: The input for the interaction. + + model: The name of the `Model` used for generating the interaction. + + stream: Input only. Whether the interaction will be streamed. + + background: Input only. Whether to run the model interaction in the background. + + generation_config: Input only. Configuration parameters for the model interaction. + + previous_interaction_id: The ID of the previous interaction, if any. + + response_format: Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + + response_mime_type: The mime type of the response. This is required if response_format is set. + + response_modalities: The requested modalities of the response (TEXT, IMAGE, AUDIO). + + service_tier: The service tier for the interaction. + + store: Input only. Whether to store the response and request for later retrieval. + + system_instruction: System instruction for the interaction. + + tools: A list of tool declarations the model may call during interaction. + + webhook_config: Optional. Webhook configuration for receiving notifications when the interaction + completes. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["input", "model"], ["input", "model", "stream"], ["agent", "input"], ["agent", "input", "stream"]) + async def create( + self, + *, + api_version: str | None = None, + input: interaction_create_params.Input, + model: ModelParam | Omit = omit, + background: bool | Omit = omit, + generation_config: GenerationConfigParam | Omit = omit, + previous_interaction_id: str | Omit = omit, + response_format: object | Omit = omit, + response_mime_type: str | Omit = omit, + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] | Omit = omit, + service_tier: Literal["flex", "standard", "priority"] | Omit = omit, + store: bool | Omit = omit, + stream: Literal[False] | Literal[True] | Omit = omit, + system_instruction: str | Omit = omit, + tools: Iterable[ToolParam] | Omit = omit, + webhook_config: WebhookConfigParam | Omit = omit, + agent: Union[str, Literal["deep-research-pro-preview-12-2025"]] | Omit = omit, + agent_config: interaction_create_params.AgentConfig | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | AsyncStream[InteractionSSEEvent]: + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if model is not omit and agent_config is not omit: + raise ValueError("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.") + if agent is not omit and generation_config is not omit: + raise ValueError("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.") + return await self._post( + self._client._build_maybe_vertex_path(api_version=api_version, path='interactions'), + body=await async_maybe_transform( + { + "input": input, + "model": model, + "background": background, + "generation_config": generation_config, + "previous_interaction_id": previous_interaction_id, + "response_format": response_format, + "response_mime_type": response_mime_type, + "response_modalities": response_modalities, + "service_tier": service_tier, + "store": store, + "stream": stream, + "system_instruction": system_instruction, + "tools": tools, + "webhook_config": webhook_config, + "agent": agent, + "agent_config": agent_config, + }, + interaction_create_params.CreateModelInteractionParamsStreaming + if stream + else interaction_create_params.CreateModelInteractionParamsNonStreaming, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Interaction, + stream=stream or False, + stream_cls=AsyncStream[InteractionSSEEvent], + ) + + async def delete( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> object: + """ + Deletes the interaction by id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._delete( + self._client._build_maybe_vertex_path(api_version=api_version, path=f'interactions/{id}'), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=object, + ) + + async def cancel( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """Cancels an interaction by id. + + This only applies to background interactions that + are still running. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._post( + self._client._build_maybe_vertex_path(api_version=api_version, path=f'interactions/{id}/cancel'), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Interaction, + ) + + @overload + async def get( + self, + id: str, + *, + api_version: str | None = None, + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + stream: Literal[False] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction: + """ + Retrieves the full details of a single interaction based on its + `Interaction.id`. + + Args: + include_input: If set to true, includes the input in the response. + + last_event_id: Optional. If set, resumes the interaction stream from the next chunk after the + event marked by the event id. Can only be used if `stream` is true. + + stream: If set to true, the generated content will be streamed incrementally. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def get( + self, + id: str, + *, + api_version: str | None = None, + stream: Literal[True], + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AsyncStream[InteractionSSEEvent]: + """ + Retrieves the full details of a single interaction based on its + `Interaction.id`. + + Args: + stream: If set to true, the generated content will be streamed incrementally. + + include_input: If set to true, includes the input in the response. + + last_event_id: Optional. If set, resumes the interaction stream from the next chunk after the + event marked by the event id. Can only be used if `stream` is true. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def get( + self, + id: str, + *, + api_version: str | None = None, + stream: bool, + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | AsyncStream[InteractionSSEEvent]: + """ + Retrieves the full details of a single interaction based on its + `Interaction.id`. + + Args: + stream: If set to true, the generated content will be streamed incrementally. + + include_input: If set to true, includes the input in the response. + + last_event_id: Optional. If set, resumes the interaction stream from the next chunk after the + event marked by the event id. Can only be used if `stream` is true. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + async def get( + self, + id: str, + *, + api_version: str | None = None, + include_input: bool | Omit = omit, + last_event_id: str | Omit = omit, + stream: Literal[False] | Literal[True] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Interaction | AsyncStream[InteractionSSEEvent]: + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._get( + self._client._build_maybe_vertex_path(api_version=api_version, path=f'interactions/{id}'), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "include_input": include_input, + "last_event_id": last_event_id, + "stream": stream, + }, + interaction_get_params.InteractionGetParams, + ), + ), + cast_to=Interaction, + stream=stream or False, + stream_cls=AsyncStream[InteractionSSEEvent], + ) + + +class InteractionsResourceWithRawResponse: + def __init__(self, interactions: InteractionsResource) -> None: + self._interactions = interactions + + self.create = to_raw_response_wrapper( + interactions.create, + ) + self.delete = to_raw_response_wrapper( + interactions.delete, + ) + self.cancel = to_raw_response_wrapper( + interactions.cancel, + ) + self.get = to_raw_response_wrapper( + interactions.get, + ) + + +class AsyncInteractionsResourceWithRawResponse: + def __init__(self, interactions: AsyncInteractionsResource) -> None: + self._interactions = interactions + + self.create = async_to_raw_response_wrapper( + interactions.create, + ) + self.delete = async_to_raw_response_wrapper( + interactions.delete, + ) + self.cancel = async_to_raw_response_wrapper( + interactions.cancel, + ) + self.get = async_to_raw_response_wrapper( + interactions.get, + ) + + +class InteractionsResourceWithStreamingResponse: + def __init__(self, interactions: InteractionsResource) -> None: + self._interactions = interactions + + self.create = to_streamed_response_wrapper( + interactions.create, + ) + self.delete = to_streamed_response_wrapper( + interactions.delete, + ) + self.cancel = to_streamed_response_wrapper( + interactions.cancel, + ) + self.get = to_streamed_response_wrapper( + interactions.get, + ) + + +class AsyncInteractionsResourceWithStreamingResponse: + def __init__(self, interactions: AsyncInteractionsResource) -> None: + self._interactions = interactions + + self.create = async_to_streamed_response_wrapper( + interactions.create, + ) + self.delete = async_to_streamed_response_wrapper( + interactions.delete, + ) + self.cancel = async_to_streamed_response_wrapper( + interactions.cancel, + ) + self.get = async_to_streamed_response_wrapper( + interactions.get, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/webhooks.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/webhooks.py new file mode 100644 index 0000000000000000000000000000000000000000..6a758b9196ad220a65bf4f0a0e96905997b53e23 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/resources/webhooks.py @@ -0,0 +1,1009 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal + +import httpx + +from ..types import ( + webhook_list_params, + webhook_ping_params, + webhook_create_params, + webhook_update_params, + webhook_rotate_signing_secret_params, +) +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import path_template, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.webhook import Webhook +from ..types.webhook_list_response import WebhookListResponse +from ..types.webhook_ping_response import WebhookPingResponse +from ..types.webhook_delete_response import WebhookDeleteResponse +from ..types.webhook_rotate_signing_secret_response import WebhookRotateSigningSecretResponse + +__all__ = ["WebhooksResource", "AsyncWebhooksResource"] + + +class WebhooksResource(SyncAPIResource): + @cached_property + def with_raw_response(self) -> WebhooksResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#accessing-raw-response-data-eg-headers + """ + return WebhooksResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> WebhooksResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#with_streaming_response + """ + return WebhooksResourceWithStreamingResponse(self) + + def create( + self, + *, + api_version: str | None = None, + subscribed_events: List[ + Union[ + Literal[ + "batch.succeeded", + "batch.cancelled", + "batch.expired", + "batch.failed", + "interaction.requires_action", + "interaction.completed", + "interaction.failed", + "interaction.cancelled", + "video.generated", + ], + str, + ] + ], + uri: str, + webhook_id: str | Omit = omit, + name: str | Omit = omit, + state: Literal["enabled", "disabled", "disabled_due_to_failed_deliveries"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Webhook: + """Creates a new Webhook. + + Args: + subscribed_events: + Required. + + The events that the webhook is subscribed to. Available events: + + - batch.succeeded + - batch.cancelled + - batch.expired + - batch.failed + - interaction.requires_action + - interaction.completed + - interaction.failed + - interaction.cancelled + - video.generated + + uri: Required. The URI to which webhook events will be sent. + + webhook_id: Optional. The webhook_id to use for the webhook. If not specified, the server + will generate a unique ID. + + name: Identifier. The name of the webhook. Format: `webhooks/{webhook_id}` + + state: The state of the webhook. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + return self._post( + path_template("/{api_version}/webhooks", api_version=api_version), + body=maybe_transform( + { + "subscribed_events": subscribed_events, + "uri": uri, + "name": name, + "state": state, + }, + webhook_create_params.WebhookCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"webhook_id": webhook_id}, webhook_create_params.WebhookCreateParams), + ), + cast_to=Webhook, + ) + + def update( + self, + id: str, + *, + api_version: str | None = None, + subscribed_events: List[ + Union[ + Literal[ + "batch.succeeded", + "batch.cancelled", + "batch.expired", + "batch.failed", + "interaction.requires_action", + "interaction.completed", + "interaction.failed", + "interaction.cancelled", + "video.generated", + ], + str, + ] + ], + uri: str, + update_mask: str | Omit = omit, + name: str | Omit = omit, + state: Literal["enabled", "disabled", "disabled_due_to_failed_deliveries"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Webhook: + """Updates an existing Webhook. + + Args: + subscribed_events: + Required. + + The events that the webhook is subscribed to. Available events: + + - batch.succeeded + - batch.cancelled + - batch.expired + - batch.failed + - interaction.requires_action + - interaction.completed + - interaction.failed + - interaction.cancelled + - video.generated + + uri: Required. The URI to which webhook events will be sent. + + update_mask: Optional. The list of fields to update. + + name: Identifier. The name of the webhook. Format: `webhooks/{webhook_id}` + + state: The state of the webhook. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._patch( + path_template("/{api_version}/webhooks/{id}", api_version=api_version, id=id), + body=maybe_transform( + { + "subscribed_events": subscribed_events, + "uri": uri, + "name": name, + "state": state, + }, + webhook_update_params.WebhookUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"update_mask": update_mask}, webhook_update_params.WebhookUpdateParams), + ), + cast_to=Webhook, + ) + + def list( + self, + *, + api_version: str | None = None, + page_size: int | Omit = omit, + page_token: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookListResponse: + """Lists all Webhooks. + + Args: + page_size: Optional. + + The maximum number of webhooks to return. The service may return fewer + than this value. If unspecified, at most 50 webhooks will be returned. The + maximum value is 1000. + + page_token: Optional. A page token, received from a previous `ListWebhooks` call. Provide + this to retrieve the subsequent page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + return self._get( + path_template("/{api_version}/webhooks", api_version=api_version), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "page_size": page_size, + "page_token": page_token, + }, + webhook_list_params.WebhookListParams, + ), + ), + cast_to=WebhookListResponse, + ) + + def delete( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookDeleteResponse: + """ + Deletes a Webhook. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._delete( + path_template("/{api_version}/webhooks/{id}", api_version=api_version, id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WebhookDeleteResponse, + ) + + def get( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Webhook: + """ + Gets a specific Webhook. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._get( + path_template("/{api_version}/webhooks/{id}", api_version=api_version, id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Webhook, + ) + + def ping( + self, + id: str, + *, + api_version: str | None = None, + body: webhook_ping_params.Body | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookPingResponse: + """ + Sends a ping event to a Webhook. + + Args: + body: Request message for WebhookService.PingWebhook. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._post( + path_template("/{api_version}/webhooks/{id}:ping", api_version=api_version, id=id), + body=maybe_transform(body, webhook_ping_params.WebhookPingParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WebhookPingResponse, + ) + + def rotate_signing_secret( + self, + id: str, + *, + api_version: str | None = None, + revocation_behavior: Literal["revoke_previous_secrets_after_h24", "revoke_previous_secrets_immediately"] + | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookRotateSigningSecretResponse: + """ + Generates a new signing secret for a Webhook. + + Args: + revocation_behavior: Optional. The revocation behavior for previous signing secrets. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._post( + path_template("/{api_version}/webhooks/{id}:rotateSigningSecret", api_version=api_version, id=id), + body=maybe_transform( + {"revocation_behavior": revocation_behavior}, + webhook_rotate_signing_secret_params.WebhookRotateSigningSecretParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WebhookRotateSigningSecretResponse, + ) + + +class AsyncWebhooksResource(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncWebhooksResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#accessing-raw-response-data-eg-headers + """ + return AsyncWebhooksResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncWebhooksResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/stainless-sdks/gemini-next-gen-api-python#with_streaming_response + """ + return AsyncWebhooksResourceWithStreamingResponse(self) + + async def create( + self, + *, + api_version: str | None = None, + subscribed_events: List[ + Union[ + Literal[ + "batch.succeeded", + "batch.cancelled", + "batch.expired", + "batch.failed", + "interaction.requires_action", + "interaction.completed", + "interaction.failed", + "interaction.cancelled", + "video.generated", + ], + str, + ] + ], + uri: str, + webhook_id: str | Omit = omit, + name: str | Omit = omit, + state: Literal["enabled", "disabled", "disabled_due_to_failed_deliveries"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Webhook: + """Creates a new Webhook. + + Args: + subscribed_events: + Required. + + The events that the webhook is subscribed to. Available events: + + - batch.succeeded + - batch.cancelled + - batch.expired + - batch.failed + - interaction.requires_action + - interaction.completed + - interaction.failed + - interaction.cancelled + - video.generated + + uri: Required. The URI to which webhook events will be sent. + + webhook_id: Optional. The webhook_id to use for the webhook. If not specified, the server + will generate a unique ID. + + name: Identifier. The name of the webhook. Format: `webhooks/{webhook_id}` + + state: The state of the webhook. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + return await self._post( + path_template("/{api_version}/webhooks", api_version=api_version), + body=await async_maybe_transform( + { + "subscribed_events": subscribed_events, + "uri": uri, + "name": name, + "state": state, + }, + webhook_create_params.WebhookCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"webhook_id": webhook_id}, webhook_create_params.WebhookCreateParams + ), + ), + cast_to=Webhook, + ) + + async def update( + self, + id: str, + *, + api_version: str | None = None, + subscribed_events: List[ + Union[ + Literal[ + "batch.succeeded", + "batch.cancelled", + "batch.expired", + "batch.failed", + "interaction.requires_action", + "interaction.completed", + "interaction.failed", + "interaction.cancelled", + "video.generated", + ], + str, + ] + ], + uri: str, + update_mask: str | Omit = omit, + name: str | Omit = omit, + state: Literal["enabled", "disabled", "disabled_due_to_failed_deliveries"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Webhook: + """Updates an existing Webhook. + + Args: + subscribed_events: + Required. + + The events that the webhook is subscribed to. Available events: + + - batch.succeeded + - batch.cancelled + - batch.expired + - batch.failed + - interaction.requires_action + - interaction.completed + - interaction.failed + - interaction.cancelled + - video.generated + + uri: Required. The URI to which webhook events will be sent. + + update_mask: Optional. The list of fields to update. + + name: Identifier. The name of the webhook. Format: `webhooks/{webhook_id}` + + state: The state of the webhook. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._patch( + path_template("/{api_version}/webhooks/{id}", api_version=api_version, id=id), + body=await async_maybe_transform( + { + "subscribed_events": subscribed_events, + "uri": uri, + "name": name, + "state": state, + }, + webhook_update_params.WebhookUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"update_mask": update_mask}, webhook_update_params.WebhookUpdateParams + ), + ), + cast_to=Webhook, + ) + + async def list( + self, + *, + api_version: str | None = None, + page_size: int | Omit = omit, + page_token: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookListResponse: + """Lists all Webhooks. + + Args: + page_size: Optional. + + The maximum number of webhooks to return. The service may return fewer + than this value. If unspecified, at most 50 webhooks will be returned. The + maximum value is 1000. + + page_token: Optional. A page token, received from a previous `ListWebhooks` call. Provide + this to retrieve the subsequent page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + return await self._get( + path_template("/{api_version}/webhooks", api_version=api_version), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "page_size": page_size, + "page_token": page_token, + }, + webhook_list_params.WebhookListParams, + ), + ), + cast_to=WebhookListResponse, + ) + + async def delete( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookDeleteResponse: + """ + Deletes a Webhook. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._delete( + path_template("/{api_version}/webhooks/{id}", api_version=api_version, id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WebhookDeleteResponse, + ) + + async def get( + self, + id: str, + *, + api_version: str | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Webhook: + """ + Gets a specific Webhook. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._get( + path_template("/{api_version}/webhooks/{id}", api_version=api_version, id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Webhook, + ) + + async def ping( + self, + id: str, + *, + api_version: str | None = None, + body: webhook_ping_params.Body | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookPingResponse: + """ + Sends a ping event to a Webhook. + + Args: + body: Request message for WebhookService.PingWebhook. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._post( + path_template("/{api_version}/webhooks/{id}:ping", api_version=api_version, id=id), + body=await async_maybe_transform(body, webhook_ping_params.WebhookPingParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WebhookPingResponse, + ) + + async def rotate_signing_secret( + self, + id: str, + *, + api_version: str | None = None, + revocation_behavior: Literal["revoke_previous_secrets_after_h24", "revoke_previous_secrets_immediately"] + | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WebhookRotateSigningSecretResponse: + """ + Generates a new signing secret for a Webhook. + + Args: + revocation_behavior: Optional. The revocation behavior for previous signing secrets. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if api_version is None: + api_version = self._client._get_api_version_path_param() + if not api_version: + raise ValueError(f"Expected a non-empty value for `api_version` but received {api_version!r}") + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._post( + path_template("/{api_version}/webhooks/{id}:rotateSigningSecret", api_version=api_version, id=id), + body=await async_maybe_transform( + {"revocation_behavior": revocation_behavior}, + webhook_rotate_signing_secret_params.WebhookRotateSigningSecretParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WebhookRotateSigningSecretResponse, + ) + + +class WebhooksResourceWithRawResponse: + def __init__(self, webhooks: WebhooksResource) -> None: + self._webhooks = webhooks + + self.create = to_raw_response_wrapper( + webhooks.create, + ) + self.update = to_raw_response_wrapper( + webhooks.update, + ) + self.list = to_raw_response_wrapper( + webhooks.list, + ) + self.delete = to_raw_response_wrapper( + webhooks.delete, + ) + self.get = to_raw_response_wrapper( + webhooks.get, + ) + self.ping = to_raw_response_wrapper( + webhooks.ping, + ) + self.rotate_signing_secret = to_raw_response_wrapper( + webhooks.rotate_signing_secret, + ) + + +class AsyncWebhooksResourceWithRawResponse: + def __init__(self, webhooks: AsyncWebhooksResource) -> None: + self._webhooks = webhooks + + self.create = async_to_raw_response_wrapper( + webhooks.create, + ) + self.update = async_to_raw_response_wrapper( + webhooks.update, + ) + self.list = async_to_raw_response_wrapper( + webhooks.list, + ) + self.delete = async_to_raw_response_wrapper( + webhooks.delete, + ) + self.get = async_to_raw_response_wrapper( + webhooks.get, + ) + self.ping = async_to_raw_response_wrapper( + webhooks.ping, + ) + self.rotate_signing_secret = async_to_raw_response_wrapper( + webhooks.rotate_signing_secret, + ) + + +class WebhooksResourceWithStreamingResponse: + def __init__(self, webhooks: WebhooksResource) -> None: + self._webhooks = webhooks + + self.create = to_streamed_response_wrapper( + webhooks.create, + ) + self.update = to_streamed_response_wrapper( + webhooks.update, + ) + self.list = to_streamed_response_wrapper( + webhooks.list, + ) + self.delete = to_streamed_response_wrapper( + webhooks.delete, + ) + self.get = to_streamed_response_wrapper( + webhooks.get, + ) + self.ping = to_streamed_response_wrapper( + webhooks.ping, + ) + self.rotate_signing_secret = to_streamed_response_wrapper( + webhooks.rotate_signing_secret, + ) + + +class AsyncWebhooksResourceWithStreamingResponse: + def __init__(self, webhooks: AsyncWebhooksResource) -> None: + self._webhooks = webhooks + + self.create = async_to_streamed_response_wrapper( + webhooks.create, + ) + self.update = async_to_streamed_response_wrapper( + webhooks.update, + ) + self.list = async_to_streamed_response_wrapper( + webhooks.list, + ) + self.delete = async_to_streamed_response_wrapper( + webhooks.delete, + ) + self.get = async_to_streamed_response_wrapper( + webhooks.get, + ) + self.ping = async_to_streamed_response_wrapper( + webhooks.ping, + ) + self.rotate_signing_secret = async_to_streamed_response_wrapper( + webhooks.rotate_signing_secret, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5606758fe407f17044eeb447a8e69430c27d6064 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__init__.py @@ -0,0 +1,135 @@ +# 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .tool import Tool as Tool +from .turn import Turn as Turn +from .model import Model as Model +from .usage import Usage as Usage +from .content import Content as Content +from .webhook import Webhook as Webhook +from .function import Function as Function +from .annotation import Annotation as Annotation +from .tool_param import ToolParam as ToolParam +from .turn_param import TurnParam as TurnParam +from .error_event import ErrorEvent as ErrorEvent +from .interaction import Interaction as Interaction +from .model_param import ModelParam as ModelParam +from .usage_param import UsageParam as UsageParam +from .content_stop import ContentStop as ContentStop +from .image_config import ImageConfig as ImageConfig +from .text_content import TextContent as TextContent +from .url_citation import URLCitation as URLCitation +from .allowed_tools import AllowedTools as AllowedTools +from .audio_content import AudioContent as AudioContent +from .content_delta import ContentDelta as ContentDelta +from .content_param import ContentParam as ContentParam +from .content_start import ContentStart as ContentStart +from .file_citation import FileCitation as FileCitation +from .image_content import ImageContent as ImageContent +from .speech_config import SpeechConfig as SpeechConfig +from .video_content import VideoContent as VideoContent +from .function_param import FunctionParam as FunctionParam +from .place_citation import PlaceCitation as PlaceCitation +from .signing_secret import SigningSecret as SigningSecret +from .thinking_level import ThinkingLevel as ThinkingLevel +from .webhook_config import WebhookConfig as WebhookConfig +from .thought_content import ThoughtContent as ThoughtContent +from .annotation_param import AnnotationParam as AnnotationParam +from .document_content import DocumentContent as DocumentContent +from .tool_choice_type import ToolChoiceType as ToolChoiceType +from .generation_config import GenerationConfig as GenerationConfig +from .google_maps_result import GoogleMapsResult as GoogleMapsResult +from .image_config_param import ImageConfigParam as ImageConfigParam +from .text_content_param import TextContentParam as TextContentParam +from .tool_choice_config import ToolChoiceConfig as ToolChoiceConfig +from .url_citation_param import URLCitationParam as URLCitationParam +from .url_context_result import URLContextResult as URLContextResult +from .allowed_tools_param import AllowedToolsParam as AllowedToolsParam +from .audio_content_param import AudioContentParam as AudioContentParam +from .file_citation_param import FileCitationParam as FileCitationParam +from .image_content_param import ImageContentParam as ImageContentParam +from .speech_config_param import SpeechConfigParam as SpeechConfigParam +from .video_content_param import VideoContentParam as VideoContentParam +from .webhook_list_params import WebhookListParams as WebhookListParams +from .webhook_ping_params import WebhookPingParams as WebhookPingParams +from .dynamic_agent_config import DynamicAgentConfig as DynamicAgentConfig +from .google_search_result import GoogleSearchResult as GoogleSearchResult +from .place_citation_param import PlaceCitationParam as PlaceCitationParam +from .webhook_config_param import WebhookConfigParam as WebhookConfigParam +from .function_call_content import FunctionCallContent as FunctionCallContent +from .interaction_sse_event import InteractionSSEEvent as InteractionSSEEvent +from .thought_content_param import ThoughtContentParam as ThoughtContentParam +from .webhook_create_params import WebhookCreateParams as WebhookCreateParams +from .webhook_list_response import WebhookListResponse as WebhookListResponse +from .webhook_ping_response import WebhookPingResponse as WebhookPingResponse +from .webhook_update_params import WebhookUpdateParams as WebhookUpdateParams +from .document_content_param import DocumentContentParam as DocumentContentParam +from .interaction_get_params import InteractionGetParams as InteractionGetParams +from .function_result_content import FunctionResultContent as FunctionResultContent +from .generation_config_param import GenerationConfigParam as GenerationConfigParam +from .interaction_start_event import InteractionStartEvent as InteractionStartEvent +from .webhook_delete_response import WebhookDeleteResponse as WebhookDeleteResponse +from .file_search_call_content import FileSearchCallContent as FileSearchCallContent +from .google_maps_call_content import GoogleMapsCallContent as GoogleMapsCallContent +from .google_maps_result_param import GoogleMapsResultParam as GoogleMapsResultParam +from .tool_choice_config_param import ToolChoiceConfigParam as ToolChoiceConfigParam +from .url_context_call_content import URLContextCallContent as URLContextCallContent +from .url_context_result_param import URLContextResultParam as URLContextResultParam +from .interaction_create_params import InteractionCreateParams as InteractionCreateParams +from .interaction_status_update import InteractionStatusUpdate as InteractionStatusUpdate +from .deep_research_agent_config import DeepResearchAgentConfig as DeepResearchAgentConfig +from .dynamic_agent_config_param import DynamicAgentConfigParam as DynamicAgentConfigParam +from .file_search_result_content import FileSearchResultContent as FileSearchResultContent +from .google_maps_call_arguments import GoogleMapsCallArguments as GoogleMapsCallArguments +from .google_maps_result_content import GoogleMapsResultContent as GoogleMapsResultContent +from .google_search_call_content import GoogleSearchCallContent as GoogleSearchCallContent +from .google_search_result_param import GoogleSearchResultParam as GoogleSearchResultParam +from .interaction_complete_event import InteractionCompleteEvent as InteractionCompleteEvent +from .url_context_call_arguments import URLContextCallArguments as URLContextCallArguments +from .url_context_result_content import URLContextResultContent as URLContextResultContent +from .code_execution_call_content import CodeExecutionCallContent as CodeExecutionCallContent +from .function_call_content_param import FunctionCallContentParam as FunctionCallContentParam +from .google_search_call_arguments import GoogleSearchCallArguments as GoogleSearchCallArguments +from .google_search_result_content import GoogleSearchResultContent as GoogleSearchResultContent +from .mcp_server_tool_call_content import MCPServerToolCallContent as MCPServerToolCallContent +from .code_execution_call_arguments import CodeExecutionCallArguments as CodeExecutionCallArguments +from .code_execution_result_content import CodeExecutionResultContent as CodeExecutionResultContent +from .function_result_content_param import FunctionResultContentParam as FunctionResultContentParam +from .file_search_call_content_param import FileSearchCallContentParam as FileSearchCallContentParam +from .google_maps_call_content_param import GoogleMapsCallContentParam as GoogleMapsCallContentParam +from .mcp_server_tool_result_content import MCPServerToolResultContent as MCPServerToolResultContent +from .url_context_call_content_param import URLContextCallContentParam as URLContextCallContentParam +from .deep_research_agent_config_param import DeepResearchAgentConfigParam as DeepResearchAgentConfigParam +from .file_search_result_content_param import FileSearchResultContentParam as FileSearchResultContentParam +from .google_maps_call_arguments_param import GoogleMapsCallArgumentsParam as GoogleMapsCallArgumentsParam +from .google_maps_result_content_param import GoogleMapsResultContentParam as GoogleMapsResultContentParam +from .google_search_call_content_param import GoogleSearchCallContentParam as GoogleSearchCallContentParam +from .url_context_call_arguments_param import URLContextCallArgumentsParam as URLContextCallArgumentsParam +from .url_context_result_content_param import URLContextResultContentParam as URLContextResultContentParam +from .code_execution_call_content_param import CodeExecutionCallContentParam as CodeExecutionCallContentParam +from .google_search_call_arguments_param import GoogleSearchCallArgumentsParam as GoogleSearchCallArgumentsParam +from .google_search_result_content_param import GoogleSearchResultContentParam as GoogleSearchResultContentParam +from .mcp_server_tool_call_content_param import MCPServerToolCallContentParam as MCPServerToolCallContentParam +from .code_execution_call_arguments_param import CodeExecutionCallArgumentsParam as CodeExecutionCallArgumentsParam +from .code_execution_result_content_param import CodeExecutionResultContentParam as CodeExecutionResultContentParam +from .mcp_server_tool_result_content_param import MCPServerToolResultContentParam as MCPServerToolResultContentParam +from .webhook_rotate_signing_secret_params import WebhookRotateSigningSecretParams as WebhookRotateSigningSecretParams +from .webhook_rotate_signing_secret_response import ( + WebhookRotateSigningSecretResponse as WebhookRotateSigningSecretResponse, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8520f9e42598d65fe1f8d09c95b1012ddae399d4 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/allowed_tools.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/allowed_tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc569a95ff1a67bc103047c2e1a0b31399b14284 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/allowed_tools.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/allowed_tools_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/allowed_tools_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26798929036dc54ee6e8157056ce0f4ee2d319b0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/allowed_tools_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/annotation.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/annotation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8a6a885796fce10642a990a3d3281ad84e1ece8 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/annotation.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/annotation_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/annotation_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99469efbb90b2ea99352e74ef712e0754c14b187 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/annotation_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/audio_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/audio_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dcdfa8636587ea58cd8ad5e045bb8232002f521 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/audio_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/audio_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/audio_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b27f4ebac6f0dc9cbe187bbee1531c6fd830a3ad Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/audio_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_arguments.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_arguments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b79e8954a565074d2545bc9e819291fbcca3606 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_arguments.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_arguments_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_arguments_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e88c06c73f4681e122a05193603e34fd74fae375 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_arguments_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bef621f291f1246608e2e2676c68617db1f5ce7f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfd9735407be3647e5d6d3a6010dc2bfaef44d91 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_call_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_result_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_result_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2cca426023b70f4c0a56aab7e8d30ac861eb628 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_result_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_result_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_result_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea1d3c7ef9505c62a0f9fb533732a144077a3d52 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/code_execution_result_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e546b9ef25a0ed443918c6eecce5769377d5051 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_delta.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68d6e26a666bee9ad70844b6f954e0cce498dc78 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_delta.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5fb0dbdc7086787a771716e2586b5dfa72b33b4 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_start.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_start.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..205be955bb7b8ff2ef7381f443653acb27cf3c21 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_start.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_stop.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_stop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d54573b9f266a7dac83cfdbd9c03bc8a90cdb3e5 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/content_stop.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/deep_research_agent_config.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/deep_research_agent_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..936c176acce7683e2e8a12fd2660a21c4aafda10 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/deep_research_agent_config.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/deep_research_agent_config_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/deep_research_agent_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4c5c908897630e219a76f18f02ed5b57f3a4838 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/deep_research_agent_config_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/document_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/document_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18067276842a3200a8e7e3b92ce23c0a3297adb0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/document_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/document_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/document_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4302f274faf4ef08711caa62d9230dcc12575306 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/document_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/dynamic_agent_config.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/dynamic_agent_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..606463ece1c5221a43f2d7d6098edf462a8ab2a3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/dynamic_agent_config.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/dynamic_agent_config_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/dynamic_agent_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..038296f89dd4cc1c216d410354dc2fc63ffd75cb Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/dynamic_agent_config_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/error_event.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/error_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61732beca02293647b4d87a71777f3351ec55eab Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/error_event.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_citation.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_citation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e3d9d513da278b81be6978262501ae14fcd7ac8 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_citation.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_citation_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_citation_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd3e8de2c9ee27ea9fdfceb9a18bce306ae748a1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_citation_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_call_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_call_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aefd4701268ed8c2ee8ac92ca171ea9c96b397e1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_call_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_call_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_call_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8a17fd6bc2d2ca6d99073cf21a5c9de21aa8294 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_call_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_result_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_result_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cb860308898dd4645c4b13e35459be4c1a6e3eb Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_result_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_result_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_result_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a0c7209e0caa5287d8b057f56d4fc4a905607a7 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/file_search_result_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f410026f9d7b6c65ff5fbaf97e87e177c77157f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_call_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_call_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b41ecf4d61e8b86f28e0fb1bc78d36dd5c6c477 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_call_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_call_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_call_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96327d3c537ab91a89c369bed266d498b9404c7c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_call_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae05de0f4fb6f32a04be402e5b52de0b0b79a609 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_result_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_result_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c8a40bcc7a90746040c90e4bd0478b8bfbc7167 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_result_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_result_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_result_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70f6bdca469d20f52cbfb41612eafdf7b087a38f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/function_result_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/generation_config.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/generation_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b441cfa71713905ee1379d4a46889eb44709a85d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/generation_config.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/generation_config_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/generation_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4a523e56017b3a321844d9439b3f2756ab43759 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/generation_config_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_arguments.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_arguments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4c86527240da2db5e77a80e98c7cdd3b36dc803 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_arguments.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_arguments_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_arguments_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..640007777dbf9fd1e2b27b871535825b9ef39afd Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_arguments_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..177e042980751652d2f88cf2da27cb64eef7ad9a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73097f244fcf5b9314d344d37eca9790b65c3c74 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_call_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..456b0ad6253d2115a9c771eaba417fe6c4aa1a12 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e8032e27afa9c84f5835c7d316fc698feb0a3b6 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ac6cc44a861f3bedb2e30bff2c618fc71748e4 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a94db0de034b149de11d6fa9407a6bc7dcef1d1e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_maps_result_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_arguments.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_arguments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b03d9b493fa6e1503db0b502cfbad991b179d37 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_arguments.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_arguments_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_arguments_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9beea441318c598dfb5ec88159d184ae4f555c28 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_arguments_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa3fb150870f33d4d37572bfa475cce016adc266 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84d5aa38bd68ab69dd4b82eb2105b089fdb24580 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_call_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..441eab9957ef6cbc7e6e133098885dc815af524b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d22983738c273bfa7f90e6486c0debdd95a77ebd Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fd0728e421d5133e374b79625a0e2118a51dafb Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12b52e57aef703ba3dbc157dbee7d0827f6c1f1d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/google_search_result_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_config.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e91b31ad024ba7232ead71dc2a72b44c6dacb03 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_config.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_config_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de3620a0d198c712d84247a0b0aa9038f476de74 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_config_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72c25ad6f442cb556d10b0c63789cf26c41527dc Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ba562cda0aa89882121a23b32860fe721866cea Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/image_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd175fe9c111941d9adb0184d7707bdbbe295640 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_complete_event.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_complete_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08abe3f638615d5973f5db262b92cd3876329b45 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_complete_event.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_create_params.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a5a378bde0d3f56113d69907352f3989fb1fad3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_create_params.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_get_params.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_get_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b11f9f8d372e8cdc9c58d7b6eb500b91ab00357 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_get_params.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_sse_event.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_sse_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f652600f70f5892ef6b51bd7c3de9e4a0bd5db Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_sse_event.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_start_event.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_start_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..772558b4ef92eb9257f8d160fb4a32ca9c250270 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_start_event.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_status_update.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_status_update.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c752cd9fa908578a5bc17b92c4aadb57353d981f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/interaction_status_update.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c485934ff2aa763063a3c2490e2d524eef63a30c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d2623268c5142935b5465564136f1173264707d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6434f123084c313dc71c17a8c27f026e223d463 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfa80147ccb8a44990ac5a3c5fb72d867c331376 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/model.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfa43979cece0e15ec9749bc2c7d58e2ceeca502 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/model.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/model_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/model_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc37bcc66db9b0565c01ec0f3e2a5e04751c8188 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/model_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/place_citation.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/place_citation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73cbd611a5c2b3b01cb402d153c38ed72f7a6d69 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/place_citation.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/place_citation_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/place_citation_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fdc454631eb5d6188b4641cce3c14ccbeea1da5 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/place_citation_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/signing_secret.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/signing_secret.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd605f06eafcbc16aa731b8cda6ed20e7b1a497c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/signing_secret.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/speech_config.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/speech_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6b32a85d93438c2b14ffa54907a227f9fd6e895 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/speech_config.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/speech_config_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/speech_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3086709ae560188591d942580f44b51f7545468 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/speech_config_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/text_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/text_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caa89ab323a7b88c89fa45256b27cdd380eef23b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/text_content.cpython-312.pyc differ