Exemplo n.º 1
0
async def test_long_running_recognize_async(
    transport: str = "grpc_asyncio",
    request_type=cloud_speech.LongRunningRecognizeRequest,
):
    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.long_running_recognize),
                           "__call__") as call:
        # Designate an appropriate return value for the call.
        call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
            operations_pb2.Operation(name="operations/spam"))

        response = await client.long_running_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.LongRunningRecognizeRequest()

    # Establish that the response is the type that we expect.
    assert isinstance(response, future.Future)
Exemplo n.º 2
0
def test_long_running_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.long_running_recognize(
            cloud_speech.LongRunningRecognizeRequest(),
            config=cloud_speech.RecognitionConfig(
                encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16
            ),
            audio=cloud_speech.RecognitionAudio(content=b"content_blob"),
        )
Exemplo n.º 3
0
    def long_running_recognize(
            self,
            request: cloud_speech.LongRunningRecognizeRequest = 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]] = (),
    ) -> 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 <https://cloud.google.com/speech-to-text/docs/async-recognize>`__.

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

        Returns:
            google.api_core.operation.Operation:
                An object representing a long-running operation.

                The result type for the operation will be :class:`google.cloud.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.
        # 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.LongRunningRecognizeRequest.
        # There's no risk of modifying the input as we've already verified
        # there are no flattened fields.
        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]

        # 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
Exemplo n.º 4
0
    async def long_running_recognize(
        self,
        request: cloud_speech.LongRunningRecognizeRequest = 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]] = (),
    ) -> operation_async.AsyncOperation:
        r"""Performs asynchronous speech recognition: receive results via
        the google.longrunning.Operations interface. Returns either an
        ``Operation.error`` or an ``Operation.response`` which contains
        a ``LongRunningRecognizeResponse`` message. For more information
        on asynchronous speech recognition, see the
        `how-to <https://cloud.google.com/speech-to-text/docs/async-recognize>`__.

        Args:
            request (:class:`~.cloud_speech.LongRunningRecognizeRequest`):
                The request object. The top-level message sent by the
                client for the `LongRunningRecognize` method.
            config (:class:`~.cloud_speech.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:`~.cloud_speech.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:
            ~.operation_async.AsyncOperation:
                An object representing a long-running operation.

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

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

        # 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