TranslationServiceClient

TranslationServiceClient

Provides natural language translation operations.

Constructor

new TranslationServiceClient(optionsopt, gaxInstanceopt)

Construct an instance of TranslationServiceClient.

Parameters:
Name Type Attributes Description
options object <optional>

The configuration object. The options accepted by the constructor are described in detail in this document. The common options are:

Properties
Name Type Attributes Description
credentials object <optional>

Credentials object.

Properties
Name Type Attributes Description
client_email string <optional>
private_key string <optional>
email string <optional>

Account email address. Required when using a .pem or .p12 keyFilename.

keyFilename string <optional>

Full path to the a .json, .pem, or .p12 key downloaded from the Google Developers Console. If you provide a path to a JSON file, the projectId option below is not necessary. NOTE: .pem and .p12 require you to specify options.email as well.

port number <optional>

The port on which to connect to the remote host.

projectId string <optional>

The project ID from the Google Developer's Console, e.g. 'grape-spaceship-123'. We will also check the environment variable GCLOUD_PROJECT for your project ID. If your app is running in an environment which supports Application Default Credentials, your project ID will be detected automatically.

apiEndpoint string <optional>

The domain name of the API remote host.

clientConfig gax.ClientConfig <optional>

Client configuration override. Follows the structure of gapicConfig.

fallback boolean <optional>

Use HTTP/1.1 REST mode. For more information, please check the documentation.

gaxInstance gax <optional>

loaded instance of google-gax. Useful if you need to avoid loading the default gRPC version and want to use the fallback HTTP implementation. Load only fallback version and pass it to the constructor: const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC const client = new TranslationServiceClient({fallback: true}, gax);

Members

apiEndpoint

The DNS address for this API service.

apiEndpoint

The DNS address for this API service - same as servicePath.

port

The port for this API service.

scopes

The scopes needed to make gRPC calls for every method defined in this service.

servicePath

The DNS address for this API service.

Methods

(async) checkBatchTranslateDocumentProgress(name) → {Promise}

Check the status of the long running operation returned by batchTranslateDocument().

Parameters:
Name Type Description
name String

The operation name that will be passed.

