יצירה של מילוני מונחים ושימוש בהם (מתקדם)

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

אפשר להשתמש במילון מונחים במקרים הבאים:

  • שמות מוצרים: לדוגמה, השם Google Home חייב להיות מתורגם ל-Google Home.
  • מילים עם משמעויות שונות: לדוגמה, המילה "bat" יכולה להתייחס לציוד ספורט או לבעל חיים. אם אתם יודעים שאתם מתרגמים מילים שקשורות לספורט, כדאי להשתמש במילון מונחים כדי להזין ל-Cloud Translation API את התרגום של המילה bat בהקשר של ספורט, ולא את התרגום של המילה בהקשר של בעל חיים.
  • מילים שאולות: לדוגמה, המילה bouillabaisse בצרפתית מתורגמת ל-bouillabaisse באנגלית. המילה bouillabaisse (מרק דגים) הושאלה מאנגלית לצרפתית במאה ה-19. אדם דובר אנגלית שלא מכיר את ההקשר התרבותי של צרפת, יכול להיות שלא יידע שבוילבאס הוא תבשיל דגים. אפשר להשתמש במילוני מונחים כדי לשנות תרגום. לדוגמה, אפשר להגדיר שתרגום המילה bouillabaisse מצרפתית לאנגלית יהיה fish stew (מרק דגים).

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

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

ההרשאות הנדרשות

כדי לעבוד עם מילוני מונחים, לחשבון השירות שלכם נדרשות הרשאות ספציפיות למילוני מונחים. אפשר להקצות תפקיד לחשבון השירות באמצעות אחד מהתפקידים המוגדרים מראש ב-IAM, כמו Cloud Translation API Editor ‏ (roles/cloudtranslate.editor), או ליצור תפקיד בהתאמה אישית שמעניק את ההרשאות הנדרשות. אפשר לראות את כל ההרשאות של Cloud Translation API בהפניה להרשאות IAM. ההרשאות ב-Cloud Translation מתחילות ב-cloudtranslate.

כדי ליצור מילונים, אתם צריכים גם הרשאות לקריאת אובייקטים בקטגוריה של Cloud Storage שבה נמצא קובץ המילון. אפשר להקצות תפקיד לחשבון השירות באמצעות אחד מתפקידי ה-IAM המוגדרים מראש, כמו 'צפייה באובייקט אחסון' (roles/storage.objectViewer), או ליצור תפקיד בהתאמה אישית שמעניק הרשאות לקריאת אובייקטים.

במאמר הענקה, שינוי וביטול גישה למשאבים מוסבר איך מוסיפים חשבון לתפקיד.

יצירת מילון מונחים

המונחים במילון יכולים להיות טוקנים בודדים (מילים) או ביטויים קצרים (בדרך כלל פחות מחמש מילים). השלבים העיקריים לשימוש במילון מונחים הם:

  1. יצירת קובץ מילון מונחים
  2. יצירת משאב מילון המונחים באמצעות Cloud Translation API
  3. מציינים באיזה מילון מונחים רוצים להשתמש כשמבקשים תרגום

פרויקט יכול לכלול כמה מילונים. אפשר לקבל רשימה של המילונים הזמינים וגם למחוק מילונים שכבר לא צריך.

מילות מעצור

שירות Cloud Translation מתעלם מחלק מהמונחים שמופיעים במילון המונחים. המונחים האלה נקראים מילות עצירה. כשמתרגמים מילות קישור, Cloud Translation מתעלם מכל הערכים התואמים במילון המונחים. רשימה של כל מילות העצירה מופיעה במאמר מילות עצירה במילון המונחים.

יצירת קובץ מילון מונחים

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

המספר הכולל של המונחים בקובץ קלט של מילון מונחים לא יכול להיות יותר מ-10.4 מיליון (10,485,760) בייטים בקידוד UTF-8 לכל המונחים בכל השפות יחד. כל מונח במילון המונחים צריך להיות קטן מ-1,024 בייטים בקידוד UTF-8. המערכת מתעלמת ממונחים שאורכם גדול מ-1,024 בייט.

כברירת מחדל, ההתאמות למילון המונחים הן תלויות אותיות רישיות. כשמחילים מילון מונחים, אפשר להתעלם מהשימוש באותיות רישיות בכל הערכים. אם יש לכם מונחים שהם תלויי-רישיות ומונחים שהם לא תלויי-רישיות, כדאי להשתמש בהתנהגות ברירת המחדל, ולכלול במילון המונחים את שתי הצורות של המונחים שהם לא תלויי-רישיות.

מילוני מונחים חד-כיווניים

‫Cloud Translation API מקבל קובצי TSV, ‏ CSV או TMX.

TSV ו-CSV

בפורמטים של ערכים מופרדים בטאבים (TSV) וערכים מופרדים בפסיקים (CSV), כל שורה מכילה צמד מונחים שמופרדים בטאב (\t) או בפסיק (,). העמודה הראשונה כוללת את המונח בשפת המקור, והעמודה השנייה כוללת את המונח בשפת היעד, כמו שמוצג בדוגמה הבאה:

חד-כיווני
מילון מונחים

Translation Memory eXchange (TMX)‎

