翻译文本(高级版)

Cloud Translation 高级版支持以下功能:使用自定义 AutoML Translation 模型翻译文本,以及创建术语表以确保 Cloud Translation API 翻译特定于客户的网域术语。

如果要为项目使用 AutoML 自定义模型,您必须启用 AutoML API (automl.googleapis.com)。 如需了解有关安装 Cloud SDK、使用服务帐号设置项目以及获取访问令牌的说明,请参阅设置页面。如果您计划使用术语表或批处理功能,还需要创建 Cloud Storage 存储分区,并将其访问权限授予您的服务帐号。

准备工作

在开始使用 Cloud Translation API 之前,您必须有一个启用了 Cloud Translation API 的项目,以及相应的凭据。您还可以安装常用编程语言的客户端库,以便调用 API。

如需了解详情,请参阅设置页面。

比较模型

向 Cloud Translation 高级版发出翻译请求时,您可以指定要使用的翻译模型。如果未指定模型,则在语言对受支持的情况下,系统会使用 nmt 模型,否则会使用 PBMT 模型。

模型 最适合的使用场景 示例
神经机器翻译 (NMT) 模型

诸如并非针对某个领域的公共网站内容之类的一般文本用例,例如新闻文章。

新闻文章、社交媒体、聊天应用、评论

基于短语的机器翻译 (PBMT) 模型 NMT 通常可以提供更好的译文。默认情况下,如果某个语言对不存在 NMT 模型,则系统可能会使用 PBMT。 使用时机:当 NMT 不可用时。
AutoML 翻译模型 特定领域的文本。客户提供特定于其用例的训练数据,针对给定语言对自定义用于特定领域的 Google 基本模型。 财经新闻、技术文档、使用该领域独有的术语和行话的任何文本。

您可以使用翻译模型的 ID 指定相应的翻译模型。对于常规的 Google 模型,NMT 模型和 PBMT 模型的 ID 分别为 general/nmtgeneral/base。如需了解 AutoML Translation 模型 ID,请参阅下一部分。

翻译文本

输入文本可以是纯文本或 HTML。Cloud Translation API 不会翻译输入文本中的任何 HTML 标记,只会翻译出现在标记之间的文本。由于源语言和目标语言之间存在差异,输出会尽可能地保留(未翻译的)HTML 标记,并将翻译的文本置于标记之间。 由于翻译中的词序更改,输出中 HTML 标记的顺序可能与输入文本中的顺序不同。

翻译输入字符串

REST 和命令行

要翻译文本,请发出 POST 请求,并在请求正文中提供 JSON,以标识要翻译的源语言 (source_language_code)、目标语言 (target_language_code) 以及要翻译的文本 (contents)。您可以提供多个要翻译的文本字符串,只需在 JSON 代码中加入这些字符串即可(请参阅示例)。可以使用相应的 ISO-639-1 代码来标识源语言和目标语言。

下面显示了使用 curl 或 PowerShell 的 POST 请求的示例。该示例使用通过 Google Cloud Cloud SDK 为项目设置的服务帐号的访问令牌。如需了解有关安装 Cloud SDK、使用服务帐号设置项目以及获取访问令牌的说明,请参阅设置页面。

在使用下面的请求数据之前,请先进行以下替换:

  • project-number-or-id:您的 Google Cloud 项目编号或 ID

HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/project-number-or-id:translateText

请求 JSON 正文:

{
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": ["Dr. Watson, come here!", "Bring me some coffee!"]
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id:translateText

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id:translateText " | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应:

{
  "translations": [
    {
      "translatedText": "Доктор Ватсон, иди сюда!",
    },
    {
      "translatedText": "Принеси мне кофе!",
    }
  ]
}

translations 数组包含两个 translatedText 字段,其中译文以请求的 targetLanguageCode 语言(ru:俄语)提供。译文的排列顺序与相应源数组在请求中的顺序相同。

C#

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Translation C# API 参考文档


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class TranslateText
    {
        /// <summary>
        /// Translates a given text to a target language.
        /// </summary>
        /// <param name="text">The content to translate.</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void TranslateTextSample(string text = "[TEXT_TO_TRANSLATE]",
            string targetLanguage = "ja",
            string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, "global"),
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);
            // Display the translation for each input text provided
            foreach (Translation translation in response.Translations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
    }

Go

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Translation Go API 参考文档

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// translateText translates input text and returns translated text.
func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
	// projectID := "my-project-id"
	// sourceLang := "en-US"
	// targetLang := "fr"
	// text := "Text you wish to translate"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/global", projectID),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
	}

	resp, err := client.TranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("TranslateText: %v", err)
	}

	// Display the translation for each input text provided
	for _, translation := range resp.GetTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

在试用此示例之前,请按照 《Translation 快速入门:使用客户端库》 中的 Java 设置说明进行操作。如需了解详情,请参阅 Translation Java API 参考文档

