翻譯文字 (進階版)

Cloud Translation - Advanced 適合用於自訂和長篇內容。除了神經機器翻譯 (NMT) 模型,Advanced 還提供翻譯 LLM (Google 最新、品質最高的 LLM 樣式翻譯模型),以及建立自訂模型的功能。

Cloud Translation - Advanced 也提供進階文字翻譯功能,例如翻譯文件建立詞彙表,確保特定領域的專用術語翻譯正確。

事前準備

如要開始使用 Cloud Translation API,您必須擁有已啟用 Cloud Translation API 的專案,並具備適當的憑證。您也可以安裝常用程式設計語言的用戶端程式庫,協助您呼叫 API。詳情請參閱「設定」頁面。

如需參考操作說明以瞭解如何安裝 Google Cloud CLI、建立具有服務帳戶的專案,以及取得存取憑證,請參閱「設定」頁面。如果您打算使用詞彙表或批次處理功能,也需要建立 Cloud Storage 值區並為其授予服務帳戶存取權。

翻譯文字

如要翻譯,輸入內容可以是純文字或 HTML。Cloud Translation API 不會翻譯輸入內容中的任何 HTML 標記,只會翻譯出現在標記之間的文字。輸出內容會保留沒有翻譯的 HTML 標記,由於原文與譯文語言間之間有所差異,系統會儘可能在標記間加入翻譯過的文字。

翻譯輸入字串

REST

如要翻譯文字,請發出 POST 要求,並在要求主體中以 JSON 格式標示原文語言 (source_language_code)、譯文語言 (target_language_code) 和要翻譯的文字 (contents)。您可以在 JSON 中加入多個文字字串來提供要翻譯的多個文字字串 (請參閱範例)。請使用 ISO-639 代碼標記原文與譯文語言。

以下為使用 curl 或 PowerShell 的 POST 要求範例。範例中使用的存取憑證,屬於使用 Google Cloud Google Cloud CLI 建立的專案服務帳戶。如需安裝 Google Cloud CLI、使用服務帳戶建立專案,以及取得存取憑證的操作說明,請參閱「設定」頁面。

使用任何要求資料之前,請先替換以下項目:

  • 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!"]
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

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