‫Translation Memory eXchange ‏ (TMX) הוא פורמט XML סטנדרטי שמשמש לציון תרגומים של מקור ויעד. ‫Cloud Translation API תומך בקובצי קלט בפורמט שמבוסס על TMX בגרסה 1.4. בדוגמה הזו אפשר לראות את המבנה הנדרש:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE tmx SYSTEM "tmx14.dtd">
<tmx version="1.4">
  <header segtype="sentence" o-tmf="UTF-8"
  adminlang="en" srclang="en" datatype="PlainText"/>
  <body>
    <tu>
      <tuv xml:lang="en">
        <seg>account</seg>
      </tuv>
      <tuv xml:lang="es">
        <seg>cuenta</seg>
      </tuv>
    </tu>
    <tu>
      <tuv xml:lang="en">
        <seg>directions</seg>
      </tuv>
      <tuv xml:lang="es">
        <seg>indicaciones</seg>
      </tuv>
    </tu>
  </body>
</tmx>

אלמנט <header> בקובץ TMX תקין חייב לזהות את שפת המקור באמצעות המאפיין srclang, וכל אלמנט <tuv> חייב לזהות את השפה של הטקסט שכלול בו באמצעות המאפיין xml:lang. מציינים את שפת המקור ושפת היעד באמצעות קודי ISO-639.

כל הרכיבים <tu> חייבים להכיל זוג רכיבים <tuv> עם אותן שפות מקור ויעד. אם רכיב <tu> מכיל יותר משני רכיבי <tuv> , Cloud Translation API מעבד רק את הרכיב הראשון <tuv> שתואם לשפת המקור ואת הרכיב הראשון שתואם לשפת היעד, ומתעלם מהשאר. אם רכיב <tu> לא מכיל זוג תואם של רכיבי <tuv>, Cloud Translation API מדלג על רכיב <tu> הלא תקין.

‫Cloud Translation API מסיר את תגי העיצוב מסביב לרכיב <seg> לפני העיבוד שלו. אם רכיב <tuv> מכיל יותר מרכיב <seg>, Cloud Translation API משרשר את הטקסט שלהם לרכיב יחיד עם רווח ביניהם.

אם הקובץ מכיל תגי XML שונים מאלה שמוצגים למעלה, Cloud Translation API מתעלם מהם.

אם הקובץ לא תואם לפורמט XML ו-TMX תקין – למשל, אם חסר תג סיום או רכיב <tmx> – Cloud Translation API מפסיק את העיבוד שלו. בנוסף, Cloud Translation API מפסיק את העיבוד אם הוא מדלג על יותר מ-1,024 רכיבי <tu> לא תקינים.

קבוצות מונחים מקבילות (CSV)

במקרה של קבוצות מונחים מקבילות, Cloud Translation API מקבל רק קבצים בפורמט CSV. כדי להגדיר קבוצות של מונחים מקבילים, יוצרים קובץ CSV עם כמה עמודות, שבו כל שורה מציגה מונח אחד במילון המונחים בכמה שפות.

השורה הראשונה בקובץ היא שורת כותרת שמציינת את השפה של כל עמודה באמצעות קוד השפה ISO-639 או BCP-47. אפשר גם לכלול עמודות אופציונליות של חלק הדיבור (pos) ותיאור (description). האלגוריתם לא משתמש כרגע במידע על pos, וערכי pos ספציפיים לא מאומתים.

כל שורה שמתקבלת מכילה מונחים מקבילים במילון המונחים בשפות שצוינו בכותרת. אפשר להשאיר עמודות ריקות אם המונח לא זמין בכל השפות.

קבוצת מונחים מקבילים

יצירת משאב מילון מונחים

אחרי שמזהים את המונחים המקבילים במילון המונחים, יוצרים משאב של מילון מונחים כדי להפוך את קובץ מילון המונחים לזמין ל-Cloud Translation API.

מילון מונחים חד-כיווני

כשיוצרים מילון מונחים חד-כיווני, צריך לציין את צמד השפות (language_pair) על ידי הגדרת שפת המקור (source_language_code) ושפת היעד (target_language_code). בדוגמה הבאה נעשה שימוש ב-API בארכיטקטורת REST ובשורת הפקודה, אבל אפשר גם להשתמש בספריות הלקוח כדי ליצור מילון מונחים חד-כיווני.

REST

כשיוצרים מילון מונחים חדש, צריך לציין מזהה מילון מונחים (שם משאב). לדוגמה:
projects/my-project/locations/us-central1/glossaries/my-en-to-ru-glossary
כאשר my-project הוא PROJECT_NUMBER_OR_ID, ו-my-en-ru-glossary הוא מזהה המילון שסיפקתם.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של פרויקט Google Cloud
  • glossary-id: מזהה המילון שלכם, לדוגמה: my_en_ru_glossary
  • bucket-name: שם הקטגוריה שבה נמצא קובץ המילון
  • glossary-filename: שם הקובץ של המילון

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

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries

תוכן בקשת JSON:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id",
  "languagePair": {
    "sourceLanguageCode": "en",
    "targetLanguageCode": "ru"
    },
  "inputConfig": {
    "gcsSource": {
      "inputUri": "gs://bucket-name/glossary-filename"
    }
  }
}

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3beta1.CreateGlossaryMetadata",
    "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "state": "RUNNING",
    "submitTime": "2019-11-19T19:05:10.650047636Z"
  }
}

מילון מונחים מקבילים

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

