תרגום טקסט

בדף הזה מוסבר איך לתרגם טקסט לדוגמה באמצעות מהדורות Basic ו-Advanced של Cloud Translation. הם נותנים לכם גישה למודל הסטנדרטי של תרגום מכונה עצבי (NMT) ולמודל LLM לתרגום, שהוא מודל התרגום הכי חדש שלנו בסגנון LLM.

Cloud Translation - Basic API מספק גישה פשוטה ומיידית למודלים האלה. לעומת זאת, Cloud Translation - Advanced מותאם לתרחישי שימוש בהתאמה אישית ובתוכן ארוך. לקוד לדוגמה, ראה את דוגמה מתקדמת לתרגום טקסט. במקרים מיוחדים, אפשר גם להשתמש ב-Cloud Translation Advanced כדי ליצור מודלים בהתאמה אישית.

‫Cloud Translation – Advanced מספק גם יכולות מתקדמות של תרגום טקסט, כמו תרגום מסמכים ויצירת מילוני מונחים, כדי לוודא שהטרמינולוגיה הספציפית לתחום שלכם מתורגמת בצורה נכונה.

לפני שמתחילים

לפני שמתחילים להשתמש ב-Cloud Translation API, צריך להשלים את השלבים שמפורטים בדף הגדרת Cloud Translation, כולל יצירת פרויקט, הפעלת Cloud Translation API והגדרת אימות. בדף ההגדרה יש גם הוראות להתקנת ספריות לקוח לשפות תכנות נפוצות, אבל זה לא חובה.

מודל שפה גדולה (LLM) לתרגום עם Cloud Translation - Basic API

כדי להשתמש במודל Translation LLM הרגיל ב-Cloud Translation - Basic API, צריך להעביר את השם המלא של המשאב שלו בפרמטר model.

curl -X POST \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
       "q": ["The old lighthouse stood on the edge of the cliff."],
       "target": "es",
       "model": "projects/PROJECT_ID/locations/REGION_NAME/models/general/translation-llm"
     }' \
     "https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY"

ממשק ה-API של Cloud Translation – Basic תומך רק במודלים סטנדרטיים של NMT ו-LLM, ולא במודלים בהתאמה אישית. כדי להשתמש במודל מותאם אישית או בתכונות מתקדמות אחרות כמו תרגום מסמכים או מילוני מונחים, צריך להשתמש ב-Cloud Translation – Advanced. מידע נוסף על קריאה ל-Basic API זמין במאמר דוגמה לתרגום טקסט באמצעות Basic API.

תרגום מתקדם של טקסט

בתרגומים באמצעות Cloud Translation - Advanced, הקלט יכול להיות טקסט פשוט או HTML. ‫Cloud Translation API לא מתרגם תגי HTML בקלט, אלא רק טקסט שמופיע בין התגים. הפלט שומר על תגי ה-HTML (שלא תורגמו), עם הטקסט המתורגם בין התגים, ככל האפשר, בגלל ההבדלים בין שפת המקור לשפת היעד.

דוגמה לתרגום טקסט מתקדם

REST

כדי לתרגם טקסט, שולחים בקשת POST ומספקים JSON בגוף הבקשה שמזהה את השפה שממנה רוצים לתרגם (source_language_code), את השפה שאליה רוצים לתרגם (target_language_code) ואת הטקסט לתרגום (contents). אפשר לספק כמה מחרוזות טקסט לתרגום על ידי הכללתן ב-JSON (ראו דוגמה). מציינים את שפות המקור והיעד באמצעות קודי ISO-639 שלהן.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl או PowerShell. בדוגמה נעשה שימוש באסימון הגישה של חשבון שירות שהוגדר לפרויקט באמצעות Google Cloud Google Cloud CLI. הוראות להתקנת Google Cloud CLI, להגדרת פרויקט עם חשבון שירות ולקבלת אסימון גישה מופיעות בדף הגדרה.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של פרויקט Google Cloud

ה-method של ה-HTTP וכתובת ה-URL:

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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# ‎ בדף של ספריות הלקוח ואז עוברים אל מאמרי העזרה של Cloud Translation ל-‎ .NET.

PHP: פועלים לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז עוברים אל מסמכי העזר של Cloud Translation ל-PHP.

Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud Translation בנושא Ruby.

תרגום טקסט באמצעות מודל ספציפי

REST

אפשר לציין באיזה מודל להשתמש לתרגום באמצעות פרמטר השאילתה model.

