Ejemplo n.º 1
0
 async def translate(self, text, lang='en'):
     result = await self.client.translate_text(
         TranslateTextRequest(
             **{
                 "parent": f"projects/{CLOUD_PROJ_ID}/locations/global",
                 "contents": [text],
                 "mime_type":
                 "text/plain",  # mime types: text/plain, text/html
                 "target_language_code": lang,
             }))
     translation = result.translations[0]
     return translation.translated_text, translation.detected_language_code
Ejemplo n.º 2
0
    async def translate_text(
        self,
        request: translation_service.TranslateTextRequest = None,
        *,
        parent: str = None,
        target_language_code: str = None,
        contents: Sequence[str] = None,
        model: str = None,
        mime_type: str = None,
        source_language_code: str = None,
        retry: retries.Retry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> translation_service.TranslateTextResponse:
        r"""Translates input text and returns translated text.

        Args:
            request (:class:`~.translation_service.TranslateTextRequest`):
                The request object. The request message for synchronous
                translation.
            parent (:class:`str`):
                Required. Project or location to make a call. Must refer
                to a caller's project.

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

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

                Non-global location is required for requests using
                AutoML models or custom glossaries.

                Models and glossaries must be within the same region
                (have same location-id), otherwise an INVALID_ARGUMENT
                (400) error is returned.
                This corresponds to the ``parent`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            target_language_code (:class:`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.
                This corresponds to the ``target_language_code`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            contents (:class:`Sequence[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.
                This corresponds to the ``contents`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            model (:class:`str`):
                Optional. The ``model`` type requested for this
                translation.

                The format depends on model type:

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

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

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

                If missing, the system decides which google base model
                to use.
                This corresponds to the ``model`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            mime_type (:class:`str`):
                Optional. The format of the source
                text, for example, "text/html",
                "text/plain". If left blank, the MIME
                type defaults to "text/html".
                This corresponds to the ``mime_type`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            source_language_code (:class:`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.
                This corresponds to the ``source_language_code`` 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:
            ~.translation_service.TranslateTextResponse:

        """
        # 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([
                parent,
                target_language_code,
                contents,
                model,
                mime_type,
                source_language_code,
        ]):
            raise ValueError("If the `request` argument is set, then none of "
                             "the individual field arguments should be set.")

        request = translation_service.TranslateTextRequest(request)

        # If we have keyword arguments corresponding to fields on the
        # request, apply these.

        if parent is not None:
            request.parent = parent
        if target_language_code is not None:
            request.target_language_code = target_language_code
        if contents is not None:
            request.contents = contents
        if model is not None:
            request.model = model
        if mime_type is not None:
            request.mime_type = mime_type
        if source_language_code is not None:
            request.source_language_code = source_language_code

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = gapic_v1.method_async.wrap_method(
            self._client._transport.translate_text,
            default_timeout=None,
            client_info=_client_info,
        )

        # 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), )), )

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

        # Done; return the response.
        return response