o
    i                     @   sR  d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZmZmZmZmZmZmZmZmZmZmZmZmZ d dlZd dlmZ d dlmZ d dlmZ d dlm Z! d d	l"m#Z$ d d
l%m&Z& d dl'm(Z( d dl)m*Z* d dl+m,Z, d dl-m.Z/ zee!j0ej1j2df Z3W n e4y   ee!j0e5df Z3Y nw z
d dlm6Z6 dZ7W n e8y   dZ7Y nw e9e:Z;d dl<m=  m>Z> d dl?m=  m@Z@ d dlAmB  mCZC d dlDmE  mFZF d dlGmHZH d dlImJZJ ddlKmLZLmMZM ddlNmOZO ddlPmQZQ ddlRmSZS G dd deTZUG dd deUdZVejWjXe/jYdZLeZeLdr%ejBjYeL_[dZ\dS )     N)OrderedDict)
HTTPStatus)CallableDictIterableIteratorMappingMutableMappingMutableSequenceOptionalSequenceTupleTypeUnioncast)client_options)
exceptions)gapic_v1)retry)credentials)MutualTLSChannelError)mtls)SslCredentials)service_account)gapic_version)client_loggingTF)operations_pb2)cloud_speech   )DEFAULT_CLIENT_INFOSpeechTransport)SpeechGrpcTransport)SpeechGrpcAsyncIOTransport)SpeechRestTransportc                   @   sL   e Zd ZdZe Zeed< eed< eed< 	d
de	e
 dee fdd	ZdS )SpeechClientMetazMetaclass for the Speech client.

    This provides class-level methods for building and retrieving
    support objects (e.g. transport) without polluting the client instance
    objects.
    grpcgrpc_asynciorestNlabelreturnc                 C   s    |r| j | S tt| j  S )a  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.
        )_transport_registrynextitervalues)clsr(    r/   a/home/ubuntu/.local/lib/python3.10/site-packages/google/cloud/speech_v1/services/speech/client.pyget_transport_class]   s   
z$SpeechClientMeta.get_transport_classN)__name__
__module____qualname____doc__r   r*   r!   r"   r#   r   strr   r    r1   r/   r/   r/   r0   r$   P   s    r$   c                   @   s  e Zd ZdZedd ZdZeeZdZ	dZ
edd Zed	efd
dZedefddZeZedefddZededededefddZededeeef fddZededededefddZededeeef fddZededefd d!Zededeeef fd"d#Zed$edefd%d&Zededeeef fd'd(Zed)edefd*d+Zededeeef fd,d-Zededefd.d/Z ededeeef fd0d1Z!edededefd2d3Z"ededeeef fd4d5Z#e	6dld7e$e%j& fd8d9Z'ed:d; Z(ed<d= Z)ed>d? Z*ed@e$e dAe$e defdBdCZ+dDdE Z,dFe-j.dd6fdGdHZ/edIdJ Z0edefdKdLZ1d6d6d6e2dMdNe$e3j4 dOe$e5eee6dPef f  d7e$e5e%j&ef  dQe7j8j9dd6f
dRdSZ:	6dld6d6e7j;j<e7j;j<dTdUdVe$e5e=j>ef  dWe$e=j? dXe$e=j@ dYeAdZe5eBeCf d[eDeEee5eeFf f  de=jGfd\d]ZH	6dld6d6e7j;j<e7j;j<dTdUdVe$e5e=jIef  dWe$e=j? dXe$e=j@ dYeAdZe5eBeCf d[eDeEee5eeFf f  deJjKfd^d_ZL	6dle7j;j<e7j;j<dTd`dae$eMe=jN  dYeAdZe5eBeCf d[eDeEee5eeFf f  deOe=jP f
dbdcZQdmdddeZRdfdg ZS	6dle7j;j<e7j;j<dTd`dVe$eTjU dYeAdZe5eBeCf d[eDeEee5eeFf f  deTjVf
dhdiZW	6dle7j;j<e7j;j<dTd`dVe$eTjX dYeAdZe5eBeCf d[eDeEee5eeFf f  deTjKf
djdkZYd6S )nSpeechClientz0Service that implements Google Cloud Speech API.c                 C   sT   | s| S t d}|| }| \}}}}|s|s| S |r$| ddS | ddS )a\  Converts api endpoint to mTLS endpoint.

        Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
        "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
        Args:
            api_endpoint (Optional[str]): the api endpoint to convert.
        Returns:
            str: converted mTLS api endpoint.
        z[(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?zsandbox.googleapis.comzmtls.sandbox.googleapis.comz.googleapis.comz.mtls.googleapis.com)recompilematchgroupsreplace)api_endpointmtls_endpoint_remnamer   sandboxgoogledomainr/   r/   r0   _get_default_mtls_endpointv   s   
z'SpeechClient._get_default_mtls_endpointzspeech.googleapis.comzspeech.{UNIVERSE_DOMAIN}zgoogleapis.comc                  C   s:   t tdr	t S tdd } | dvrtd| dkS )a  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.)
        should_use_client_cert!GOOGLE_API_USE_CLIENT_CERTIFICATEfalse)truerG   zYEnvironment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`rH   )hasattrr   rE   osgetenvlower
ValueError)use_client_cert_strr/   r/   r0   _use_client_cert_effective   s   
z'SpeechClient._use_client_cert_effectiveinfoc                 O   "   t j|}||d< | |i |S )av  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.
        r   )r   Credentialsfrom_service_account_info)r.   rP   argskwargsr   r/   r/   r0   rS      s   z&SpeechClient.from_service_account_infofilenamec                 O   rQ   )a  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.
        r   )r   rR   from_service_account_file)r.   rV   rT   rU   r   r/   r/   r0   rW      s   z&SpeechClient.from_service_account_filer)   c                 C      | j S )zReturns the transport used by the client instance.

        Returns:
            SpeechTransport: The transport used by the client
                instance.
        )
