Creating and using glossaries (Advanced)

A glossary is a custom dictionary the Translation API uses to consistently translate the customer's domain-specific terminology. This typically involves specifying how to translate a named entity.

Glossary use cases may involve:

  • Product names: For example, 'Google Home' must translate to 'Google Home'.
  • Ambiguous words: For example, the word 'bat' can mean a piece of sports equipment or an animal. If you know that you are translating words about sports, you might want to use a glossary to feed the Translation API the sports translation of 'bat', not the translation for the animal.
  • Borrowed words: For example, 'bouillabaisse' in French translates to 'bouillabaisse' in English. English borrowed the word 'bouillabaisse' from French in the 19th century. An English speaker lacking French cultural context might not know that bouillabaisse is a fish stew dish. Glossaries can override a translation so that 'bouillabaisse' in French translates to 'fish stew' in English.

Create a glossary

The terms in a glossary can be single tokens (words) or short phrases (usually fewer than five words). The current limit for the number of separate glossaries is 1000 per project.

The main steps for using a glossary are:

  1. Create a glossary file
  2. Create the glossary resource with our Translation API
  3. Specify which glossary to use when you request a translation

A project can have multiple glossaries. You can get a list of the available glossaries and can delete glossaries that you no longer need.

Creating a glossary file

Fundamentally, a glossary is a text file in which each line contains corresponding terms in multiple languages. The Translation API supports both unidirectional glossaries, which specify the desired translation for a single pair of source and target languages, and equivalent term sets, which identify the equivalent terms in multiple languages.

Unidirectional glossaries

The Translation API accepts TSV, CSV or TMX files.

Tab-separated values (.tsv)

The Translation API supports tab-separated files, where each row has this format:

  • Term in source language tab Term in target language

For example:

account\tcuenta
directions\tindicaciones

The tab-separated source data does not include language codes to identify the source and target languages. You identify the source and target language codes when you create the online glossary.

Comma-separated values (.csv)

CSV files have the same format as TSV, except a comma (",") is used as a column separator.

Translation Memory eXchange (.tmx)

Translation Memory eXchange (TMX) is a standard XML format for providing source and target translations. The Translation API supports input files in a format based on TMX version 1.4. This example illustrates the required structure:

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

The <header> element of a well-formed .tmx file must identify the source language using the srclang attribute, and every <tuv> element must identify the language of the contained text using the xml:lang attribute. You identify the source and target languages using their iso-639-1 codes.

All <tu> elements must contain a pair of <tuv> elements with the same source and target languages. If a <tu> element contains more than two <tuv> elements, the Translation API processes only the first <tuv> matching the source language and the first matching the target language and ignores the rest. If a <tu> element does not have a matching pair of <tuv> elements, the Translation API skips over the invalid <tu> element.

The Translation API strips the markup tags from around a <seg> element before processing it. If a <tuv> element contains more than one <seg> element, the Translation API concatenates their text into a single element with a space between them.

If the file contains XML tags other than those shown above, the Translation API ignores them.

If the file does not conform to proper XML and TMX format – for example, if it is missing an end tag or a <tmx> element – the Translation API aborts processing it. The Translation API also aborts processing if it skips more than 1024 invalid <tu> elements.

Equivalent term sets (.csv)

The Translation API only accepts .csv in the GTT (Google Translate Toolkit) format.

To define equivalent term sets, you create a multi-column CSV file in which each row lists a single glossary term in multiple languages.

The first row in the file is a header row identifying the language for each column, using its iso-639-1 or BCP-47 language code. You can also include optional columns for part of speech (pos) and a description (description).

Each subsequent row contains equivalent glossary terms in the languages identified in the header. You can leave columns blank if the term is not available in all languages.

Equivalent terms set

Create a glossary resource

Once you have the equivalent glossary terms identified, make the glossary available to the Translation API by creating the online glossary.

Unidirectional glossary

When creating a unidirectional glossary, you must indicate the language pair (language_pair), by specifying the source language (source_language_code), and the target language (target_language_code).

REST & CMD LINE

When you create a new glossary, you supply a glossary id (a resource name). For example:
projects/my-project/locations/us-central1/glossaries/my-en-to-ru-glossary
where my-project is the project-number-or-id, and my-en-ru-glossary is the glossary-id provided by you.

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID
  • glossary-id: your glossary ID, for example., my_en_ru_glossary
  • bucket-name: name of bucket where your glossary file is located
  • glossary-filename: filename of your glossary

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries

Request JSON body:

{
  "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"
    }
  }
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries

PowerShell

Save the request body in a file called request.json, and execute the following command:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "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"
  }
}

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .

using Google.Cloud.Translate.V3;
using System;
using System.Collections.Generic;

namespace Google.Cloud.Translate.V3.Samples
{
    public class TranslateV3CreateGlossary
    {
        /// <summary>
        /// Create Glossary
        /// </summary>
        public static void SampleCreateGlossary(string projectId, string glossaryId, string inputUri)
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // TODO(developer): Uncomment and set the following variables
            // string projectId = "[Google Cloud Project ID]"
            // string glossaryId = "my_glossary_id_123"
            // string inputUri = "gs://cloud-samples-data/translation/glossary.csv"
            CreateGlossaryRequest request = new CreateGlossaryRequest
            {
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
                Parent = new LocationName(projectId, "us-central1").ToString(),
                Glossary = new Glossary
                {
                    Name = new GlossaryName(projectId, "us-central1", glossaryId).ToString(),
                    LanguageCodesSet = new Glossary.Types.LanguageCodesSet
                    {
                        LanguageCodes =
                        {
                            "en", // source lang
                            "ja", // target lang
                        },
                    },
                    InputConfig = new GlossaryInputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                    },
                },
            };
            // Poll until the returned long-running operation is complete
            Glossary response = translationServiceClient.CreateGlossary(request).PollUntilCompleted().Result;
            Console.WriteLine("Created Glossary.");
            Console.WriteLine($"Glossary name: {response.Name}");
            Console.WriteLine($"Entry count: {response.EntryCount}");
            Console.WriteLine($"Input URI: {response.InputConfig.GcsSource.InputUri}");
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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 := "glossary-id"
	// glossaryInputURI := "gs://cloud-samples-data/translation/glossary.csv"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

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.concurrent.ExecutionException;

public class CreateGlossary {

  public static void createGlossary() throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "[Google Cloud Project ID]";
    String location = "us-central1";
    String glossaryId = "[Your Glossary ID]";
    String inputUri = "gs://cloud-samples-data/text.txt";
    createGlossary(projectId, location, glossaryId, inputUri);
  }