REST

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של פרויקט Google Cloud
  • glossary-id: מזהה המילון שלכם
  • bucket-name: שם הקטגוריה שבה נמצא קובץ המילון
  • glossary-filename: שם הקובץ של המילון

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

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries

תוכן בקשת JSON:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id",
  "languageCodesSet": {
    "languageCodes": ["en", "en-GB", "ru", "fr", "pt-BR", "pt-PT", "es"]
  },
  "inputConfig": {
    "gcsSource": {
"inputUri": "gs://bucket-name/glossary-file-name"
    }
  }
}

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/project-number/locations/us-central1/operations/20191103-09061569945989-5d937985-0000-21ac-816d-f4f5e80782d4",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3beta1.CreateGlossaryMetadata",
    "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "state": "RUNNING",
    "submitTime": "2019-11-03T16:06:29.134496675Z"
  }
}

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

// createGlossary creates a glossary to use for other operations.
func createGlossary(w io.Writer, projectID string, location string, glossaryID string, glossaryInputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "my-glossary-display-name"
	// glossaryInputURI := "gs://cloud-samples-data/translation/glossary.csv"

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

	req := &translatepb.CreateGlossaryRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Glossary: &translatepb.Glossary{
			Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
			Languages: &translatepb.Glossary_LanguageCodesSet_{
				LanguageCodesSet: &translatepb.Glossary_LanguageCodesSet{
					LanguageCodes: []string{"en", "ja"},
				},
			},
			InputConfig: &translatepb.GlossaryInputConfig{
				Source: &translatepb.GlossaryInputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{
						InputUri: glossaryInputURI,
					},
				},
			},
		},
	}

	// The CreateGlossary operation is async.
	op, err := client.CreateGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateGlossary: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Created: %v\n", resp.GetName())
	fmt.Fprintf(w, "Input URI: %v\n", resp.InputConfig.GetGcsSource().GetInputUri())

	return nil
}

Java

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

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.CreateGlossaryMetadata;
import com.google.cloud.translate.v3.CreateGlossaryRequest;
import com.google.cloud.translate.v3.GcsSource;
import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.GlossaryInputConfig;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class CreateGlossary {

  public static void createGlossary() throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    List<String> languageCodes = new ArrayList<>();
    languageCodes.add("your-language-code");
    String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
    createGlossary(projectId, glossaryId, languageCodes, inputUri);
  }

  // Create a equivalent term sets glossary
  // https://cloud.google.com/translate/docs/advanced/glossary#format-glossary
  public static void createGlossary(
      String projectId, String glossaryId, List<String> languageCodes, String inputUri)
      throws IOException, ExecutionException, InterruptedException {

    // 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);
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);

      // Supported Languages: https://cloud.google.com/translate/docs/languages
      Glossary.LanguageCodesSet languageCodesSet =
          Glossary.LanguageCodesSet.newBuilder().addAllLanguageCodes(languageCodes).build();

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
      GlossaryInputConfig inputConfig =
          GlossaryInputConfig.newBuilder().setGcsSource(gcsSource).build();

      Glossary glossary =
          Glossary.newBuilder()
              .setName(glossaryName.toString())
              .setLanguageCodesSet(languageCodesSet)
              .setInputConfig(inputConfig)
              .build();

      CreateGlossaryRequest request =
          CreateGlossaryRequest.newBuilder()
              .setParent(parent.toString())
              .setGlossary(glossary)
              .build();

      // Start an asynchronous request
      OperationFuture<Glossary, CreateGlossaryMetadata> future =
          client.createGlossaryAsync(request);

      System.out.println("Waiting for operation to complete...");
      Glossary response = future.get();
      System.out.println("Created Glossary.");
      System.out.printf("Glossary name: %s\n", response.getName());
      System.out.printf("Entry count: %s\n", response.getEntryCount());
      System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
    }
  }
}

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 glossaryId = 'your-glossary-display-name';

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

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

async function createGlossary() {
  // Construct glossary
  const glossary = {
    languageCodesSet: {
      languageCodes: ['en', 'es'],
    },
    inputConfig: {
      gcsSource: {
        inputUri: 'gs://cloud-samples-data/translation/glossary.csv',
      },
    },
    name: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };

  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    glossary: glossary,
  };

  // Create glossary using a long-running operation
  const [operation] = await translationClient.createGlossary(request);

  // Wait for the operation to complete
  await operation.promise();

  console.log('Created glossary:');
  console.log(`InputUri ${request.glossary.inputConfig.gcsSource.inputUri}`);
}

createGlossary();

Python

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

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

from google.cloud import translate_v3 as translate


def create_glossary(
    project_id: str = "YOUR_PROJECT_ID",
    input_uri: str = "YOUR_INPUT_URI",
    glossary_id: str = "YOUR_GLOSSARY_ID",
    timeout: int = 180,
) -> translate.Glossary:
    """
    Create a equivalent term sets glossary. Glossary can be words or
    short phrases (usually fewer than five words).
    https://cloud.google.com/translate/docs/advanced/glossary#format-glossary
    """
    client = translate.TranslationServiceClient()

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    source_lang_code = "en"
    target_lang_code = "ja"
    location = "us-central1"  # The location of the glossary

    name = client.glossary_path(project_id, location, glossary_id)
    language_codes_set = translate.types.Glossary.LanguageCodesSet(
        language_codes=[source_lang_code, target_lang_code]
    )

    gcs_source = translate.types.GcsSource(input_uri=input_uri)

    input_config = translate.types.GlossaryInputConfig(gcs_source=gcs_source)

    glossary = translate.types.Glossary(
        name=name, language_codes_set=language_codes_set, input_config=input_config
    )

    parent = f"projects/{project_id}/locations/{location}"
    # glossary is a custom dictionary Translation API uses
    # to translate the domain-specific terminology.
    operation = client.create_glossary(parent=parent, glossary=glossary)

    result = operation.result(timeout)
    print(f"Created: {result.name}")
    print(f"Input Uri: {result.input_config.gcs_source.input_uri}")

    return result