Returns:
Type Description
Promise
  • The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. Location to make a regional call.
   *  Format: `projects/{project-number-or-id}/locations/{location-id}`.
   *  The `global` location is not supported for batch translation.
   *  Only AutoML Translation models or glossaries within the same region (have
   *  the same location-id) can be used, otherwise an INVALID_ARGUMENT (400)
   *  error is returned.
   */
  // const parent = 'abc123'
  /**
   *  Required. The BCP-47 language code of the input document if known, for
   *  example, "en-US" or "sr-Latn". Supported language codes are listed in
   *  Language Support (https://cloud.google.com/translate/docs/languages).
   */
  // const sourceLanguageCode = 'abc123'
  /**
   *  Required. The BCP-47 language code to use for translation of the input
   *  document. Specify up to 10 language codes here.
   */
  // const targetLanguageCodes = ['abc','def']
  /**
   *  Required. Input configurations.
   *  The total number of files matched should be <= 100.
   *  The total content size to translate should be <= 100M Unicode codepoints.
   *  The files must use UTF-8 encoding.
   */
  // const inputConfigs = [1,2,3,4]
  /**
   *  Required. Output configuration.
   *  If 2 input configs match to the same file (that is, same input path),
   *  we don't generate output for duplicate inputs.
   */
  // const outputConfig = {}
  /**
   *  Optional. The models to use for translation. Map's key is target language
   *  code. Map's value is the model name. Value can be a built-in general model,
   *  or an AutoML Translation model.
   *  The value format depends on model type:
   *  - AutoML Translation models:
   *    `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`
   *  - General (built-in) models:
   *    `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`,
   *  If the map is empty or a specific model is not requested for a language
   *  pair, then default google model (nmt) is used.
   */
  // const models = [1,2,3,4]
  /**
   *  Optional. Glossaries to be applied. It's keyed by target language code.
   */
  // const glossaries = [1,2,3,4]
  /**
   *  Optional. File format conversion map to be applied to all input files.
   *  Map's key is the original mime_type. Map's value is the target mime_type of
   *  translated documents.
   *  Supported file format conversion includes:
   *  - `application/pdf` to
   *    `application/vnd.openxmlformats-officedocument.wordprocessingml.document`
   *  If nothing specified, output files will be in the same format as the
   *  original file.
   */
  // const formatConversions = [1,2,3,4]
  /**
   *  Optional. This flag is to support user customized attribution.
   *  If not provided, the default is `Machine Translated by Google`.
   *  Customized attribution should follow rules in
   *  https://cloud.google.com/translate/attribution#attribution_and_logos
   */
  // const customizedAttribution = 'abc123'
  /**
   *  Optional. If true, use the text removal server to remove the shadow text on
   *  background image for native pdf translation.
   *  Shadow removal feature can only be enabled when
   *  is_translate_native_pdf_only: false && pdf_native_only: false
   */
  // const enableShadowRemovalNativePdf = true
  /**
   *  Optional. If true, enable auto rotation correction in DVS.
   */
  // const enableRotationCorrection = true

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

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

  async function callBatchTranslateDocument() {
    // Construct request
    const request = {
      parent,
      sourceLanguageCode,
      targetLanguageCodes,
      inputConfigs,
      outputConfig,
    };

    // Run request
    const [operation] = await translationClient.batchTranslateDocument(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callBatchTranslateDocument();

(async) checkBatchTranslateTextProgress(name) → {Promise}

Check the status of the long running operation returned by batchTranslateText().

Parameters:
Name Type Description
name String

The operation name that will be passed.

Returns:
Type Description
Promise
  • The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. Location to make a call. Must refer to a caller's project.
   *  Format: `projects/{project-number-or-id}/locations/{location-id}`.
   *  The `global` location is not supported for batch translation.
   *  Only AutoML Translation models or glossaries within the same region (have
   *  the same location-id) can be used, otherwise an INVALID_ARGUMENT (400)
   *  error is returned.
   */
  // const parent = 'abc123'
  /**
   *  Required. Source language code.
   */
  // const sourceLanguageCode = 'abc123'
  /**
   *  Required. Specify up to 10 language codes here.
   */
  // const targetLanguageCodes = ['abc','def']
  /**
   *  Optional. The models to use for translation. Map's key is target language
   *  code. Map's value is model name. Value can be a built-in general model,
   *  or an AutoML Translation model.
   *  The value format depends on model type:
   *  - AutoML Translation models:
   *    `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`
   *  - General (built-in) models:
   *    `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`,
   *  If the map is empty or a specific model is
   *  not requested for a language pair, then default google model (nmt) is used.
   */
  // const models = [1,2,3,4]
  /**
   *  Required. Input configurations.
   *  The total number of files matched should be <= 100.
   *  The total content size should be <= 100M Unicode codepoints.
   *  The files must use UTF-8 encoding.
   */
  // const inputConfigs = [1,2,3,4]
  /**
   *  Required. Output configuration.
   *  If 2 input configs match to the same file (that is, same input path),
   *  we don't generate output for duplicate inputs.
   */
  // const outputConfig = {}
  /**
   *  Optional. Glossaries to be applied for translation.
   *  It's keyed by target language code.
   */
  // const glossaries = [1,2,3,4]
  /**
   *  Optional. The labels with user-defined metadata for the request.
   *  Label keys and values can be no longer than 63 characters
   *  (Unicode codepoints), can only contain lowercase letters, numeric
   *  characters, underscores and dashes. International characters are allowed.
   *  Label values are optional. Label keys must start with a letter.
   *  See https://cloud.google.com/translate/docs/labels for more information.
   */
  // const labels = [1,2,3,4]

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

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

  async function callBatchTranslateText() {
    // Construct request
    const request = {
      parent,
      sourceLanguageCode,
      targetLanguageCodes,
      inputConfigs,
      outputConfig,
    };

    // Run request
    const [operation] = await translationClient.batchTranslateText(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callBatchTranslateText();

(async) checkCreateGlossaryProgress(name) → {Promise}

Check the status of the long running operation returned by createGlossary().

Parameters:
Name Type Description
name String

The operation name that will be passed.

Returns:
Type Description
Promise
  • The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The project name.
   */
  // const parent = 'abc123'
  /**
   *  Required. The glossary to create.
   */
  // const glossary = {}

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

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

  async function callCreateGlossary() {
    // Construct request
    const request = {
      parent,
      glossary,
    };

    // Run request
    const [operation] = await translationClient.createGlossary(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callCreateGlossary();

(async) checkDeleteGlossaryProgress(name) → {Promise}

Check the status of the long running operation returned by deleteGlossary().

Parameters:
Name Type Description
name String

The operation name that will be passed.

Returns:
Type Description
Promise
  • The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The name of the glossary to delete.
   */
  // const name = 'abc123'

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

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

  async function callDeleteGlossary() {
    // Construct request
    const request = {
      name,
    };

    // Run request
    const [operation] = await translationClient.deleteGlossary(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callDeleteGlossary();

close() → {Promise}

Terminate the gRPC channel and close the client.

The client will no longer be usable and all future behavior is undefined.

Returns:
Type Description
Promise

A promise that resolves when the client is closed.

getProjectId() → {Promise}

Return the project ID used by this class.

Returns:
Type Description
Promise

A promise that resolves to string containing the project ID.

glossaryPath(project, location, glossary) → {string}

Return a fully-qualified glossary resource name string.

Parameters:
Name Type Description
project string
location string
glossary string
Returns:
Type Description
string

Resource name string.

initialize() → {Promise}

Initialize the client. Performs asynchronous operations (such as authentication) and prepares the client. This function will be called automatically when any class method is called for the first time, but if you need to initialize it before calling an actual method, feel free to call initialize() directly.

You can await on this method if you want to make sure the client is initialized.

Returns:
Type Description
Promise

A promise that resolves to an authenticated service stub.

listGlossariesAsync(request, optionsopt) → {Object}

Equivalent to listGlossaries, but returns an iterable object.

for-await-of syntax is used with the iterable to get response elements on-demand.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Attributes Description
parent string

Required. The name of the project from which to list all of the glossaries.

pageSize number <optional>

Optional. Requested page size. The server may return fewer glossaries than requested. If unspecified, the server picks an appropriate default.

pageToken string <optional>

Optional. A token identifying a page of results the server should return. Typically, this is the value of [ListGlossariesResponse.next_page_token] returned from the previous call to ListGlossaries method. The first page is returned if page_tokenis empty or missing.

filter string <optional>

Optional. Filter specifying constraints of a list operation. Specify the constraint by the format of "key=value", where key must be "src" or "tgt", and the value must be a valid language code. For multiple restrictions, concatenate them by "AND" (uppercase only), such as: "src=en-US AND tgt=zh-CN". Notice that the exact match is used here, which means using 'en-US' and 'en' can lead to different results, which depends on the language code you used when you create the glossary. For the unidirectional glossaries, the "src" and "tgt" add restrictions on the source and target language code separately. For the equivalent term set glossaries, the "src" and/or "tgt" add restrictions on the term set. For example: "src=en-US AND tgt=zh-CN" will only pick the unidirectional glossaries which exactly match the source language code as "en-US" and the target language code "zh-CN", but all equivalent term set glossaries which contain "en-US" and "zh-CN" in their language set will be picked. If missing, no filtering is performed.

options object <optional>

Call options. See CallOptions for more details.

Returns:
Type Description
Object

An iterable Object that allows async iteration. When you iterate the returned iterable, each element will be an object representing Glossary. The API will be called under the hood as needed, once per the page, so you can stop the iteration when you don't need more results. Please see the documentation for more details and examples.

Example
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The name of the project from which to list all of the glossaries.
   */
  // const parent = 'abc123'
  /**
   *  Optional. Requested page size. The server may return fewer glossaries than
   *  requested. If unspecified, the server picks an appropriate default.
   */
  // const pageSize = 1234
  /**
   *  Optional. A token identifying a page of results the server should return.
   *  Typically, this is the value of ListGlossariesResponse.next_page_token 
   *  returned from the previous call to `ListGlossaries` method.
   *  The first page is returned if `page_token`is empty or missing.
   */
  // const pageToken = 'abc123'
  /**
   *  Optional. Filter specifying constraints of a list operation.
   *  Specify the constraint by the format of "key=value", where key must be
   *  "src" or "tgt", and the value must be a valid language code.
   *  For multiple restrictions, concatenate them by "AND" (uppercase only),
   *  such as: "src=en-US AND tgt=zh-CN". Notice that the exact match is used
   *  here, which means using 'en-US' and 'en' can lead to different results,
   *  which depends on the language code you used when you create the glossary.
   *  For the unidirectional glossaries, the "src" and "tgt" add restrictions
   *  on the source and target language code separately.
   *  For the equivalent term set glossaries, the "src" and/or "tgt" add
   *  restrictions on the term set.
   *  For example: "src=en-US AND tgt=zh-CN" will only pick the unidirectional
   *  glossaries which exactly match the source language code as "en-US" and the
   *  target language code "zh-CN", but all equivalent term set glossaries which
   *  contain "en-US" and "zh-CN" in their language set will be picked.
   *  If missing, no filtering is performed.
   */
  // const filter = 'abc123'

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

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

  async function callListGlossaries() {
    // Construct request
    const request = {
      parent,
    };

    // Run request
    const iterable = translationClient.listGlossariesAsync(request);
    for await (const response of iterable) {
        console.log(response);
    }
  }

  callListGlossaries();

listGlossariesStream(request, optionsopt) → {Stream}

Equivalent to method.name.toCamelCase(), but returns a NodeJS Stream object.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Attributes Description
parent string

Required. The name of the project from which to list all of the glossaries.

pageSize number <optional>

Optional. Requested page size. The server may return fewer glossaries than requested. If unspecified, the server picks an appropriate default.

pageToken string <optional>

Optional. A token identifying a page of results the server should return. Typically, this is the value of [ListGlossariesResponse.next_page_token] returned from the previous call to ListGlossaries method. The first page is returned if page_tokenis empty or missing.

filter string <optional>

Optional. Filter specifying constraints of a list operation. Specify the constraint by the format of "key=value", where key must be "src" or "tgt", and the value must be a valid language code. For multiple restrictions, concatenate them by "AND" (uppercase only), such as: "src=en-US AND tgt=zh-CN". Notice that the exact match is used here, which means using 'en-US' and 'en' can lead to different results, which depends on the language code you used when you create the glossary. For the unidirectional glossaries, the "src" and "tgt" add restrictions on the source and target language code separately. For the equivalent term set glossaries, the "src" and/or "tgt" add restrictions on the term set. For example: "src=en-US AND tgt=zh-CN" will only pick the unidirectional glossaries which exactly match the source language code as "en-US" and the target language code "zh-CN", but all equivalent term set glossaries which contain "en-US" and "zh-CN" in their language set will be picked. If missing, no filtering is performed.

options object <optional>

Call options. See CallOptions for more details.

Returns:
Type Description
Stream

An object stream which emits an object representing Glossary on 'data' event. The client library will perform auto-pagination by default: it will call the API as many times as needed. Note that it can affect your quota. We recommend using listGlossariesAsync() method described below for async iteration which you can stop as needed. Please see the documentation for more details and examples.

locationPath(project, location) → {string}

Return a fully-qualified location resource name string.

Parameters:
Name Type Description
project string
location string
Returns:
Type Description
string

Resource name string.

matchGlossaryFromGlossaryName(glossaryName) → {string}

Parse the glossary from Glossary resource.

Parameters:
Name Type Description
glossaryName string

A fully-qualified path representing Glossary resource.

Returns:
Type Description
string

A string representing the glossary.

matchLocationFromGlossaryName(glossaryName) → {string}

Parse the location from Glossary resource.

Parameters:
Name Type Description
glossaryName string

A fully-qualified path representing Glossary resource.

Returns:
Type Description
string

A string representing the location.

matchLocationFromLocationName(locationName) → {string}

Parse the location from Location resource.

Parameters:
Name Type Description
locationName string

A fully-qualified path representing Location resource.

Returns:
Type Description
string

A string representing the location.

matchProjectFromGlossaryName(glossaryName) → {string}

Parse the project from Glossary resource.

Parameters:
Name Type Description
glossaryName string

A fully-qualified path representing Glossary resource.

Returns:
Type Description
string

A string representing the project.

matchProjectFromLocationName(locationName) → {string}

Parse the project from Location resource.

Parameters:
Name Type Description
locationName string

A fully-qualified path representing Location resource.

Returns:
Type Description
string

A string representing the project.