迁移到 Translation 高级版

本页面介绍了 Cloud Translation 基本版与 Cloud Translation 高级版之间的重大更改,还提供了一些代码示例来帮助您迁移应用。如果您只希望查看 Cloud Translation 高级版中的功能(例如术语表),请参阅 Cloud Translation 高级版简介

Cloud Translation 高级版支持基本版中提供的所有功能和模型。但是,客户端库不支持客户端集成的向后兼容性。换句话说,您必须计划迁移您的应用,才能受益于 Cloud Translation 高级版的功能。

如果您正在规划新项目,则应使用 Cloud Translation 高级版构建应用,以利用新功能和改进的服务。Cloud Translation 基本版仍然可用,但不支持术语表、批量翻译或模型选择等新功能。

基本版与高级版之间的重大更改

Cloud Translation 高级版与基本版有几点不同。

服务帐号

借助 Cloud Translation 基本版,您可以使用 API 密钥对 Translation 进行身份验证。

Cloud Translation 高级版提供的功能需要使用客户管理的资源,这些资源需要通过 IAM 角色和权限进行管理。因此,您无法使用 API 密钥对该服务进行身份验证,而必须改用服务帐号对 Translation 进行身份验证。

IAM 角色

用于对 Translation 进行身份验证的服务帐号以前不需要应用专门的 IAM 角色

Cloud Translation 高级版具有多个 IAM 角色,您可以将这些角色分配给您的服务帐号,以便访问项目中的特定资源。例如,如果要使用服务帐号翻译文本,则可以为其分配 roles/cloudtranslate.user 角色。如需详细了解可用的 IAM 角色,请参阅 Cloud Translation 高级版简介

资源、项目和位置

向 Cloud Translation 高级版发出请求时,您必须提供想要使用的资源的名称。资源通常是某个包含项目名称及其位置的限定名称,例如一个 AutoML 模型的名称。

例如,如果您的 Google Cloud 项目名称为 my-project 并且资源的位置为 us-central1,该资源的全名可能如下所示:

projects/MY_PROJECT/locations/us-central1/...

您还可以在用于发送 REST 请求的网址中使用位置名称。该位置指定了请求的执行位置。 例如,您用于发送 getSupportedLanguages 请求的网址可能如下所示:

https://translation.googleapis.com/v3/projects/my-project/locations/us-central1/supportedLanguages

翻译模型

向 Cloud Translation 高级版请求翻译时,您可以使用 AutoML Translation 自定义模型,也可以使用常规模型,即神经机器翻译 (NMT) 和基于短语的机器翻译 (PBMT)。

若要与 AutoML 模型集成,那么用于处理翻译请求的服务帐号需要具有访问 AutoML 和常规模型(无论是在您的项目还是在其他项目中定义的模型)的适当 IAM 权限。

如需详细了解如何选择翻译模型,请参阅使用 Cloud Translation 高级版翻译文本

每个请求的内容限制

Cloud Translation API 针对较小的翻译请求进行了优化。每个请求的建议长度上限为 5K 字符(码位)。 您包含的字符越多,响应延迟时间就越长。 对于 Cloud Translation 高级版,单个请求的码位上限是 30K。Cloud Translation 基本版的请求大小上限为 100K 字节。

无论可用配额有多少,Cloud Translation API 都会拒绝大小超过此上限的请求并返回 400 INVALID_ARGUMENT 错误。

如需详细了解配额和限制,请参阅配额

参照以下步骤,将现有应用从 Cloud Translation 基本版更新为 Cloud Translation 高级版。

  1. 清点您的 Google Cloud 项目、应用和访问基本版 API 的用户。
  2. 为您的应用设置服务帐号和身份验证。 查看与 IAM 角色相关的材料,重点关注 AutoML、Cloud Storage、Cloud Translation 角色。
  3. 为您的项目启用 Cloud Translation 高级版。如果要将 AutoML 模型与 Cloud Translation 高级版搭配使用,还必须启用 AutoML。
  4. 使用 Cloud Translation 高级版客户端库和方法。对于 Cloud Translation 高级版请求,您必须在请求中提供项目编号(或项目 ID)和项目位置(通常是 globalus-central1)。如需了解详情,请参阅 API 和客户端库的区别
  5. 更新您的应用或翻译工作流以利用新功能。要将您的应用与 AutoML 和 Cloud Storage 集成,您必须为您的服务帐号授予适当的 IAM 角色和权限,以便这些帐号访问您的资源。
  6. 检查对 Cloud Translation 高级版的翻译请求大小是否不超过限制
  7. 规划您的翻译请求配额监控。这两个版本的 API 共享相同的每日和每月配额
  8. 审核任何可能的结算变化。