_transportselfr/   r/   r0   	transport   s   zSpeechClient.transportprojectlocationcustom_classc                 C      dj | ||dS )z.Returns a fully-qualified custom_class string.zDprojects/{project}/locations/{location}/customClasses/{custom_class}r]   r^   r_   formatra   r/   r/   r0   custom_class_path   
   zSpeechClient.custom_class_pathpathc                 C      t d| }|r| S i S )z7Parses a custom_class path into its component segments.z[^projects/(?P<project>.+?)/locations/(?P<location>.+?)/customClasses/(?P<custom_class>.+?)$r9   r;   	groupdictrf   r@   r/   r/   r0   parse_custom_class_path   
   z$SpeechClient.parse_custom_class_path
phrase_setc                 C   r`   )z,Returns a fully-qualified phrase_set string.z?projects/{project}/locations/{location}/phraseSets/{phrase_set}r]   r^   rm   rb   rn   r/   r/   r0   phrase_set_path   re   zSpeechClient.phrase_set_pathc                 C   rg   )z5Parses a phrase_set path into its component segments.zV^projects/(?P<project>.+?)/locations/(?P<location>.+?)/phraseSets/(?P<phrase_set>.+?)$rh   rj   r/   r/   r0   parse_phrase_set_path  rl   z"SpeechClient.parse_phrase_set_pathbilling_accountc                 C      dj | dS )z1Returns a fully-qualified billing_account string.z!billingAccounts/{billing_account}rq   rb   rs   r/   r/   r0   common_billing_account_path     z(SpeechClient.common_billing_account_pathc                 C   rg   )z9Parse a billing_account path into its component segments.z*^billingAccounts/(?P<billing_account>.+?)$rh   rj   r/   r/   r0   !parse_common_billing_account_path     z.SpeechClient.parse_common_billing_account_pathfolderc                 C   rr   )z(Returns a fully-qualified folder string.zfolders/{folder}rx   rb   ry   r/   r/   r0   common_folder_path#  ru   zSpeechClient.common_folder_pathc                 C   rg   )z0Parse a folder path into its component segments.z^folders/(?P<folder>.+?)$rh   rj   r/   r/   r0   parse_common_folder_path,  rw   z%SpeechClient.parse_common_folder_pathorganizationc                 C   rr   )z.Returns a fully-qualified organization string.zorganizations/{organization}r|   rb   r}   r/   r/   r0   common_organization_path2  ru   z%SpeechClient.common_organization_pathc                 C   rg   )z6Parse a organization path into its component segments.z%^organizations/(?P<organization>.+?)$rh   rj   r/   r/   r0   parse_common_organization_path;  rw   z+SpeechClient.parse_common_organization_pathc                 C   rr   )z)Returns a fully-qualified project string.zprojects/{project}r]   rb   r   r/   r/   r0   common_project_pathA  ru   z SpeechClient.common_project_pathc                 C   rg   )z1Parse a project path into its component segments.z^projects/(?P<project>.+?)$rh   rj   r/   r/   r0   parse_common_project_pathJ  rw   z&SpeechClient.parse_common_project_pathc                 C   s   dj | |dS )z*Returns a fully-qualified location string.z'projects/{project}/locations/{location}r]   r^   rb   r   r/   r/   r0   common_location_pathP  s   z!SpeechClient.common_location_pathc                 C   rg   )z2Parse a location path into its component segments.z7^projects/(?P<project>.+?)/locations/(?P<location>.+?)$rh   rj   r/   r/   r0   parse_common_location_path[  rw   z'SpeechClient.parse_common_location_pathNr   c                 C   s   t dt |du rt }t }tdd}|dvr t	dd}|r3|j
r+|j
}nt r3t }|jdur?|j}||fS |dksI|dkrP|rP| j}||fS | j}||fS )a  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.
        zWget_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.NGOOGLE_API_USE_MTLS_ENDPOINTautor   neveralwaysWEnvironment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`r   )warningswarnDeprecationWarningclient_options_libClientOptionsr8   rO   rJ   rK   r   client_cert_sourcer   has_default_client_cert_sourcedefault_client_cert_sourcer>   DEFAULT_MTLS_ENDPOINTDEFAULT_ENDPOINT)r.   r   use_client_certuse_mtls_endpointr   r>   r/   r/   r0   !get_mtls_endpoint_and_cert_sourcea  s6   #