בדוגמה הבאה מתורגם טקסט באמצעות מודל בהתאמה אישית עם מזהה המודל 1395675701985363739. אפשר לקבל את מזהה המודל של מודל בהתאמה אישית מהרשימה של המודלים במסוף Google Cloud , מהתגובה של ה-API או מהדף המתאים ב-Pantheon כשמאמנים את המודל. כדי להשתמש במודל שפה גדול (LLM) לתרגום, מציינים את המזהה general/translation-llm. כדי להשתמש במודל שפה גדול (LLM) מותאם אישית לתרגום (בגרסת Public Preview), מציינים models/translation-llm-custom/{model-id} כמזהה המודל.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו נמצא המודל בהתאמה אישית, למשל us-central1.

ה-method של ה-HTTP וכתובת ה-URL:

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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# ‎ בדף של ספריות הלקוח ואז עוברים אל מאמרי העזרה של Cloud Translation ל-‎ .NET.

PHP: פועלים לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז עוברים אל מסמכי העזר של Cloud Translation ל-PHP.

Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud Translation בנושא Ruby.

תעתיק

תעתיק הוא הגדרת תצורה בשיטה translateText. כשמפעילים תעתיק, מתרגמים טקסט שעבר רומניזציה (תעתיק לאותיות לטיניות) ישירות לשפת יעד. לדוגמה, אפשר לתרגם טקסט ביפנית שעבר רומניזציה ישירות לאנגלית, לספרדית או לסינית. התרגומים שמתקבלים הם במערכת הכתב של שפת היעד.

בבקשות התעתיק, צריך לכלול רק טקסט שעבר רומניזציה. אם משלבים טקסט ברומניזציה עם טקסט שלא עבר רומניזציה, Cloud Translation לא יכול להבטיח תרגומים עקביים ונכונים.

לתשומת ליבכם

תעתיק שונה מתרגום טקסט רגיל בדרכים הבאות:

  • תעתיק תומך במספר מוגבל של שפות. מידע נוסף מופיע בעמודה תעתיק בדף שפות נתמכות.
  • סוג ה-MIME צריך להיות text/plain. אין תמיכה ב-HTML.
  • רק המודל הרגיל שמוגדר כברירת מחדל תומך בתעתיק. אין תמיכה במודלים בהתאמה אישית.
  • מכסת ברירת המחדל של התוכן בתעתיק נמוכה יותר. מידע נוסף זמין במאמר מכסות ומגבלות.

REST

מגדירים את השדה transliteration_config בשיטה translateText.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו רוצים להריץ את הפעולה הזו. לדוגמה, us-central1.
  • SOURCE_LANGUAGE: (אופציונלי) קוד השפה של טקסט הקלט. אם ידוע, צריך להגדיר את אחד מקודי השפה שמופיעים בתמיכה בשפות.
  • TARGET_LANGUAGE: שפת היעד לתרגום של טקסט הקלט. הערך צריך להיות אחד מקודי השפות שמפורטים בתמיכה בשפות.
  • SOURCE_TEXT: טקסט שעבר רומניזציה בשפת המקור לתרגום.

ה-method של ה-HTTP וכתובת ה-URL:

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

דוגמה בסיסית לתרגום טקסט

REST

שליחת בקשה ל-Cloud Translation – Basic באמצעות הפעלת method של REST לשיטה Basictranslate. מזהים את שפות המקור והיעד באמצעות קודי ISO-639 שלהן.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl או PowerShell.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של פרויקט Google Cloud

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{
  "q": "The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex.",
  "source": "en",
  "target": "es",
  "format": "text"
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_NUMBER_OR_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://translation.googleapis.com/language/translate/v2"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

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": "La Gran Pirámide de Giza (también conocida como la Pirámide de Khufu o la Pirámide de Keops) es la más antigua y más grande de las tres pirámides en el complejo de la pirámide de Giza."
    }]
  }
}

Go

מידע על התקנת ספריית הלקוח של Cloud Translation ושימוש בה מופיע במאמר ספריות הלקוח של Cloud Translation. מידע נוסף מופיע במאמרי העזרה של Cloud Translation Go API.

כדי לבצע אימות ב-Cloud Translation, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