שפות נוספות

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

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

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

סטטוס פעילות

יצירת משאב מילון מונחים היא פעולה ממושכת, ולכן היא עשויה להימשך זמן רב. אפשר לדגום את הסטטוס של הפעולה הזו כדי לראות אם היא הושלמה, או לבטל את הפעולה.

מידע נוסף זמין במאמר בנושא פעולות ממושכות.

שימוש במילוני מונחים

תרגום טקסט באמצעות מילון מונחים

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

REST

בדוגמה הזו מתורגם טקסט באמצעות מודל NMT שמוגדר כברירת מחדל ומילון מונחים.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • GLOSSARY_ID: מזהה מילון המונחים, למשל my-en-ru-glossary.
  • BOOLEAN: האם ההתאמות הן לא תלויות-רישיות. ערך ברירת המחדל הוא false.
  • BOOLEAN_CONTEXTUAL: האם נלקח בחשבון ההקשר בתרגום המונחים במילון. ערך ברירת המחדל הוא false.

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

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:translateText

תוכן בקשת JSON:

{
  "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.",
  "glossaryConfig": {
    "glossary": "projects/project-number/locations/us-central1/glossaries/GLOSSARY_ID",
    "ignoreCase": BOOLEAN,
    "contextual_translation_enabled": BOOLEAN_CONTEXTUAL
  }
}

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "glossaryTranslations": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора. Вы поделились нежелательной электронной почтой со я . Давайте поговорим о спаме и важности рейтинга в конфиденциальном режиме.",
    "glossaryConfig": {
      "glossary": "projects/project-number/locations/us-central1/glossaries/GLOSSARY_ID",
      "ignoreCase": BOOLEAN,
      "contextual_translation_enabled": BOOLEAN_CONTEXTUAL
    }
  },
  "translations": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора. Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о спаме и важности рейтинга в конфиденциальном режиме.",
  }
}

השדה translations מכיל את התרגום האוטומטי הרגיל לפני החלת המילון; השדה glossaryTranslations מכיל את התרגום אחרי החלת המילון. כשמגדירים את השדה contextual_translation_enabled לערך true, התגובה תכיל רק את השדה glossaryTranslations ולא את השדה translations.

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

// translateTextWithGlossary translates input text and returns translated text.
func translateTextWithGlossary(w io.Writer, projectID string, location string, sourceLang string, targetLang string, text string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// sourceLang := "en"
	// targetLang := "ja"
	// text := "Hello world"
	// glossaryID := "your-glossary-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},
		GlossaryConfig: &translatepb.TranslateTextGlossaryConfig{
			Glossary: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
		},
	}

	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.GetGlossaryTranslations() {
		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.GlossaryName;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
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 TranslateTextWithGlossary {

  public static void translateTextWithGlossary() 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 glossaryId = "your-glossary-display-name";
    translateTextWithGlossary(projectId, sourceLanguage, targetLanguage, text, glossaryId);
  }

  // Translates a given text using a glossary.
  public static void translateTextWithGlossary(
      String projectId,
      String sourceLanguage,
      String targetLanguage,
      String text,
      String glossaryId)
      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);

      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      TranslateTextGlossaryConfig glossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();

      // 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)
              .setGlossaryConfig(glossaryConfig)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getGlossaryTranslationsList()) {
        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 glossaryId = 'YOUR_GLOSSARY_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 translateTextWithGlossary() {
  const glossaryConfig = {
    glossary: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'es',
    glossaryConfig: glossaryConfig,
  };

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

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

translateTextWithGlossary();

Python

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

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


from google.cloud import translate


def translate_text_with_glossary(
    text: str = "YOUR_TEXT_TO_TRANSLATE",
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID",
) -> translate.TranslateTextResponse:
    """Translates a given text using a glossary.

    Args:
        text: The text to translate.
        project_id: The ID of the GCP project that owns the glossary.
        glossary_id: The ID of the glossary to use.

    Returns:
        The translated text."""
    client = translate.TranslationServiceClient()
    location = "us-central1"
    parent = f"projects/{project_id}/locations/{location}"

    glossary = client.glossary_path(
        project_id, "us-central1", glossary_id  # The location of the glossary
    )

    glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary)

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.translate_text(
        request={
            "contents": [text],
            "target_language_code": "ja",
            "source_language_code": "en",
            "parent": parent,
            "glossary_config": glossary_config,
        }
    )

    print("Translated text: \n")
    for translation in response.glossary_translations:
        print(f"\t {translation.translated_text}")

    return response

שפות נוספות

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

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

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

תרגומים מותאמים עם מילון מונחים

כדי להשתמש במילון מונחים עם בקשת תרגום דינמי, צריך לכלול בהגדרות הבקשה את מילון המונחים.