z.SpeechClient.get_mtls_endpoint_and_cert_sourcec                  C   s<   t  } tdd }td}|dvrtd| ||fS )a  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"].
        r   r   GOOGLE_CLOUD_UNIVERSE_DOMAINr   r   )r8   rO   rJ   rK   rL   r   )r   r   universe_domain_envr/   r/   r0   _read_environment_variables  s   

z(SpeechClient._read_environment_variablesc                 C   s(   d}|r| r
| }|S t  rt  }|S )aZ  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.
        N)r   r   r   )provided_cert_sourceuse_cert_flagr   r/   r/   r0   _get_client_cert_source  s   z$SpeechClient._get_client_cert_sourcec                 C   s^   | dur| }|S |dks|dkr&|r&t j}||kr!td| dt j}|S t jj|d}|S )a  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.
        Nr   r   z1mTLS is not supported in any universe other than .)UNIVERSE_DOMAIN)r8   _DEFAULT_UNIVERSEr   r   _DEFAULT_ENDPOINT_TEMPLATErc   )api_overrider   universe_domainr   r>   _default_universer/   r/   r0   _get_api_endpoint  s    
zSpeechClient._get_api_endpointclient_universe_domainr   c                 C   s<   t j}| dur
| }n|dur|}t| dkrtd|S )a  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.
        Nr   z*Universe Domain cannot be an empty string.)r8   r   lenstriprM   )r   r   r   r/   r/   r0   _get_universe_domain  s   z!SpeechClient._get_universe_domainc                 C   s   dS )zValidates 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.
        Tr/   rZ   r/   r/   r0   _validate_universe_domain
  s   z&SpeechClient._validate_universe_domainerrorc                 C   sf   |j tjtjtjfvrdS | jj}t|dsdS | }|r/t|j	dr1|j	