API 和客户端库的差异

以下部分介绍了调用 Cloud Translation 基本版与调用 Cloud Translation 高级版之间的具体差异。

导入 Cloud Translation 高级版客户端库

如需导入 Cloud Translation 高级版客户端库,请使用以下代码。

C#

nuget install Google.Cloud.Translate.V3 -Pre

Go

go get -u cloud.google.com/go/translate/apiv3

Java

如果您使用的是 Maven,请将以下代码添加到您的 pom.xml 文件中。如需详细了解 BOM,请参阅 Google Cloud Platform 库 BOM

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>19.2.1</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-translate</artifactId>
  </dependency>
</dependencies>

如果您使用的是 Gradle,请将以下代码添加到您的依赖项中:

implementation platform('com.google.cloud:libraries-bom:19.2.1')

compile 'com.google.cloud:google-cloud-translate'

如果您使用的是 sbt,请将以下代码添加到您的依赖项中:

libraryDependencies += "com.google.cloud" % "google-cloud-translate" % "1.96.0"

如果您使用的是 IntelliJ 或 Eclipse,请通过以下 IDE 插件将客户端库添加到您的项目中:

上述插件还提供其他功能,例如服务帐号密钥管理。如需了解详情,请参阅各个插件相应的文档。

Node.js

如需详细了解如何设置 Node.js 开发环境,请参阅 Node.js 开发环境设置指南

npm install --save @google-cloud/translate

PHP

composer require google/cloud-translate

Python

如需详细了解如何设置 Python 开发环境,请参阅 Python 开发环境设置指南

pip install --upgrade google-cloud-translate

Ruby

如需详细了解如何设置 Ruby 开发环境,请参阅 Ruby 开发环境设置指南

gem install google-cloud-translate

翻译文本

如需使用 Cloud Translation 基本版向 API 发送翻译请求,请使用以下代码:

REST 和命令行

HTTP 方法和网址:

POST https://translation.googleapis.com/language/translate/v2

请求 JSON 正文:

{
  "q": ["Hello world", "My name is Jeff"],
  "target": "de"
}

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

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/language/translate/v2

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/language/translate/v2 " | Select-Object -Expand Content

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

{
  "data": {
    "translations": [
      {
        "translatedText": "Hallo Welt",
        "detectedSourceLanguage": "en"
      },
      {
        "translatedText": "Mein Name ist Jeff",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

Go

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

func translateText(targetLanguage, text string) (string, error) {
	// text := "The Go Gopher is cute"
	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return "", fmt.Errorf("language.Parse: %v", err)
	}

	client, err := translate.NewClient(ctx)
	if err != nil {
		return "", err
	}
	defer client.Close()

	resp, err := client.Translate(ctx, []string{text}, lang, nil)
	if err != nil {
		return "", fmt.Errorf("Translate: %v", err)
	}
	if len(resp) == 0 {
		return "", fmt.Errorf("Translate returned empty response to text: %s", text)
	}
	return resp[0].Text, nil
}

Java

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

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

Translation translation = translate.translate("¡Hola Mundo!");
System.out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());

Node.js

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

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';

async function translateText() {
  // Translates the text into the target language. "text" can be a string for
  // translating a single piece of text, or an array of strings for translating
  // multiple texts.
  let [translations] = await translate.translate(text, target);
  translations = Array.isArray(translations) ? translations : [translations];
  console.log('Translations:');
  translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);
  });
}

translateText();

Python

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