translations 陣列具有兩個 translatedText 欄位,其中皆包含以要求的targetLanguageCode語言 (ru:俄文) 提供的翻譯。系統列出翻譯的順序與要求中的對應來源陣列相同。

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Go API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Translation library
import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"cloud.google.com/go/translate/apiv3/translatepb"
)

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

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

	// Construct request
	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: %w", 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Java API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Imports the Google Cloud Translation library.
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 {

  // Set and pass variables to overloaded translateText() method for translation.
  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);
  }

  // Translate text to target language.
  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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Node.js API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * 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() {
  // MIME type of the content to translate
  // Supported MIME types:
  // https://cloud.google.com/translate/docs/supported-formats
  const mimeType = 'text/plain';

  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: mimeType,
    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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Python API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import os

# Import the Google Cloud Translation library.
from google.cloud import translate_v3

PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")


def translate_text(
    text: str = "YOUR_TEXT_TO_TRANSLATE",
    source_language_code: str = "en-US",
    target_language_code: str = "fr",
) -> translate_v3.TranslationServiceClient:
    """Translate Text from a Source language to a Target language.
    Args:
        text: The content to translate.
        source_language_code: The code of the source language.
        target_language_code: The code of the target language.
            For example: "fr" for French, "es" for Spanish, etc.
            Find available languages and codes here:
            https://cloud.google.com/translate/docs/languages#neural_machine_translation_model
    """

    # Initialize Translation client.
    client = translate_v3.TranslationServiceClient()
    parent = f"projects/{PROJECT_ID}/locations/global"

    # MIME type of the content to translate.
    # Supported MIME types:
    # https://cloud.google.com/translate/docs/supported-formats
    mime_type = "text/plain"

    # Translate text from the source to the target language.
    response = client.translate_text(
        contents=[text],
        parent=parent,
        mime_type=mime_type,
        source_language_code=source_language_code,
        target_language_code=target_language_code,
    )

    # Display the translation for the text.
    # For example, for "Hello! How are you doing today?":
    # Translated text: Bonjour comment vas-tu aujourd'hui?
    for translation in response.translations:
        print(f"Translated text: {translation.translated_text}")

    return response

其他語言

C#: 請按照用戶端程式庫頁面的 C# 設定說明操作, 然後前往 .NET 適用的 Cloud Translation 參考說明文件

PHP: 請按照用戶端程式庫頁面的 PHP 設定說明 操作,然後前往 PHP 適用的 Cloud Translation 參考說明文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明 操作,然後前往 Ruby 適用的 Cloud Translation 參考文件

使用特定模型翻譯文字

REST

您可以使用 model 查詢參數指定要使用哪個模型執行翻譯作業。

下列範例使用模型 ID 為 1395675701985363739 的自訂模型翻譯文字。您可以前往 Google Cloud 控制台,從模型清單中取得自訂模型的模型 ID,也可以在訓練模型時,從 API 回應或對應的 Pantheon 頁面取得模型 ID。如要使用翻譯 LLM,請指定 general/translation-llm 做為模型 ID。如要使用自訂翻譯大型語言模型 (公開預先發布版),請指定 model/translation-llm-custom/{model-id} 做為模型 ID。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION:自訂模型所在的區域,例如 us-central1

HTTP 方法和網址:

POST https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText

JSON 要求主體:

{
  "model": "projects/PROJECT_ID/locations/LOCATION/models/1395675701985363739",
  "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 print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }

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

您應該會收到如下的 JSON 回應:

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

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Go API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"cloud.google.com/go/translate/apiv3/translatepb"
)

// 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: %w", 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: %w", 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Java API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Node.js API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Python API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


from google.cloud import translate


def translate_text_with_model(
    text: str = "YOUR_TEXT_TO_TRANSLATE",
    project_id: str = "YOUR_PROJECT_ID",
    model_id: str = "YOUR_MODEL_ID",
) -> translate.TranslationServiceClient:
    """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(f"Translated text: {translation.translated_text}")

    return response

其他語言

C#: 請按照用戶端程式庫頁面的 C# 設定說明操作, 然後前往 .NET 適用的 Cloud Translation 參考說明文件

PHP: 請按照用戶端程式庫頁面的 PHP 設定說明 操作,然後前往 PHP 適用的 Cloud Translation 參考說明文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明 操作,然後前往 Ruby 適用的 Cloud Translation 參考文件

音譯

音譯是 translateText 方法中的設定。啟用音譯功能後,系統會直接將羅馬化文字 (拉丁文字) 翻譯成目標語言。舉例來說,你可以直接將羅馬拼音的日文翻譯成英文、西班牙文或中文。翻譯結果會採用目標語言的書寫系統。

在音譯要求中,請只加入羅馬拼音文字。如果將羅馬化文字與非羅馬化文字混用,Cloud Translation 無法確保翻譯結果一致且正確。

注意事項

音譯與標準文字翻譯的差異如下:

  • 音譯功能僅支援部分語言。詳情請參閱「支援的語言」頁面上的「音譯」欄。
  • MIME 類型必須為 text/plain。不支援 HTML。
  • 只有預設標準模型支援音譯。不支援自訂模型。
  • 音譯的預設內容配額較低。詳情請參閱配額與限制

REST

translateText 方法中設定 transliteration_config 欄位。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER_OR_ID:專案的數值或英數字元 ID。 Google Cloud
  • LOCATION:您要執行這項作業的區域。例如:us-central1
  • SOURCE_LANGUAGE:(選用) 輸入文字的語言代碼。如果知道語言代碼,請設為「語言支援」頁面列出的其中一個代碼。
  • TARGET_LANGUAGE:輸入文字的目標翻譯語言。設為「語言支援」中列出的其中一個語言代碼。
  • SOURCE_TEXT:要翻譯的來源語言羅馬化文字。

HTTP 方法和網址:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION:translateText

JSON 要求主體:

{
  "source_language_code": "SOURCE_LANGUAGE",
  "target_language_code": "TARGET_LANGUAGE",
  "contents": "SOURCE_TEXT",
  "mime_type": "text/plain",
  "transliteration_config": { "enable_transliteration": true}
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "translations": [
    {
      "translatedText": "TRANSLATED_TEXT",
    }
  ]
}

其他資源

  • 如需解決常見問題或錯誤的說明,請參閱「疑難排解」頁面。