import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextRequest;
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class TranslateText {

  public static void translateText() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String targetLanguage = "your-target-language";
    String text = "your-text";
    translateText(projectId, targetLanguage, text);
  }

  // Translating Text
  public static void translateText(String projectId, String targetLanguage, String text)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "global");

      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain")
              .setTargetLanguageCode(targetLanguage)
              .addContents(text)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getTranslationsList()) {
        System.out.printf("Translated text: %s\n", translation.getTranslatedText());
      }
    }
  }
}

Node.js

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Translation Node.js API 参考文档

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';
// const text = 'text to translate';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateText() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'sr-Latn',
  };

  try {
    // Run request
    const [response] = await translationClient.translateText(request);

    for (const translation of response.translations) {
      console.log(`Translation: ${translation.translatedText}`);
    }
  } catch (error) {
    console.error(error.details);
  }
}

translateText();

PHP

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 PHP 设置说明进行操作。如需了解详情,请参阅 Translation PHP API 参考文档

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $targetLanguage = 'fr';
// $projectId = '[Google Cloud Project ID]';
$contents = [$text];
$formattedParent = $translationServiceClient->locationName($projectId, 'global');

try {
    $response = $translationServiceClient->translateText(
        $contents,
        $targetLanguage,
        $formattedParent
    );
    // Display the translation for each input text provided
    foreach ($response->getTranslations() as $translation) {
        printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
    }
} finally {
    $translationServiceClient->close();
}

Python

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Translation Python API 参考文档

from google.cloud import translate

def translate_text(text="YOUR_TEXT_TO_TRANSLATE", project_id="YOUR_PROJECT_ID"):
    """Translating Text."""

    client = translate.TranslationServiceClient()

    location = "global"

    parent = f"projects/{project_id}/locations/{location}"

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.translate_text(
        request={
            "parent": parent,
            "contents": [text],
            "mime_type": "text/plain",  # mime types: text/plain, text/html
            "source_language_code": "en-US",
            "target_language_code": "fr",
        }
    )

    # Display the translation for each input text provided
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))

Ruby

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。如需了解详情,请参阅 Translation Ruby API 参考文档

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"

# The content to translate in string format
contents = ["Hello, world!"]
# Required. The BCP-47 language code to use for translation.
target_language = "fr"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id

response = client.translate_text parent:               parent,
                                 contents:             contents,
                                 target_language_code: target_language

# Display the translation for each input text provided
response.translations.each do |translation|
  puts "Translated text: #{translation.translated_text}"
end

使用 AutoML Translation 自定义模型翻译文本

REST 和命令行

以下示例使用模型 ID 为 TRL1395675701985363739 的 AutoML Translation 模型翻译文本。您可以从 AutoML Translation 界面上的模型列表中获取 AutoML Translation 模型的 ID,也可以从在训练模型时收到的 API 响应中获取此 ID。

您必须确保已为项目启用了 Cloud AutoML API。将 AutoML 模型与 Cloud Translation API 搭配使用时,必须确保这一点。请参阅此使用入门文档,以启用该 API。

在使用下面的请求数据之前,请先进行以下替换:

  • project-number-or-id:您的 Google Cloud 项目编号或 ID

HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText

请求 JSON 正文:

{
  "model": "projects/project-number-or-id/locations/us-central1/models/TRL1395675701985363739",
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": ["Dr. Watson, please discard your trash. You've shared unsolicited email with me.
  Let's talk about spam and importance ranking in a confidential mode."]
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText " | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应:

{
  "translation": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора.
    Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о
    спаме и важности рейтинга в конфиденциальном режиме.",
    "model": "projects/project-number/locations/us-central1/models/TRL1395675701985363739"
  }
}

C#

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 C# 设置说明进行操作。如需了解详情,请参阅 Translation C# API 参考文档


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class TranslateTextWithModel
    {
        /// <summary>
        /// Translates a given text to a target language with custom model.
        /// </summary>
        /// <param name="modelId">Translation Model ID.</param>
        /// <param name="text">The content to translate.t</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="sourceLanguage">Optional. Source language code.</param>
        /// <param name="projectId"> Google Project ID.</param>
        /// <param name="location"> Region.</param>
        public static void TranslateTextWithModelSample(
            string modelId = "[YOUR_MODEL_ID]",
            string text = "[TEXT_TO_TRANSLATE]",
            string targetLanguage = "ja",
            string sourceLanguage = "en",
            string projectId = "[Google Cloud Project ID]",
            string location = "us-central1")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            string modelPath = $"projects/{projectId}/locations/{location}/models/{modelId}";

            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, location),
                Model = modelPath,
                SourceLanguageCode = sourceLanguage,
                MimeType = "text/plain",
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);
            // Display the translation for each input text provided
            foreach (Translation translation in response.Translations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
    }

Go

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Translation Go API 参考文档

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// translateTextWithModel translates input text and returns translated text.
func translateTextWithModel(w io.Writer, projectID string, location string, sourceLang string, targetLang string, text string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// sourceLang := "en"
	// targetLang := "fr"
	// text := "Hello, world!"
	// modelID := "your-model-id"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
		Model:              fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

	resp, err := client.TranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("TranslateText: %v", err)
	}

	// Display the translation for each input text provided
	for _, translation := range resp.GetTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