def translate_text(target, text):
    """Translates text into the target language.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    import six
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, six.binary_type):
        text = text.decode("utf-8")

    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.translate(text, target_language=target)

    print(u"Text: {}".format(result["input"]))
    print(u"Translation: {}".format(result["translatedText"]))
    print(u"Detected source language: {}".format(result["detectedSourceLanguage"]))

使用 Cloud Translation 高级版,您在发出 translateText 请求时必须提供项目编号(或项目 ID)和项目位置(通常是 globalus-central1)。

您还可以明确指定翻译文本时使用的翻译模型或术语表。您甚至可以要求以 text/plaintext/html(默认值为 text/html)的形式接收响应翻译。

REST 和命令行

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

  • 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": "Принеси мне кофе!",
    }
  ]
}

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

发现支持的语言

如需使用 Cloud Translation 基本版获取 API 支持的语言列表,请使用以下代码:

REST 和命令行

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

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

HTTP 方法和网址:

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

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

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages

PowerShell

执行以下命令:

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages " | Select-Object -Expand Content

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

{
  "languages": [
     "languageCode": "af",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "ar",
      "supportSource": true,
      "supportTarget": true
    },
    ....
    {
      "languageCode": "zu",
      "supportSource": true,
      "supportTarget": true
    }
   ]
}

该列表按照语言代码的字母顺序排列。此查询会返回受支持语言的 ISO-639-1 语言代码。一些语言代码还包含国家/地区代码(如 zh-CN 或 zh-TW)。例如:

   {
      "languageCode": "zh-TW",
      "supportSource": true,
      "supportTarget": true
    },

Java

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

List<Language> languages = translate.listSupportedLanguages();

for (Language language : languages) {
  System.out.printf("Name: %s, Code: %s\n", language.getName(), language.getCode());
}

Node.js

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

async function listLanguages() {
  // Lists available translation language with their names in English (the default).
  const [languages] = await translate.getLanguages();

  console.log('Languages:');
  languages.forEach(language => console.log(language));
}

listLanguages();

Python

def list_languages():
    """Lists all available languages."""
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    results = translate_client.get_languages()

    for language in results:
        print(u"{name} ({language})".format(**language))

使用 Cloud Translation 高级版,您在发出 getSupportedLanguages 请求时必须提供项目编号或项目 ID 和项目位置(通常是 globalus-central1)。

REST 和命令行

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

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

HTTP 方法和网址:

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

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

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages

PowerShell

执行以下命令:

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages " | Select-Object -Expand Content

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

{
  "languages": [
     "languageCode": "af",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "ar",
      "supportSource": true,
      "supportTarget": true
    },
    ....
    {
      "languageCode": "zu",
      "supportSource": true,
      "supportTarget": true
    }
   ]
}

该列表按照语言代码的字母顺序排列。此查询会返回受支持语言的 ISO-639-1 语言代码。一些语言代码还包含国家/地区代码(如 zh-CN 或 zh-TW)。例如:

   {
      "languageCode": "zh-TW",
      "supportSource": true,
      "supportTarget": true
    },

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

// getSupportedLanguages gets a list of supported language codes.
func getSupportedLanguages(w io.Writer, projectID string) error {
	// projectID := "my-project-id"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}

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

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
	}

	return nil
}

Java

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

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguages {

  public static void getSupportedLanguages() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    getSupportedLanguages(projectId);
  }

  // Getting a list of supported language codes
  public static void getSupportedLanguages(String projectId) 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");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder().setParent(parent.toString()).build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
      }
    }
  }
}

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

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

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  // Get supported languages
  const [response] = await translationClient.getSupportedLanguages(request);

  for (const language of response.languages) {
    // Supported language code, generally consisting of its ISO 639-1 identifier, for
    // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
    // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
    console.log(`Language - Language Code: ${language.languageCode}`);
    // Human readable name of the language localized in the display language specified
    // in the request.
    console.log(`Language - Display Name: ${language.displayName}`);
    // Can be used as source language.
    console.log(`Language - Support Source: ${language.supportSource}`);
    // Can be used as target language.
    console.log(`Language - Support Target: ${language.supportTarget}`);
  }
}

getSupportedLanguages();

Python

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

from google.cloud import translate

def get_supported_languages(project_id="YOUR_PROJECT_ID"):
    """Getting a list of supported language codes."""

    client = translate.TranslationServiceClient()

    parent = f"projects/{project_id}"

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.get_supported_languages(parent=parent)

    # List language codes of supported languages.
    print("Supported Languages:")
    for language in response.languages:
        print("Language Code: {}".format(language.language_code))

检测语言

如需使用 Cloud Translation 基本版检测文本中的源语言,请使用以下代码:

curl

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': 'Omnia Gallia est divisa in tres partes',
}" "https://translation.googleapis.com/language/translate/v2/detect"

如果请求成功,服务器将返回一个 200 OK HTTP 状态代码以及 JSON 格式的响应。

{
  "data": {
    "detections": [
      [
        {
          "confidence": 0.93554825,
          "isReliable": false,
          "language": "la"
        }
      ]
    ]
  }

Java

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

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

List<String> texts = new LinkedList<>();
texts.add("Hello, World!");
texts.add("¡Hola Mundo!");
List<Detection> detections = translate.detect(texts);

System.out.println("Language(s) detected:");
for (Detection detection : detections) {
  System.out.printf("\t%s\n", detection);
}

Node.js

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

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const text = 'The text for which to detect language, e.g. Hello, world!';

// Detects the language. "text" can be a string for detecting the language of
// a single piece of text, or an array of strings for detecting the languages
// of multiple texts.
async function detectLanguage() {
  let [detections] = await translate.detect(text);
  detections = Array.isArray(detections) ? detections : [detections];
  console.log('Detections:');
  detections.forEach(detection => {
    console.log(`${detection.input} => ${detection.language}`);
  });
}

detectLanguage();

Python

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

def detect_language(text):
    """Detects the text's language."""
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.detect_language(text)

    print("Text: {}".format(text))
    print("Confidence: {}".format(result["confidence"]))
    print("Language: {}".format(result["language"]))

