Example #1
0
async def test_recognize_async(transport: str = "grpc_asyncio",
                               request_type=cloud_speech.RecognizeRequest):
    client = SpeechAsyncClient(
        credentials=credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Everything is optional in proto3 as far as the runtime is concerned,
    # and we are mocking out the actual API, so just send an empty request.
    request = request_type()

    # Mock the actual call within the gRPC stub, and fake the request.
    with mock.patch.object(type(client.transport.recognize),
                           "__call__") as call:
        # Designate an appropriate return value for the call.
        call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
            cloud_speech.RecognizeResponse())

        response = await client.recognize(request)

        # Establish that the underlying gRPC stub method was called.
        assert len(call.mock_calls)
        _, args, _ = call.mock_calls[0]

        assert args[0] == cloud_speech.RecognizeRequest()

    # Establish that the response is the type that we expect.
    assert isinstance(response, cloud_speech.RecognizeResponse)
Example #2
0
def test_recognize_flattened_error():
    client = SpeechClient(credentials=credentials.AnonymousCredentials(), )

    # Attempting to call a method with both a request object and flattened
    # fields is an error.
    with pytest.raises(ValueError):
        client.recognize(
            cloud_speech.RecognizeRequest(),
            config=cloud_speech.RecognitionConfig(
                encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16
            ),
            audio=cloud_speech.RecognitionAudio(content=b"content_blob"),
        )
Example #3
0
    def recognize(
        self,
        request: cloud_speech.RecognizeRequest = None,
        *,
        config: cloud_speech.RecognitionConfig = None,
        audio: cloud_speech.RecognitionAudio = None,
        retry: retries.Retry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> cloud_speech.RecognizeResponse:
        r"""Performs synchronous speech recognition: receive
        results after all audio has been sent and processed.

        Args:
            request (google.cloud.speech_v1.types.RecognizeRequest):
                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, str]]): Strings which should be
                sent along with the request as metadata.

        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.
        # Sanity check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([config, audio])
        if request is not None and has_flattened_params:
            raise ValueError("If the `request` argument is set, then none of "
                             "the individual field arguments should be set.")

        # Minor optimization to avoid making a copy if the user passes
        # in a cloud_speech.RecognizeRequest.
        # There's no risk of modifying the input as we've already verified
        # there are no flattened fields.
        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]

        # Send the request.
        response = rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response
    async def recognize(
        self,
        request: cloud_speech.RecognizeRequest = None,
        *,
        config: cloud_speech.RecognitionConfig = None,
        audio: cloud_speech.RecognitionAudio = None,
        retry: retries.Retry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> cloud_speech.RecognizeResponse:
        r"""Performs synchronous speech recognition: receive
        results after all audio has been sent and processed.

        Args:
            request (:class:`google.cloud.speech_v1.types.RecognizeRequest`):
                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.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.cloud.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.
        # Sanity check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([config, audio])
        if request is not None and has_flattened_params:
            raise ValueError("If the `request` argument is set, then none of "
                             "the individual field arguments should be set.")

        request = 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 = gapic_v1.method_async.wrap_method(
            self._client._transport.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=DEFAULT_CLIENT_INFO,
        )

        # Send the request.
        response = await rpc(
            request,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )

        # Done; return the response.
        return response