// translateText translates the given text into the specified targetLanguage. sourceLanguage
// is optional. If empty, the API will attempt to detect the source language automatically.
// targetLanguage and sourceLanguage should follow ISO 639 language code of the input text
// (e.g., 'fr' for French)
//
// Find a list of supported languages and codes here:
// https://cloud.google.com/translate/docs/languages#nmt
func translateText(w io.Writer, targetLanguage, sourceLanguage, text string) error {
	ctx := context.Background()

	// Create new Translate client.
	client, err := translate.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("translate.NewClient error: %w", err)
	}
	defer client.Close()

	// Get required tag by parsing the target language.
	targetLang, err := language.Parse(targetLanguage)
	if err != nil {
		return fmt.Errorf("language.Parse: %w", err)
	}

	options := &translate.Options{}

	if sourceLanguage != "" {
		sourceLang, err := language.Parse(sourceLanguage)
		if err != nil {
			return fmt.Errorf("language.Parse: %w", err)
		}
		options = &translate.Options{
			Source: sourceLang,
		}
	}

	// Find more information about translate function here:
	// https://pkg.go.dev/cloud.google.com/go/translate#Client.Translate
	resp, err := client.Translate(ctx, []string{text}, targetLang, options)
	if err != nil {
		return fmt.Errorf("client.Translate error: %w", err)
	}
	if len(resp) == 0 {
		return fmt.Errorf("client.Translate returned empty response to text: %s", text)
	}

	// Print results to buffer.
	fmt.Fprintf(w, "Input Text: %s\n", resp[0].Text)
	fmt.Fprintf(w, "Translated Test: %s\n", text)

	return nil
}

Java

מידע על התקנת ספריית הלקוח של Cloud Translation ושימוש בה מופיע במאמר ספריות הלקוח של Cloud Translation. מידע נוסף מופיע במאמרי העזרה של Cloud Translation Java API.

כדי לבצע אימות ב-Cloud Translation, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

מידע על התקנת ספריית הלקוח של Cloud Translation ושימוש בה מופיע במאמר ספריות הלקוח של Cloud Translation. מידע נוסף מופיע במאמרי העזרה של Cloud Translation Node.js API.

כדי לבצע אימות ב-Cloud Translation, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

מידע על התקנת ספריית הלקוח של Cloud Translation ושימוש בה מופיע במאמר ספריות הלקוח של Cloud Translation. מידע נוסף מופיע במאמרי העזרה של Cloud Translation Python API.

כדי לבצע אימות ב-Cloud Translation, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

def translate_text(
    text: str | bytes | list[str] = "¡Hola amigos y amigas!",
    target_language: str = "en",
    source_language: str | None = None,
) -> dict:
    """Translates a given text into the specified target language.

    Find a list of supported languages and codes here:
    https://cloud.google.com/translate/docs/languages#nmt

    Args:
        text: The text to translate. Can be a string, bytes or a list of strings.
              If bytes, it will be decoded as UTF-8.
        target_language: The ISO 639 language code to translate the text into
                         (e.g., 'en' for English, 'es' for Spanish).
        source_language: Optional. The ISO 639 language code of the input text
                         (e.g., 'fr' for French). If None, the API will attempt
                         to detect the source language automatically.

    Returns:
        A dictionary containing the translation results.
    """

    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        text = [text.decode("utf-8")]

    if isinstance(text, str):
        text = [text]

    # If a string is supplied, a single dictionary will be returned.
    # In case a list of strings is supplied, this method
    # will return a list of dictionaries.

    # Find more information about translate function here:
    # https://cloud.google.com/python/docs/reference/translate/latest/google.cloud.translate_v2.client.Client#google_cloud_translate_v2_client_Client_translate
    results = translate_client.translate(
        values=text,
        target_language=target_language,
        source_language=source_language
    )

    for result in results:
        if "detectedSourceLanguage" in result:
            print(f"Detected source language: {result['detectedSourceLanguage']}")

        print(f"Input text: {result['input']}")
        print(f"Translated text: {result['translatedText']}")
        print()

    return results

שפות נוספות

C#‎: פועלים לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז עוברים אל מאמרי העזרה של Cloud Translation ל-‎ .NET.

PHP: פועלים לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז עוברים אל מסמכי העזר של Cloud Translation ל-PHP.

Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud Translation בנושא Ruby.

פרמטר של מודל

כששולחים בקשת תרגום ל-Cloud Translation - Basic, השירות מתרגם את הטקסט באמצעות מודל תרגום המכונה העצבי (NMT) של Google כברירת מחדל. אפשר גם לציין את מודל ה-LLM הרגיל לתרגום אם מעבירים את שם המשאב המלא של המודל בפרמטר model, כמו בדוגמה Translation LLM with Basic example. ‫Cloud Translation – Basic תומך רק במודלים סטנדרטיים של NMT ו-LLM, ולא במודלים מותאמים אישית. כדי להשתמש במודל בהתאמה אישית, צריך לציין אותו בבקשה ל-Cloud Translation - Advanced.

מקורות מידע נוספים