使用 Cloud Translation 高级版,您在发出 detectLanguage 请求时必须提供项目编号(或项目 ID)和项目位置(通常是 globalus-central1)。

此外,您可以配置向 Cloud Translation 高级版发送的请求,以便发送不同的 MIME 类型。例如,您可以请求 text/htmltext/plain(默认值为 text/html)。

REST 和命令行

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

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

HTTP 方法和网址:

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

请求 JSON 正文:

{
   "content":"Доктор Ватсон, иди сюда!"
}

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

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:detectLanguage

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:detectLanguage " | Select-Object -Expand Content

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

{
  "languages": [
    {
      "languageCode": "ru",
      "confidence": 1
    }
  ]
}
在响应中,languageCode 提供检测到的语言的代码。confidence 的范围从 0 到 1。1 表示置信度为 100%。

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

// detectLanguage detects the language of a text string.
func detectLanguage(w io.Writer, projectID string, text string) error {
	// projectID := "my-project-id"
	// text := "Hello, world!"

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

	req := &translatepb.DetectLanguageRequest{
		Parent:   fmt.Sprintf("projects/%s/locations/global", projectID),
		MimeType: "text/plain", // Mime types: "text/plain", "text/html"
		Source: &translatepb.DetectLanguageRequest_Content{
			Content: text,
		},
	}

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

	// Display list of detected languages sorted by detection confidence.
	// The most probable language is first.
	for _, language := range resp.GetLanguages() {
		// The language detected.
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
		// Confidence of detection result for this language.
		fmt.Fprintf(w, "Confidence: %v\n", language.GetConfidence())
	}

	return nil
}

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 detectLanguage() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    content: text,
  };

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

  console.log('Detected Languages:');
  for (const language of response.languages) {
    console.log(`Language Code: ${language.languageCode}`);
    console.log(`Confidence: ${language.confidence}`);
  }
}

detectLanguage();

Python

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

from google.cloud import translate

def detect_language(project_id="YOUR_PROJECT_ID"):
    """Detecting the language of a text string."""

    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.detect_language(
        content="Hello, world!",
        parent=parent,
        mime_type="text/plain",  # mime types: text/plain, text/html
    )

    # Display list of detected languages sorted by detection confidence.
    # The most probable language is first.
    for language in response.languages:
        # The language detected
        print("Language code: {}".format(language.language_code))
        # Confidence of detection result for this language
        print("Confidence: {}".format(language.confidence))