REST

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של Google Cloud הפרויקט
  • LOCATION: האזור שבו נמצא מערך הנתונים של המקור, לדוגמה us-central1.
  • DATASET_NAME: השם של מערך הנתונים שבו Cloud Translation משתמש כדי להתאים אישית את התרגומים, בפורמט projects/PROJECT_ID/locations/LOCATION/adaptiveMtDatasets/DATASET_ID. כדי לקבל את השמות של מערכי הנתונים, אפשר להציג רשימה של כל מערכי הנתונים בפרויקט.
  • SOURCE_TEXT: הטקסט לתרגום.
  • MIME_TYPE (אופציונלי): הפורמט של טקסט המקור, כמו ‫text/html או text/plain. כברירת מחדל, סוג ה-MIME מוגדר כ-text/plain.
  • GLOSSARY_ID: מזהה מילון המונחים, למשל my-en-ru-glossary.
  • BOOLEAN (אופציונלי): האם ההתאמות הן לא תלויות-רישיות. ערך ברירת המחדל הוא false.
  • BOOLEAN_CONTEXTUAL (אופציונלי): האם להתחשב בהקשר בתרגום מונחים במילון. ערך ברירת המחדל הוא false.

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

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

תוכן בקשת JSON:

{
  "dataset": "DATASET_NAME",
  "content": ["SOURCE_TEXT"],
  "mimeType": "MIME_TYPE",
  "glossaryConfig": {
    "glossary": "projects/project-number/locations/LOCATION/glossaries/GLOSSARY_ID",
    "ignoreCase": BOOLEAN,
    "contextual_translation_enabled": BOOLEAN_CONTEXTUAL
  }
}

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "translations": [
    {
      "translatedText": "TRANSLATED_TEXT"
    }
  ],
  "languageCode": "TARGET_LANGUAGE",
  "glossaryTranslations": {
    "translatedText": "TRANSLATED_TEXT",
    "glossaryConfig": {
      "glossary": "projects/project-number/locations/LOCATION/glossaries/GLOSSARY_ID",
      "ignoreCase": BOOLEAN,
      "contextual_translation_enabled": BOOLEAN_CONTEXTUAL
    }
  },
}

Java

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

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

  {% dynamic setvar launch_stage %}preview{% dynamic endsetvar %}
{% dynamic setvar launch_type %}feature{% dynamic endsetvar %}
{% include "cloud/_shared/_info_launch_stage_disclaimer.html" %}

/** Translates using AdaptiveMt. */
private static void adaptiveMtTranslate(
    TranslationServiceClient translationServiceClient, String projectId, String datasetId) {
  String adaptiveMtDatasetName =
      String.format(
          "projects/%s/locations/LOCATION/adaptiveMtDatasets/%s", projectId, datasetId);
  String glossaryId = "your-glossary-display-name";
  GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
  GlossaryConfig glossaryConfig =
      GlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();

  AdaptiveMtTranslateRequest request =
      AdaptiveMtTranslateRequest.newBuilder()
          .setParent(LocationName.of(projectId, "us-central1").toString())
          .setDataset(adaptiveMtDatasetName)
          .addContent("Sample translation text")
          .setGlossaryConfig(glossaryConfig)
          .build();
  AdaptiveMtTranslateResponse response = translationServiceClient.adaptiveMtTranslate(request);

  System.out.println("Translating using AdaptiveMt");
  System.out.println(response);
}



  

Node.js

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

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

  async function translate() {
  /**
  * TODO(developer): Uncomment these variables before running the sample.
  */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';
  // const glossaryId = 'YOUR_GLOSSARY_ID';

  const glossaryConfig = {
    glossary: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    dataset: `projects/${projectId}/locations/${location}/adaptiveMtDatasets/${
        adaptiveMtDatasetName}`,
    content: ['Sample translate query'],
    glossaryConfig: glossaryConfig,
  } const [response] = await translationClient.adaptiveMtTranslate(request)
  console.log('Translating')
  console.log(response)
}
  

Python

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

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

  def adaptive_mt_translate(
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID"):
    # Create a client
    client = translate.TranslationServiceClient()
    # Create a glossary
    glossary = client.glossary_path(
        project_id, "us-central1", glossary_id  # The location of the glossary
    )

    glossary_config = translate.GlossaryConfig(glossary=glossary)
    # Initialize the request
    request = translate.AdaptiveMtTranslateRequest(
        parent="projects/PROJECT_ID/locations/LOCATION",
        dataset="projects/PROJECT_ID/locations/LOCATION/adaptiveMtDatasets/DATASET_ID",
        content=["Sample translation request"]
        glossary_config=glossary_config,
    )
    # Make the request
    response = client.adaptive_mt_translate(request)
    # Handle the response
    print(response)
  

קבלת מידע על מילון מונחים

REST

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של פרויקט Google Cloud
  • glossary-id: מזהה המילון שלכם, לדוגמה, my-en-to-ru-glossary

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

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
  "languagePair": {
    "sourceLanguageCode": "en",
    "targetLanguageCode": "ru"
  },
  "inputConfig": {
    "gcsSource": {
  "inputUri": "gs://bucket-name/glossary-file-name"
    }
  },
  "entryCount": 9603
}


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