在试用此示例之前,请按照 《Translation 快速入门:使用客户端库》 中的 Java 设置说明进行操作。如需了解详情,请参阅 Translation Java API 参考文档

import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextRequest;
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class TranslateTextWithModel {

  public static void translateTextWithModel() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String sourceLanguage = "your-source-language";
    String targetLanguage = "your-target-language";
    String text = "your-text";
    String modelId = "YOUR-MODEL-ID";
    translateTextWithModel(projectId, sourceLanguage, targetLanguage, text, modelId);
  }

  // Translating Text with Model
  public static void translateTextWithModel(
      String projectId, String sourceLanguage, String targetLanguage, String text, String modelId)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      String location = "us-central1";
      LocationName parent = LocationName.of(projectId, location);
      String modelPath =
          String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);

      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain")
              .setSourceLanguageCode(sourceLanguage)
              .setTargetLanguageCode(targetLanguage)
              .addContents(text)
              .setModel(modelPath)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getTranslationsList()) {
        System.out.printf("Translated text: %s\n", translation.getTranslatedText());
      }
    }
  }
}

Node.js

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Translation Node.js API 参考文档

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const text = 'text to translate';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateTextWithModel() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'ja',
    model: `projects/${projectId}/locations/${location}/models/${modelId}`,
  };

  try {
    // Run request
    const [response] = await translationClient.translateText(request);

    for (const translation of response.translations) {
      console.log(`Translated Content: ${translation.translatedText}`);
    }
  } catch (error) {
    console.error(error.details);
  }
}

translateTextWithModel();

PHP

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 PHP 设置说明进行操作。如需了解详情,请参阅 Translation PHP API 参考文档

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $modelId = '[MODEL ID]';
// $text = 'Hello, world!';
// $targetLanguage = 'fr';
// $sourceLanguage = 'en';
// $projectId = '[Google Cloud Project ID]';
// $location = 'global';
$modelPath = sprintf(
    'projects/%s/locations/%s/models/%s',
    $projectId,
    $location,
    $modelId
);
$contents = [$text];
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    $location
);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';

try {
    $response = $translationServiceClient->translateText(
        $contents,
        $targetLanguage,
        $formattedParent,
        [
            'model' => $modelPath,
            'sourceLanguageCode' => $sourceLanguage,
            'mimeType' => $mimeType
        ]
    );
    // Display the translation for each input text provided
    foreach ($response->getTranslations() as $translation) {
        printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
    }
} finally {
    $translationServiceClient->close();
}

Python

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Translation Python API 参考文档


from google.cloud import translate

def translate_text_with_model(
    text="YOUR_TEXT_TO_TRANSLATE",
    project_id="YOUR_PROJECT_ID",
    model_id="YOUR_MODEL_ID",
):
    """Translates a given text using Translation custom model."""

    client = translate.TranslationServiceClient()

    location = "us-central1"
    parent = f"projects/{project_id}/locations/{location}"
    model_path = f"{parent}/models/{model_id}"

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.translate_text(
        request={
            "contents": [text],
            "target_language_code": "ja",
            "model": model_path,
            "source_language_code": "en",
            "parent": parent,
            "mime_type": "text/plain",  # mime types: text/plain, text/html
        }
    )
    # Display the translation for each input text provided
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))

Ruby

在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。如需了解详情,请参阅 Translation Ruby API 参考文档

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# model_id = "[MODEL ID]"

# The `model` type requested for this translation.
model = "projects/#{project_id}/locations/#{location_id}/models/#{model_id}"
# The content to translate in string format
contents = ["Hello, world!"]
# Required. The BCP-47 language code to use for translation.
target_language = "fr"
# Optional. The BCP-47 language code of the input text.
source_language = "en"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id

response = client.translate_text parent:               parent,
                                 contents:             contents,
                                 target_language_code: target_language,
                                 source_language_code: source_language,
                                 model:                model,
                                 mime_type:            mime_type

# Display the translation for each input text provided
response.translations.each do |translation|
  puts "Translated text: #{translation.translated_text}"
end

使用模型参数

REST 和命令行

您可以使用 model 查询参数指定使用哪个模型进行翻译。如需使用 PBMT 模型,请指定 base;如需使用 NMT 模型,请指定 nmt。如果您在请求中指定了 NMT 模型,但 NMT 模型不支持请求的语言翻译对,则系统会使用 PBMT 模型。

以下示例展示了如何在翻译请求中使用 model 参数,还展示了如何选择 base

在使用下面的请求数据之前,请先进行以下替换:

  • project-number-or-id:您的 Google Cloud 项目编号或 ID

HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:translateText

请求 JSON 正文:

{
  "model": "projects/project-number-or-id/locations/global/models/general/base",
  "sourceLanguageCode": "en",
  "targetLanguageCode": "de",
  "contents": ["Come here!"]
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:translateText

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:translateText " | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应:

{
  "translations": [
    {
      "translatedText": "Komm her!",
      "model": "projects/project-number/locations/global/models/general/base"
    }
  ]
}