t| dS dS dS )zAdds 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.
        Nget_cred_infoappend)coder   UNAUTHORIZED	FORBIDDEN	NOT_FOUNDrY   _credentialsrI   r   _detailsr   jsondumps)r[   r   cred	cred_infor/   r/   r0   _add_cred_info_for_auth_errors  s   
z+SpeechClient._add_cred_info_for_auth_errorsc                 C   rX   )zReturn the API endpoint used by the client instance.

        Returns:
            str: The API endpoint used by the client instance.
        )_api_endpointrZ   r/   r/   r0   r>   2     zSpeechClient.api_endpointc                 C   rX   )zReturn the universe domain used by the client instance.

        Returns:
            str: The universe domain used by the client instance.
        )_universe_domainrZ   r/   r/   r0   r   ;  r   zSpeechClient.universe_domain)r   r\   r   client_infor   r\   .r   c          
      C   sX  || _ t| j trt| j | _ | j du rt | _ ttj| j | _ t| j dd}t	 \| _
| _| _t| j j| j
| _t|| j| _d| _d| _trQt  t| j dd}|r`|r`tdt|t}|r|so| j jso|rstd| j jr{tdtt|| _| jj| _| jpt| j j| j| j| j| _|sddl}|rt |j!j"d	r|j!j"#|}t|t$s|du rt%|ntt&d
tf |}	|	|| j j| j| j j| j| j j'|d| j j(d	| _dt$| jvr&tr(t)*t+j,r*t)j-dt | jdrdt| jj.ddt/| jj.j0 dt/| jj.j1 t| j2j.ddd  dndddd dS dS dS dS )ao  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.
        Nr   Fapi_keyz=client_options.api_key and credentials are mutually exclusivezFWhen providing a transport instance, provide its credentials directly.zAWhen providing a transport instance, provide its scopes directly.r   get_api_key_credentials.T)	r   credentials_filehostscopesclient_cert_source_for_mtlsquota_project_idr   always_use_jwt_accessapi_audienceasyncz5Created client `google.cloud.speech_v1.SpeechClient`.r   zgoogle.cloud.speech.v1.Speech r   r   c                   S   s   d S r2   r/   r/   r/   r/   r0   <lambda>  s    z'SpeechClient.__init__.<locals>.<lambda>)serviceNameuniverseDomaincredentialsTypecredentialsInfo)r   r   )extra)3_client_options
isinstancedictr   	from_dictr   r   getattrr8   r   _use_client_cert_use_mtls_endpoint_universe_domain_envr   r   _client_cert_sourcer   r   r   _is_universe_domain_validCLIENT_LOGGING_SUPPORTEDr   initialize_loggingrM   r    r   r   rY   r   r   r>   google.auth._defaultrI   auth_defaultr   r7   r1   r   r   r   _LOGGERisEnabledForstd_loggingDEBUGdebugr   typer4   r5   r\   )
r[   r   r\   r   r   universe_domain_optapi_key_valuetransport_providedgoogletransport_initr/   r/   r0   __init__D  s   ;









 
zSpeechClient.__init__r/   )configaudior   timeoutmetadatarequestr   r   r   r   r   c                C   s   ||g}t dd |D dk}|dur|rtdt|tjs2t|}|dur+||_|dur2||_| jj| jj	 }	| 
  |	||||d}
|
S )a  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.

        c                 S      g | ]}|d ur|qS r2   r/   .0paramr/   r/   r0   
<listcomp>E      z*SpeechClient.recognize.<locals>.<listcomp>r   N\If the `request` argument is set, then none of the individual field arguments should be set.r   r   r   )r   rM   r   r   RecognizeRequestr   r   rY   _wrapped_methods	recognizer   r[   r   r   r   r   r   r   flattened_paramshas_flattened_paramsrpcresponser/   r/   r0   r     s,   S
zSpeechClient.recognizec                C   s   ||g}t dd |D dk}|dur|rtdt|tjs2t|}|dur+||_|dur2||_| jj| jj	 }	| 
  |	||||d}
