def test_translate_text(self):
        # Setup Expected Response
        expected_response = {}
        expected_response = translation_service_pb2.TranslateTextResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = translate_v3beta1.TranslationServiceClient()

        # Setup Request
        contents = []
        target_language_code = "targetLanguageCode1323228230"
        parent = client.location_path("[PROJECT]", "[LOCATION]")

        response = client.translate_text(contents, target_language_code,
                                         parent)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = translation_service_pb2.TranslateTextRequest(
            contents=contents,
            target_language_code=target_language_code,
            parent=parent)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Example #2
0
    def translate_text(
        self,
        contents,
        target_language_code,
        mime_type=None,
        source_language_code=None,
        parent=None,
        model=None,
        glossary_config=None,
        retry=google.api_core.gapic_v1.method.DEFAULT,
        timeout=google.api_core.gapic_v1.method.DEFAULT,
        metadata=None,
    ):
        """
        Translates input text and returns translated text.

        Example:
            >>> from google.cloud import translate_v3beta1
            >>>
            >>> client = translate_v3beta1.TranslationServiceClient()
            >>>
            >>> # TODO: Initialize `contents`:
            >>> contents = []
            >>>
            >>> # TODO: Initialize `target_language_code`:
            >>> target_language_code = ''
            >>>
            >>> response = client.translate_text(contents, target_language_code)

        Args:
            contents (list[str]): Required. The content of the input in string format.
                We recommend the total content be less than 30k codepoints.
                Use BatchTranslateText for larger text.
            target_language_code (str): Required. The BCP-47 language code to use for translation of the input
                text, set to one of the language codes listed in Language Support.
            mime_type (str): Optional. The format of the source text, for example, "text/html",
                 "text/plain". If left blank, the MIME type defaults to "text/html".
            source_language_code (str): Optional. The BCP-47 language code of the input text if
                known, for example, "en-US" or "sr-Latn". Supported language codes are
                listed in Language Support. If the source language isn't specified, the API
                attempts to identify the source language automatically and returns the
                source language within the response.
            parent (str): Required. Location to make a regional or global call.

                Format: ``projects/{project-id}/locations/{location-id}``.

                For global calls, use ``projects/{project-id}/locations/global``.

                Models and glossaries must be within the same region (have same
                location-id), otherwise an INVALID\_ARGUMENT (400) error is returned.
            model (str): Optional. The ``model`` type requested for this translation.

                The format depends on model type:

                -  AutoML Translation models:
                   ``projects/{project-id}/locations/{location-id}/models/{model-id}``

                -  General (built-in) models:
                   ``projects/{project-id}/locations/{location-id}/models/general/nmt``,
                   ``projects/{project-id}/locations/{location-id}/models/general/base``

                For global (non-regionalized) requests, use ``location-id`` ``global``.
                For example,
                ``projects/{project-id}/locations/global/models/general/nmt``.

                If missing, the system decides which google base model to use.
            glossary_config (Union[dict, ~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig]): Optional. Glossary to be applied. The glossary must be within the same
                region (have the same location-id) as the model, otherwise an
                INVALID\_ARGUMENT (400) error is returned.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.translate_v3beta1.types.TranslateTextGlossaryConfig`
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.translate_v3beta1.types.TranslateTextResponse` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if "translate_text" not in self._inner_api_calls:
            self._inner_api_calls[
                "translate_text"] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.translate_text,
                    default_retry=self._method_configs["TranslateText"].retry,
                    default_timeout=self._method_configs["TranslateText"].
                    timeout,
                    client_info=self._client_info,
                )

        request = translation_service_pb2.TranslateTextRequest(
            contents=contents,
            target_language_code=target_language_code,
            mime_type=mime_type,
            source_language_code=source_language_code,
            parent=parent,
            model=model,
            glossary_config=glossary_config,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [("parent", parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls["translate_text"](request,
                                                       retry=retry,
                                                       timeout=timeout,
                                                       metadata=metadata)