  // Create Glossary
  public static void createGlossary(
      String projectId, String location, String glossaryId, 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()) {
      LocationName parent = LocationName.of(projectId, location);
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      Glossary.LanguageCodesSet languageCodesSet =
          Glossary.LanguageCodesSet.newBuilder()
              .addLanguageCodes("en")
              .addLanguageCodes("ja")
              .build();
      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();

      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

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

/**
 * 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 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.
  // You can wait for now, or get results later.
  const [operation] = await translationClient.createGlossary(request);

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

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

createGlossary();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\V3\GcsSource;
use Google\Cloud\Translate\V3\Glossary;
use Google\Cloud\Translate\V3\GlossaryInputConfig;
use Google\Cloud\Translate\V3\Glossary\LanguageCodesSet;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = 'my_glossary_id_123';
// $inputUri = 'gs://cloud-samples-data/translation/glossary.csv';
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    'us-central1'
);
$formattedName = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);
$languageCodesElement = 'en';
$languageCodesElement2 = 'ja';
$languageCodes = [$languageCodesElement, $languageCodesElement2];
$languageCodesSet = new LanguageCodesSet();
$languageCodesSet->setLanguageCodes($languageCodes);
$gcsSource = (new GcsSource())
    ->setInputUri($inputUri);
$inputConfig = (new GlossaryInputConfig())
    ->setGcsSource($gcsSource);
$glossary = (new Glossary())
    ->setName($formattedName)
    ->setLanguageCodesSet($languageCodesSet)
    ->setInputConfig($inputConfig);

try {
    $operationResponse = $translationServiceClient->createGlossary(
        $formattedParent,
        $glossary
    );
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        printf('Created Glossary.' . PHP_EOL);
        printf('Glossary name: %s' . PHP_EOL, $response->getName());
        printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
        printf(
            'Input URI: %s' . PHP_EOL,
            $response->getInputConfig()
                ->getGcsSource()
                ->getInputUri()
        );
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

from google.cloud import translate

def sample_create_glossary(project_id, input_uri, glossary_id):
    """Create Glossary"""
    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # project_id = 'YOUR_PROJECT_ID'
    # glossary_id = 'glossary-id'
    # input_uri = 'gs://cloud-samples-data/translation/glossary.csv'
    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=['en', 'ja'])

    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 = client.location_path(project_id, location)

    operation = client.create_glossary(parent=parent, glossary=glossary)

    result = operation.result(timeout=90)
    print('Created: {}'.format(result.name))
    print('Input Uri: {}'.format(result.input_config.gcs_source.input_uri))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"
glossary_id = "[YOUR_GLOSSARY_ID]"

project_2 = "[Your Google Cloud Project ID]"
input_uri = "gs://translation_samples_beta/glossaries/glossary.csv"

parent = client.class.location_path project_id, location_id
glossary = {
  name:               client.class.glossary_path(project_2, location_id, glossary_id),
  language_codes_set: {
    language_codes: ["en", "ja"]
  },
  input_config:       {
    gcs_source: {
      input_uri: input_uri
    }
  }
}

operation = client.create_glossary parent, glossary

# Wait until the long running operation is done
operation.wait_until_done!
response = operation.response

puts "Created Glossary."
puts "Glossary name: #{response.name}"
puts "Entry count: #{response.entry_count}"
puts "Input URI: #{response.input_config.gcs_source.input_uri}"

Equivalent term sets glossary

Once you have the glossary terms identified in your equivalent term set, make the glossary available to the Translation API by creating the online glossary.

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID
  • glossary-id: your glossary ID
  • bucket-name: name of bucket where your glossary file is located
  • glossary-filename: filename of your glossary

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries

Request JSON body:

{
  "languageCodesSet": {
    "languageCodes": ["en", "en-GB", "ru", "fr", "pt-BR", "pt-PT", "es"]
  },
  "inputConfig": {
    "gcsSource": {
"inputUri": "gs://bucket-name/glossary-file-name"
    }
  }
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries

PowerShell

Save the request body in a file called request.json, and execute the following command:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "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"
  }
}

Operation status

Creating a glossary is a long-running operation, so it may take a substantial amount of time to complete. You can poll the status of this operation to see if it has completed, or you can cancel the operation.

For more information, see Long-running operations.

Use glossaries

Translate text with a glossary

In Translation API - Advanced, you explicitly specify which translation model to use for translating the text. You can also identify a glossary to use for domain-specific terminology.

REST & CMD LINE

This example translates text using the default NMT model and a glossary.

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID
  • glossary-id: your glossary ID e.g., my-en-ru-glossary

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText

Request JSON body:

{
  "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.",
  "glossary_config": {
    "glossary": "projects/project-number/locations/us-central1/glossaries/glossary-id"
  }
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:translateText

PowerShell

Save the request body in a file called request.json, and execute the following command:

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

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

You should receive a JSON response similar to the following:

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

The translations field contains the regular machine translation before the glossary is applied; the glossaryTranslations field contains the translation after the glossary is applied.

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .

using Google.Cloud.Translate.V3;
using System;
using System.Collections.Generic;

namespace Google.Cloud.Translate.V3.Samples
{
    public class TranslateV3TranslateTextWithGlossary
    {
        /// <summary>
        /// Translates a given text using a glossary.
        /// </summary>
        /// <param name="text">The content to translate in string format</param>
        /// <param name="sourceLanguage">Optional. The BCP-47 language code of the input text.</param>
        /// <param name="targetLanguage">Required. The BCP-47 language code to use for translation.</param>
        /// <param name="glossaryId">Specifies the glossary used for this translation.</param>
        public static void SampleTranslateTextWithGlossary(string text, string sourceLanguage, string targetLanguage, string projectId, string glossaryId)
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // TODO(developer): Uncomment and set the following variables
            // string text = "Hello, world!"
            // string sourceLanguage = "en"
            // string targetLanguage = "fr"
            // string projectId = "[Google Cloud Project ID]"
            // string glossaryId = "[YOUR_GLOSSARY_ID]"

            string glossaryPath = $"projects/{projectId}/locations/{"us-central1"}/glossaries/{glossaryId}";
            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate in string format
                    text,
                },
                TargetLanguageCode = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
                SourceLanguageCode = sourceLanguage,
                GlossaryConfig = new TranslateTextGlossaryConfig
                {
                    // Specifies the glossary used for this translation.
                    Glossary = glossaryPath,
                },
                MimeType = "text/plain",
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);
            // Display the translation for each input text provided
            foreach (Translation translation in response.GlossaryTranslations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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: %v", err)
	}
	defer client.Close()

	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
		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: %v", err)
	}

	// Display the translation for each input text provided
	for _, translation := range resp.GetTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

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 = "[Google Cloud Project ID]";
    String location = "us-central1";
    String sourceLanguage = "en";
    String targetLanguage = "fr";
    String text = "Hello, world!";
    String glossaryId = "[Your Glossary ID]";
    translateTextWithGlossary(
        projectId, location, sourceLanguage, targetLanguage, text, glossaryId);
  }

  // Translates a given text using a glossary.
  public static void translateTextWithGlossary(
      String projectId,
      String location,
      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()) {
      LocationName parent = LocationName.of(projectId, location);
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      TranslateTextGlossaryConfig glossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain") // Optional. Can be "text/plain" or "text/html".
              .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

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

/**
 * 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();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\V3\TranslateTextGlossaryConfig;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $sourceLanguage = 'en';
// $targetLanguage = 'fr';
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = '[YOUR_GLOSSARY_ID]';
$glossaryPath = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);
$contents = [$text];
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    'us-central1'
);
$glossaryConfig = new TranslateTextGlossaryConfig();
$glossaryConfig->setGlossary($glossaryPath);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';

try {
    $response = $translationServiceClient->translateText(
        $contents,
        $targetLanguage,
        $formattedParent,
        [
            'sourceLanguageCode' => $sourceLanguage,
            'glossaryConfig' => $glossaryConfig,
            'mimeType' => $mimeType
        ]
    );
    // Display the translation for each input text provided
    foreach ($response->getGlossaryTranslations() as $translation) {
        printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

from google.cloud import translate

def sample_translate_text_with_glossary(
    text, source_language, target_language, project_id, glossary_id
):
    """
    Translates a given text using a glossary.

    Args:
      text The content to translate in string format
      source_language Optional. The BCP-47 language code of the input text.
      target_language Required. The BCP-47 language code to use for translation.
      glossary_id Specifies the glossary used for this translation.
    """

    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # text = 'Hello, world!'
    # source_language = 'en'
    # target_language = 'fr'
    # project = '[Google Cloud Project ID]'
    # glossary_id = '[YOUR_GLOSSARY_ID]'
    contents = [text]
    parent = client.location_path(project_id, "us-central1")

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

    glossary_config = translate.types.TranslateTextGlossaryConfig(
        glossary=glossary)

    response = client.translate_text(
        contents,
        target_language_code=target_language,
        source_language_code=source_language,
        parent=parent,
        glossary_config=glossary_config,
        mime_type='text/plain'  # mime types: text/plain, text/html
    )

    for translation in response.glossary_translations:
        print(u"Translated text: {}".format(translation.translated_text))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"
glossary_id = "[YOUR_GLOSSARY_ID]"

# The content to translate in string format
contents = ["Hello, world!"]
# Required. The BCP-47 language code to use for translation.
target_language = "fr"
# Optional. The BCP-47 language code of the input text.
source_language = "en"
glossary_config = {
  # Specifies the glossary used for this translation.
  glossary: client.class.glossary_path(project_id, location_id, glossary_id)
}
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"
parent = client.class.location_path project_id, location_id

response = client.translate_text(
  contents, target_language, parent,
  source_language_code: source_language,
  glossary_config:      glossary_config,
  mime_type:            mime_type
)

# Display the translation for each input text provided
response.translations.each do |translation|
  puts "Translated text: #{translation.translated_text}"
end

Get information about a glossary

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID
  • glossary-id: your glossary ID, for example, "my-en-to-ru-glossary"

HTTP method and URL:

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

To send your request, choose one of these options:

curl

Execute the following command:

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

PowerShell

Execute the following command:

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

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

You should receive a JSON response similar to the following:

{
  "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
}


C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .

using Google.Cloud.Translate.V3;
using System;

namespace Google.Cloud.Translate.V3.Samples
{
    public class TranslateV3GetGlossary
    {
        /// <summary>
        /// Get Glossary
        /// </summary>
        public static void SampleGetGlossary(string projectId, string glossaryId)
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // TODO(developer): Uncomment and set the following variables
            // string projectId = "[Google Cloud Project ID]"
            // string glossaryId = "[Glossary ID]"
            GetGlossaryRequest request = new GetGlossaryRequest
            {
                GlossaryName = new GlossaryName(projectId, "us-central1", glossaryId),
            };
            Glossary response = translationServiceClient.GetGlossary(request);
            Console.WriteLine($"Glossary name: {response.Name}");
            Console.WriteLine($"Entry count: {response.EntryCount}");
            Console.WriteLine($"Input URI: {response.InputConfig.GcsSource.InputUri}");
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

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

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

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 = "[Google Cloud Project ID]";
    String location = "us-central1";
    String glossaryId = "[Your Glossary ID]";
    getGlossary(projectId, location, glossaryId);
  }

  // Get Glossary
  public static void getGlossary(String projectId, String location, 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()) {
      GlossaryName glossaryName = GlossaryName.of(projectId, location, 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

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

/**
 * 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(`Got glossary: ${response.name}`);
}

getGlossary();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = '[Glossary ID]';
$formattedName = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);

try {
    $response = $translationServiceClient->getGlossary($formattedName);
    printf('Glossary name: %s' . PHP_EOL, $response->getName());
    printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
    printf(
        'Input URI: %s' . PHP_EOL,
        $response->getInputConfig()
            ->getGcsSource()
            ->getInputUri()
    );
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

from google.cloud import translate

def sample_get_glossary(project_id, glossary_id):
    """Get Glossary"""

    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # project = '[Google Cloud Project ID]'
    # glossary_id = '[Glossary ID]'
    name = client.glossary_path(project_id, "us-central1", glossary_id)

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

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"
glossary_id = "[YOUR_GLOSSARY_ID]"

name = client.class.glossary_path project_id, location_id, glossary_id

response = client.get_glossary name

puts "Glossary name: #{response.name}"
puts "Entry count: #{response.entry_count}"
puts "Input URI: #{response.input_config.gcs_source.input_uri}"

List glossaries

A project can include numerous glossaries. This section describes how to retrieve a list of the available glossaries for a particular project.

REST & CMD LINE

This example lists all glossaries associated with the specified project.

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

GET https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries

To send your request, choose one of these options:

curl

Execute the following command:

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

PowerShell

Execute the following command:

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

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

You should receive a successful status code (2xx) and an empty response.

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .

using Google.Api.Gax;
using Google.Cloud.Translate.V3;
using System;

namespace Google.Cloud.Translate.V3.Samples
{
    public class TranslateV3ListGlossary
    {
        /// <summary>
        /// List Glossaries
        /// </summary>
        public static void SampleListGlossaries(string projectId)
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // TODO(developer): Uncomment and set the following variables
            // string project = "[Google Cloud Project ID]"
            ListGlossariesRequest request = new ListGlossariesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
            };
            PagedEnumerable<ListGlossariesResponse, Glossary> response = translationServiceClient.ListGlossaries(request);
            // Iterate over pages (of server-defined size), performing one RPC per page
            foreach (Glossary item in response)
            {
                Console.WriteLine($"Glossary name: {item.Name}");
                Console.WriteLine($"Entry count: {item.EntryCount}");
                Console.WriteLine($"Input URI: {item.InputConfig.GcsSource.InputUri}");
            }
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"google.golang.org/api/iterator"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

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

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

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 = "[Google Cloud Project ID]";
    String location = "us-central1";
    listGlossaries(projectId, location);
  }

  // List Glossaries
  public static void listGlossaries(String projectId, String location) 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()) {
      LocationName parent = LocationName.of(projectId, location);
      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

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

/**
 * 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();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    'us-central1'
);

try {
    // Iterate through all elements
    $pagedResponse = $translationServiceClient->listGlossaries($formattedParent);
    foreach ($pagedResponse->iterateAllElements() as $responseItem) {
        printf('Glossary name: %s' . PHP_EOL, $responseItem->getName());
        printf('Entry count: %s' . PHP_EOL, $responseItem->getEntryCount());
        printf(
            'Input URI: %s' . PHP_EOL,
            $responseItem->getInputConfig()
                ->getGcsSource()
                ->getInputUri()
        );
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

from google.cloud import translate

def sample_list_glossaries(project_id):
    """List Glossaries"""

    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # project_id = '[Google Cloud Project ID]'
    parent = client.location_path(project_id, "us-central1")

    # Iterate over all results
    for glossary in client.list_glossaries(parent):
        print('Name: {}'.format(glossary.name))
        print('Entry count: {}'.format(glossary.entry_count))
        print('Input uri: {}'.format(
            glossary.input_config.gcs_source.input_uri))
        for language_code in glossary.language_codes_set.language_codes:
            print('Language code: {}'.format(language_code))
        if glossary.language_pair:
            print(glossary.language_pair.source_language_code)
            print(glossary.language_pair.target_language_code)

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"

parent = client.class.location_path project_id, location_id

responses = client.list_glossaries parent

responses.each do |response|
  puts "Glossary name: #{response.name}"
  puts "Entry count: #{response.entry_count}"
  puts "Input URI: #{response.input_config.gcs_source.input_uri}"
end

Delete a glossary

The following example deletes a glossary.

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID
  • glossary-id: your glossary ID

HTTP method and URL:

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

To send your request, choose one of these options:

curl

Execute the following command:

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

PowerShell

Execute the following command:

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

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries/glossary-id " | Select-Object -Expand Content

You should receive a successful status code (2xx) and an empty response.

C#

Before trying this sample, follow the C# setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API C# API reference documentation .

using Google.Cloud.Translate.V3;
using System;

namespace Google.Cloud.Translate.V3.Samples
{
    public class TranslateV3DeleteGlossary
    {
        /// <summary>
        /// Delete Glossary
        /// </summary>
        public static void SampleDeleteGlossary(string projectId, string glossaryId)
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // TODO(developer): Uncomment and set the following variables
            // string project = "[Google Cloud Project ID]"
            // string glossaryId = "[Glossary ID]"
            DeleteGlossaryRequest request = new DeleteGlossaryRequest
            {
                GlossaryName = new GlossaryName(projectId, "us-central1", glossaryId),
            };
            // Poll until the returned long-running operation is complete
            DeleteGlossaryResponse response = translationServiceClient.DeleteGlossary(request).PollUntilCompleted().Result;
            Console.WriteLine("Deleted Glossary.");
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Java API reference documentation .

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 = "[Google Cloud Project ID]";
    String location = "us-central1";
    String glossaryId = "[Your Glossary ID]";
    deleteGlossary(projectId, location, glossaryId);
  }

  /** Delete Glossary */
  public static void deleteGlossary(String projectId, String location, 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()) {
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      DeleteGlossaryRequest request =
          DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

      OperationFuture<DeleteGlossaryResponse, DeleteGlossaryMetadata> future =
          client.deleteGlossaryAsync(request);

      System.out.println("Waiting for operation to complete...");
      DeleteGlossaryResponse response = future.get();
      System.out.println("Deleted Glossary.");
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Node.js API reference documentation .

/**
 * 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.
  // You can wait for now, or get results later.
  const [operation] = await translationClient.deleteGlossary(request);

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

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

deleteGlossary();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API PHP API reference documentation .

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = '[Glossary ID]';
$formattedName = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);

try {
    $operationResponse = $translationServiceClient->deleteGlossary($formattedName);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        printf('Deleted Glossary.' . PHP_EOL);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Python API reference documentation .

from google.cloud import translate

def sample_delete_glossary(project_id, glossary_id):
    """Delete Glossary"""
    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # project_id = 'YOUR_PROJECT_ID'
    # glossary_id = 'GLOSSARY_ID'

    parent = client.glossary_path(
        project_id,
        'us-central1',
        glossary_id)

    operation = client.delete_glossary(parent)
    result = operation.result(timeout=90)
    print('Deleted: {}'.format(result.name))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API Ruby API reference documentation .

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"
glossary_id = "[YOUR_GLOSSARY_ID]"

name = client.class.glossary_path project_id, location_id, glossary_id

operation = client.delete_glossary name

# Wait until the long running operation is done
operation.wait_until_done!
response = operation.response

puts "Deleted Glossary."

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Translation
Need help? Visit our support page.