// getGlossary gets the specified glossary.
func getGlossary(w io.Writer, projectID string, location string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "glossary-id"

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

	req := &translatepb.GetGlossaryRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
	}

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

	fmt.Fprintf(w, "Glossary name: %v\n", resp.GetName())
	fmt.Fprintf(w, "Entry count: %v\n", resp.GetEntryCount())
	fmt.Fprintf(w, "Input URI: %v\n", resp.GetInputConfig().GetGcsSource().GetInputUri())

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GetGlossaryRequest;
import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetGlossary {

  public static void getGlossary() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    getGlossary(projectId, glossaryId);
  }

  // Get a particular glossary based on the glossary ID
  public static void getGlossary(String projectId, String glossaryId) 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)
      GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
      GetGlossaryRequest request =
          GetGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

      Glossary response = client.getGlossary(request);

      System.out.printf("Glossary name: %s\n", response.getName());
      System.out.printf("Entry count: %s\n", response.getEntryCount());
      System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
    }
  }
}

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 glossaryId = 'YOUR_GLOSSARY_ID';

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

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

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

  // Get glossary
  const [response] = await translationClient.getGlossary(request);

  console.log(`Glossary name: ${response.name}`);
  console.log(`Entry count: ${response.entryCount}`);
  console.log(`Input URI: ${response.inputConfig.gcsSource.inputUri}`);
}

getGlossary();

Python

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

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

from google.cloud import translate_v3 as translate


def get_glossary(
    project_id: str = "YOUR_PROJECT_ID", glossary_id: str = "YOUR_GLOSSARY_ID"
) -> translate.Glossary:
    """Get a particular glossary based on the glossary ID.

    Args:
        project_id: The GCP project ID.
        glossary_id: The ID of the glossary to retrieve.

    Returns:
        The glossary.
    """
    client = translate.TranslationServiceClient()

    name = client.glossary_path(project_id, "us-central1", glossary_id)

    response = client.get_glossary(name=name)
    print(f"Glossary name: {response.name}")
    print(f"Entry count: {response.entry_count}")
    print(f"Input URI: {response.input_config.gcs_source.input_uri}")

    return response

שפות נוספות

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

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

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

הצגת רשימה של מילוני מונחים

פרויקט יכול לכלול מילונים רבים. בקטע הזה מוסבר איך מאחזרים רשימה של מילוני המונחים שזמינים לפרויקט מסוים.

REST

בדוגמה הזו מפורטים כל המילונים שמשויכים לפרויקט שצוין.

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

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

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

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "glossaries": [
    {
      "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
      "languagePair": {
        "sourceLanguageCode": "en",
        "targetLanguageCode": "ru"
      },
      "inputConfig": {
        "gcsSource": {
          "inputUri": "gs://bucket-name/glossary-file-name"
        }
      },
      "entryCount": 9603
    },
    ...
  ]
}

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"
	"google.golang.org/api/iterator"
)

// listGlossaries gets the specified glossary.
func listGlossaries(w io.Writer, projectID string, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"

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

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

	it := client.ListGlossaries(ctx, req)

	// Iterate over all results
	for {
		glossary, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListGlossaries.Next: %w", err)
		}
		fmt.Fprintf(w, "Name: %v\n", glossary.GetName())
		fmt.Fprintf(w, "Entry count: %v\n", glossary.GetEntryCount())
		fmt.Fprintf(w, "Input URI: %v\n", glossary.GetInputConfig().GetGcsSource().GetInputUri())
		for _, languageCode := range glossary.GetLanguageCodesSet().GetLanguageCodes() {
			fmt.Fprintf(w, "Language code: %v\n", languageCode)
		}
		if languagePair := glossary.GetLanguagePair(); languagePair != nil {
			fmt.Fprintf(w, "Language pair: %v, %v\n",
				languagePair.GetSourceLanguageCode(), languagePair.GetTargetLanguageCode())
		}
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.ListGlossariesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class ListGlossaries {

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

  // List all the glossaries in a specified location
  public static void listGlossaries(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, "us-central1");
      ListGlossariesRequest request =
          ListGlossariesRequest.newBuilder().setParent(parent.toString()).build();

      for (Glossary responseItem : client.listGlossaries(request).iterateAll()) {
        System.out.printf("Glossary name: %s\n", responseItem.getName());
        System.out.printf("Entry count: %s\n", responseItem.getEntryCount());
        System.out.printf(
            "Input URI: %s\n", responseItem.getInputConfig().getGcsSource().getInputUri());
      }
    }
  }
}

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

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

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

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

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

  for (const glossary of response) {
    console.log(`Name: ${glossary.name}`);
    console.log(`Entry count: ${glossary.entryCount}`);
    console.log(`Input uri: ${glossary.inputConfig.gcsSource.inputUri}`);
    for (const languageCode of glossary.languageCodesSet.languageCodes) {
      console.log(`Language code: ${languageCode}`);
    }
  }
}

listGlossaries();

Python

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

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

from google.cloud import translate


def list_glossaries(project_id: str = "YOUR_PROJECT_ID") -> translate.Glossary:
    """List Glossaries.

    Args:
        project_id: The GCP project ID.

    Returns:
        The glossary.
    """
    client = translate.TranslationServiceClient()

    location = "us-central1"

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

    # Iterate over all results
    for glossary in client.list_glossaries(parent=parent):
        print(f"Name: {glossary.name}")
        print(f"Entry count: {glossary.entry_count}")
        print(f"Input uri: {glossary.input_config.gcs_source.input_uri}")

        # Note: You can create a glossary using one of two modes:
        # language_code_set or language_pair. When listing the information for
        # a glossary, you can only get information for the mode you used
        # when creating the glossary.
        for language_code in glossary.language_codes_set.language_codes:
            print(f"Language code: {language_code}")

    return glossary

