翻译文本(高级版)

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 模型。

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

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

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

AutoML 翻译模型 特定领域的文本。客户提供特定于其用例的训练数据,针对给定语言对自定义用于特定领域的 Google NMT 模型。 财经新闻、技术文档、使用该领域独有的术语和行话的任何文本。

您可以使用翻译模型的 ID 指定相应的翻译模型。对于 NMT 模型,模型 ID 为 general/nmt。如需了解 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:俄语)提供。译文的排列顺序与相应源数组在请求中的顺序相同。

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',
  };

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

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

translateText();

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

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Translation 参考文档

PHP:请按照客户端库页面上的 PHP 设置说明操作,然后访问 PHP 版 Translation 参考文档

Ruby:请按照客户端库页面上的 Ruby 设置说明操作,然后访问 Ruby 版 Translation 参考文档

使用 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"
  }
}

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}`,
  };

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

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

translateTextWithModel();

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

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Translation 参考文档

PHP:请按照客户端库页面上的 PHP 设置说明操作,然后访问 PHP 版 Translation 参考文档

Ruby:请按照客户端库页面上的 Ruby 设置说明操作,然后访问 Ruby 版 Translation 参考文档

使用模型参数

REST 和命令行

您可以使用 model 查询参数指定使用哪个模型进行翻译。例如,如需使用 NMT 模型,请指定 nmt

以下示例展示了如何在翻译请求中使用 model 参数。

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

  • 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/nmt",
  "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/nmt"
    }
  ]
}

其他资源

  • 如需有关解决常见问题或错误的帮助,请参阅问题排查页面。