tj|
| jjtjtjd}
|
S )aO  Performs asynchronous speech recognition: receive results via
        the google.longrunning.Operations interface. Returns either an
        ``Operation.error`` or an ``Operation.response`` which contains
        a ``LongRunningRecognizeResponse`` message. For more information
        on asynchronous speech recognition, see the
        `how-to <https://cloud.google.com/speech-to-text/docs/async-recognize>`__.

        .. code-block:: python

            # This snippet has been automatically generated and should be regarded as a
            # code template only.
            # It will require modifications to work:
            # - It may require correct/in-range values for request initialization.
            # - It may require specifying regional endpoints when creating the service
            #   client as shown in:
            #   https://googleapis.dev/python/google-api-core/latest/client_options.html
            from google.cloud import speech_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.

        c                 S   r   r2   r/   r   r/   r/   r0   r     r   z7SpeechClient.long_running_recognize.<locals>.<listcomp>r   Nr   r   )metadata_type)r   rM   r   r   LongRunningRecognizeRequestr   r   rY   r   long_running_recognizer   	operation
from_gapicoperations_clientLongRunningRecognizeResponseLongRunningRecognizeMetadatar   r/   r/   r0   r  j  s8   `
z#SpeechClient.long_running_recognizer   requestsc                C   s,   | j j| j j }|   |||||d}|S )ar  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.

        r   )rY   r   streaming_recognizer   )r[   r  r   r   r   r   r   r/   r/   r0   r    s    z SpeechClient.streaming_recognizec                 C   s   | S r2   r/   rZ   r/   r/   r0   	__enter__  s   zSpeechClient.__enter__c                 C   s   | j   dS )a  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!
        N)r\   close)r[   r   value	tracebackr/   r/   r0   __exit__  s   zSpeechClient.__exit__c             
   C      t |trtjdi |}| jj| jj }t|tj	
d|jfff }|   z|||||d}|W S  tjyG } z| | |d}~ww )a  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.
        rA   r   Nr/   )r   r   r   ListOperationsRequestrY   r   list_operationstupler   routing_headerto_grpc_metadatarA   r   core_exceptionsGoogleAPICallErrorr   r[   r   r   r   r   r   r   er/   r/   r0   r    (   

zSpeechClient.list_operationsc             
   C   r  )aS  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.
        rA   r   Nr/   )r   r   r   GetOperationRequestrY   r   get_operationr  r   r  r  rA   r   r  r  r   r  r/   r/   r0   r    r  zSpeechClient.get_operationr2   )r)   r8   )Zr3   r4   r5   r6   staticmethodrD   r   __func__r   r   r   rO   classmethodr   rS   r7   rW   from_service_account_jsonpropertyr    r\   rd   r   rk   ro   rp   rt   rv   rz   r{   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r>   r   r   ga_credentialsrR   r   r   r   r   
ClientInfor   methodDEFAULTr   r   RecognitionConfigRecognitionAudioOptionalRetryfloatobjectr   r   bytesRecognizeResponser   r   r  	Operationr  r   StreamingRecognizeRequestr   StreamingRecognizeResponser  r	  r  r   r  ListOperationsResponser  r  r  r/   r/   r/   r0   r8   s   s   

	
C


!

	
 /
	
|
	
 

 


=
r8   )	metaclassprotobuf_runtime_version)r8   )]r   loggingr   rJ   r9   r   collectionsr   httpr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   google.protobufr   google.api_corer   r   r   r  r   r   retriesgoogle.authr   r   google.auth.exceptionsr   google.auth.transportr   google.auth.transport.grpcr   google.oauth2r   google.cloud.speech_v1r   package_versionRetryr"  _MethodDefaultr&  AttributeErrorr(  r   r   ImportError	getLoggerr3   r   google.api_core.operationapi_corer  google.api_core.operation_asyncoperation_asyncgoogle.protobuf.duration_pb2protobufduration_pb2google.rpc.status_pb2r   
status_pb2google.longrunningr   google.cloud.speech_v1.typesr   transports.baser   r    transports.grpcr!   transports.grpc_asyncior"   transports.restr#   r   r$   r8   r   r!  __version__rI   r0  __all__r/   r/   r/   r0   <module>   st   <
#         /