שפות נוספות

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

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

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

עדכון מילון מונחים

אפשר לעדכן מילון מונחים כדי לשנות את השם שלו או להחליף את כל הערכים שלו בקובץ קלט חדש של מילון מונחים. אם אתם צריכים לבטל שינויים בערכים של המילון, אתם צריכים להשתמש בקובץ המילון המקורי כדי להחליף את המילון ששונה.

REST

כדי לעדכן מילון מונחים, שולחים בקשת PATCH באמצעות ה-method ‏glossary.patch. בדוגמה הבאה מעדכנים מילון מונחים של קבוצת מונחים מקבילה. משתמשים ב-method‏ list כדי למצוא את המזהה של מילון מונחים מסוים.

פרמטר השאילתה update_mask מציין אם מעדכנים את קובץ הקלט של המילון, את השם המוצג של המילון או את שניהם. צריך לציין לפחות פרמטר אחד של מסכת עדכון.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו נמצא המילון שרוצים לעדכן, למשל us-central1.
  • GLOSSARY_ID: המזהה של מילון מונחים קיים.
  • LANGUAGE_CODE: קוד השפה שמציין את השפות של אוסף המונחים המקביל הזה במילון המונחים.
  • GLOSSARY_FILE_PATH: המיקום ושם הקובץ של קובץ הקלט של המילון.

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

PATCH https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID?update_mask=input_config&update_mask=display_name

תוכן בקשת JSON:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID",
  "languageCodesSet": {
    "languageCodes": ["LANGUAGE_CODE", ...]
  },
  "inputConfig": {
    "gcsSource": {
      "inputUri": "gs://GLOSSARY_FILE_PATH"
    }
  }
}

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.UpdateGlossaryMetadata",
    "glossary": {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID",
      "languageCodesSet": {
        "languageCodes": ["LANGUAGE_CODE", ...]
      },
      "inputConfig": {
        "gcsSource": {
        "inputUri": "gs://GLOSSARY_FILE_PATH"
        }
      },
      "entryCount": NUMBER_OF_ENTRIES,
      "submitTime": "2022-04-22T23:16:30.628806944Z",
      "endTime": "2022-04-22T23:41:15.115797Z",
      "displayName": "GLOSSARY_ID"
    },
    "state": "RUNNING",
    "submitTime": "2022-04-22T23:50:24.337964527Z"
  }
}

שפות נוספות

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

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

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

מחיקת מילון מונחים

בדוגמה הבאה מוצג איך מוחקים מילון מונחים.

REST

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של פרויקט Google Cloud
  • glossary-id: מזהה המילון שלכם

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

DELETE https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id

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

אמור להתקבל קוד סטטוס של הצלחה (2xx) ותגובה ריקה.

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

// deleteGlossary deletes a glossary.
func deleteGlossary(w io.Writer, projectID string, location string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "glossary-id"

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

	req := &translatepb.DeleteGlossaryRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
	}

	// The DeleteGlossary operation is async.
	op, err := client.DeleteGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("DeleteGlossary: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Deleted: %v\n", resp.GetName())

	return nil
}

Java

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

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
import com.google.cloud.translate.v3.DeleteGlossaryRequest;
import com.google.cloud.translate.v3.DeleteGlossaryResponse;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class DeleteGlossary {

  public static void deleteGlossary() throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    deleteGlossary(projectId, glossaryId);
  }

  // Delete a specific glossary based on the glossary ID
  public static void deleteGlossary(String projectId, String glossaryId)
      throws InterruptedException, ExecutionException, 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)
      GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
      DeleteGlossaryRequest request =
          DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

      // Start an asynchronous request
      OperationFuture<DeleteGlossaryResponse, DeleteGlossaryMetadata> future =
          client.deleteGlossaryAsync(request);

      System.out.println("Waiting for operation to complete...");
      DeleteGlossaryResponse response = future.get();
      System.out.format("Deleted Glossary: %s\n", response.getName());
    }
  }
}

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 glossaryId = 'YOUR_GLOSSARY_ID';

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

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

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

  // Delete glossary using a long-running operation
  const [operation] = await translationClient.deleteGlossary(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();

  console.log(`Deleted glossary: ${response.name}`);
}

deleteGlossary();

Python

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

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

from google.cloud import translate_v3 as translate


def delete_glossary(
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID",
    timeout: int = 180,
) -> translate.Glossary:
    """Delete a specific glossary based on the glossary ID.

    Args:
        project_id: The ID of the GCP project that owns the glossary.
        glossary_id: The ID of the glossary to delete.
        timeout: The timeout for this request.

    Returns:
        The glossary that was deleted.
    """
    client = translate.TranslationServiceClient()

    name = client.glossary_path(project_id, "us-central1", glossary_id)

    operation = client.delete_glossary(name=name)
    result = operation.result(timeout)
    print(f"Deleted: {result.name}")

    return result

שפות נוספות

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

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

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

ניהול ערכים במילון המונחים

ערך במילון מונחים ממפה מונח בשפה אחת למונח בשפה אחרת. אפשר להוסיף רשומות חדשות למילון מונחים, להציג את כל הרשומות במילון מונחים קיים או לשנות רשומות קיימות.

יצירת רשומות חדשות

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

REST

בדוגמה הבאה נוצרת רשומה למילון מונחים של קבוצת מונחים מקבילה. אפשר ליצור רק רשומה אחת לכל בקשה. מידע נוסף זמין במאמר בנושא השיטה glossaryEntries.create.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו נמצא המילון שרוצים לעדכן, למשל us-central1.
  • GLOSSARY_ID: המזהה של מילון מונחים קיים.
  • LANGUAGE_CODE: קוד השפה שבה מוגדר המונח.
  • TERM: המונח שרוצים להוסיף למילון המונחים.
  • DESCRIPTION: מידע על הערך במילון המונחים.

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

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries

תוכן בקשת JSON:

{
  termsSet: {
   terms: {
     languageCode: "LANGUAGE_CODE",
     text: "TERM"
    },
    ...
  },
  description: "DESCRIPTION"
}

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

שפות נוספות

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

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

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

רשימת מונחים במילון

הצגת כל הערכים במילון מונחים קיים. האפשרות הזו שימושית אם, לדוגמה, אתם רוצים לבדוק אילו מונחים ואילו שפות מופיעים במילון מונחים מסוים.

REST

כדי להציג רשימה של כל הערכים במילון המונחים, שולחים בקשת GET באמצעות השיטה glossaryEntries.list.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו נמצא המילון שרוצים לעדכן, למשל us-central1.
  • GLOSSARY_ID: המזהה של מילון מונחים קיים.

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

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "glossaryEntries": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
      "termsSet": {
        "terms": [
          {
            "languageCode": "LANGUAGE_CODE",
            "text": "TERM"
          },
        ...
        ]
      },
      "description": "DESCRIPTION"
    },
    ...
  ]
}

שפות נוספות

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

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

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

קבלת ערך במילון מונחים

בוחרים ערך כדי לראות את הפרטים שלו.

REST

כדי לקבל רשומה ספציפית במילון המונחים, שולחים בקשת GET עם השיטה glossaryEntries.get. משתמשים בשיטת הרשימה כדי למצוא את המזהה של רשומה מסוימת.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו נמצא המילון שרוצים לעדכן, למשל us-central1.
  • GLOSSARY_ID: המזהה של מילון מונחים קיים.
  • GLOSSARY_ENTRY_ID: המזהה של ערך מילון מונחים קיים.

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

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

שפות נוספות

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

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

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

עדכון ערכים במילון המונחים

אפשר לעדכן ערך אחד או להחליף את כל הערכים במילון המונחים. כדי להחליף את כל הערכים, אפשר לעיין במאמר בנושא עדכון מילון מונחים.

כדי לשנות רשומה במילון מונחים חד-כיווני, צריך לספק צמד מונחים, שבו מונח אחד הוא בשפת המקור והמונח השני הוא בשפת היעד. כדי ליצור מילונים של קבוצות מונחים מקבילות, צריך לספק קבוצת מונחים שבה כל פריט מציין מונח וקוד שפה.

REST

בדוגמאות הבאות מוצג עדכון של רשומה במילון מונחים של קבוצת מונחים מקבילה. למידע נוסף, אפשר לעיין בשיטה glossaryEntries.patch.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו נמצא המילון שרוצים לעדכן, למשל us-central1.
  • GLOSSARY_ID: המזהה של מילון מונחים קיים שמכיל את הערך שרוצים לעדכן.
  • GLOSSARY_ENTRY_ID: המזהה של הערך במילון המונחים שרוצים לעדכן.
  • LANGUAGE_CODE: קוד השפה שבה מוגדר המונח.
  • TERM: המונח לעדכון.
  • DESCRIPTION: מידע על הערך במילון המונחים.

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

PATCH https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

תוכן בקשת JSON:

{
  termsSet: {
   terms: {
     languageCode: "LANGUAGE_CODE",
     text: "TERM"
    },
    ...
  },
  description: "DESCRIPTION"
}

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

שפות נוספות

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

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

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

מחיקת רשומה במילון המונחים

הסרת רשומה אחת במילון המונחים.

REST

כדי למחוק רשומה ספציפית במילון המונחים, שולחים בקשת DELETE באמצעות השיטה glossaryEntries.delete. משתמשים בשיטת הרשימה כדי למצוא את המזהה של רשומה מסוימת.

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

  • PROJECT_NUMBER_OR_ID: המזהה המספרי או האלפאנומרי של הפרויקט ב- Google Cloud .
  • LOCATION: האזור שבו נמצא המילון שרוצים לעדכן, למשל us-central1.
  • GLOSSARY_ID: המזהה של מילון מונחים קיים שמכיל את הערך שרוצים למחוק.
  • GLOSSARY_ENTRY_ID: המזהה של הערך במילון המונחים שרוצים למחוק.

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

DELETE https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

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

אמור להתקבל קוד סטטוס של הצלחה (2xx) ותגובה ריקה.

שפות נוספות

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

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

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

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

  • לקבלת עזרה בפתרון בעיות או שגיאות נפוצות, אפשר לעיין בדף פתרון בעיות.