Cloud Translation V3 Client - Class TranslationServiceClient (1.15.4)

Reference documentation and code samples for the Cloud Translation V3 Client class TranslationServiceClient.

Service Description: Provides natural language translation operations.

This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started:

$translationServiceClient = new TranslationServiceClient();
try {
    $formattedParent = $translationServiceClient->locationName('[PROJECT]', '[LOCATION]');
    $sourceLanguageCode = 'source_language_code';
    $targetLanguageCodes = [];
    $inputConfigs = [];
    $outputConfig = new BatchDocumentOutputConfig();
    $operationResponse = $translationServiceClient->batchTranslateDocument($formattedParent, $sourceLanguageCode, $targetLanguageCodes, $inputConfigs, $outputConfig);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
    // doSomethingWith($result)
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
    // Alternatively:
    // start the operation, keep the operation name, and resume later
    $operationResponse = $translationServiceClient->batchTranslateDocument($formattedParent, $sourceLanguageCode, $targetLanguageCodes, $inputConfigs, $outputConfig);
    $operationName = $operationResponse->getName();
    // ... do other work
    $newOperationResponse = $translationServiceClient->resumeOperation($operationName, 'batchTranslateDocument');
    while (!$newOperationResponse->isDone()) {
        // ... do other work
        $newOperationResponse->reload();
    }
    if ($newOperationResponse->operationSucceeded()) {
        $result = $newOperationResponse->getResult();
    // doSomethingWith($result)
    } else {
        $error = $newOperationResponse->getError();
        // handleError($error)
    }
} finally {
    $translationServiceClient->close();
}

Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parseName method to extract the individual identifiers contained within formatted names that are returned by the API.

This service has a new (beta) implementation. See Google\Cloud\Translate\V3\Client\TranslationServiceClient to use the new surface.

Namespace

Google \ Cloud \ Translate \ V3

Methods

__construct

Constructor.

Parameters
NameDescription
options array

Optional. Options for configuring the service API wrapper.

↳ apiEndpoint string

The address of the API remote host. May optionally include the port, formatted as "

↳ credentials string|array|FetchAuthTokenInterface|CredentialsWrapper

The credentials to be used by the client to authorize API calls. This option accepts either a path to a credentials file, or a decoded credentials file as a PHP array. Advanced usage: In addition, this option can also accept a pre-constructed Google\Auth\FetchAuthTokenInterface object or Google\ApiCore\CredentialsWrapper object. Note that when one of these objects are provided, any settings in $credentialsConfig will be ignored.

↳ credentialsConfig array

Options used to configure credentials, including auth token caching, for the client. For a full list of supporting configuration options, see Google\ApiCore\CredentialsWrapper::build() .

↳ disableRetries bool

Determines whether or not retries defined by the client configuration should be disabled. Defaults to false.

↳ clientConfig string|array

Client method configuration, including retry settings. This option can be either a path to a JSON file, or a PHP array containing the decoded JSON data. By default this settings points to the default client config file, which is provided in the resources folder.

↳ transport string|TransportInterface

The transport used for executing network requests. May be either the string rest or grpc. Defaults to grpc if gRPC support is detected on the system. Advanced usage: Additionally, it is possible to pass in an already instantiated Google\ApiCore\Transport\TransportInterface object. Note that when this object is provided, any settings in $transportConfig, and any $apiEndpoint setting, will be ignored.

↳ transportConfig array

Configuration options that will be used to construct the transport. Options for each supported transport type should be passed in a key for that transport. For example: $transportConfig = [ 'grpc' => [...], 'rest' => [...], ]; See the Google\ApiCore\Transport\GrpcTransport::build() and Google\ApiCore\Transport\RestTransport::build() methods for the supported options.

↳ clientCertSource callable

A callable which returns the client cert as a string. This can be used to provide a certificate and private key to the transport layer for mTLS.

batchTranslateDocument

Translates a large volume of document in asynchronous batch mode.

This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location.

This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.

Parameters
NameDescription
parent string

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.

sourceLanguageCode string

Required. The ISO-639 language code of the input document if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support.

targetLanguageCodes string[]

Required. The ISO-639 language code to use for translation of the input document. Specify up to 10 language codes here.

inputConfigs array<Google\Cloud\Translate\V3\BatchDocumentInputConfig>

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.

outputConfig Google\Cloud\Translate\V3\BatchDocumentOutputConfig

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.

optionalArgs array

Optional.

↳ models array

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.

↳ glossaries array

Optional. Glossaries to be applied. It's keyed by target language code.

↳ formatConversions array

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.

↳ customizedAttribution string

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

↳ enableShadowRemovalNativePdf bool

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

↳ enableRotationCorrection bool

Optional. If true, enable auto rotation correction in DVS.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\BatchDocumentInputConfig;
use Google\Cloud\Translate\V3\BatchDocumentOutputConfig;
use Google\Cloud\Translate\V3\BatchTranslateDocumentResponse;
use Google\Cloud\Translate\V3\TranslationServiceClient;
use Google\Rpc\Status;

/**
 * @param string $formattedParent            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. Please see
 *                                           {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $sourceLanguageCode         The ISO-639 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).
 * @param string $targetLanguageCodesElement The ISO-639 language code to use for translation of the input
 *                                           document. Specify up to 10 language codes here.
 */
function batch_translate_document_sample(
    string $formattedParent,
    string $sourceLanguageCode,
    string $targetLanguageCodesElement
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $targetLanguageCodes = [$targetLanguageCodesElement,];
    $inputConfigs = [new BatchDocumentInputConfig()];
    $outputConfig = new BatchDocumentOutputConfig();

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->batchTranslateDocument(
            $formattedParent,
            $sourceLanguageCode,
            $targetLanguageCodes,
            $inputConfigs,
            $outputConfig
        );
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var BatchTranslateDocumentResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $sourceLanguageCode = '[SOURCE_LANGUAGE_CODE]';
    $targetLanguageCodesElement = '[TARGET_LANGUAGE_CODES]';

    batch_translate_document_sample($formattedParent, $sourceLanguageCode, $targetLanguageCodesElement);
}

batchTranslateText

Translates a large volume of text in asynchronous batch mode.

This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location.

This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.

Parameters
NameDescription
parent string

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.

sourceLanguageCode string

Required. Source language code.

targetLanguageCodes string[]

Required. Specify up to 10 language codes here.

inputConfigs array<Google\Cloud\Translate\V3\InputConfig>

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.

outputConfig Google\Cloud\Translate\V3\OutputConfig

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.

optionalArgs array

Optional.

↳ models array

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.

↳ glossaries array

Optional. Glossaries to be applied for translation. It's keyed by target language code.

↳ labels array

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/advanced/labels for more information.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\BatchTranslateResponse;
use Google\Cloud\Translate\V3\InputConfig;
use Google\Cloud\Translate\V3\OutputConfig;
use Google\Cloud\Translate\V3\TranslationServiceClient;
use Google\Rpc\Status;

/**
 * @param string $formattedParent            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. Please see
 *                                           {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $sourceLanguageCode         Source language code.
 * @param string $targetLanguageCodesElement Specify up to 10 language codes here.
 */
function batch_translate_text_sample(
    string $formattedParent,
    string $sourceLanguageCode,
    string $targetLanguageCodesElement
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $targetLanguageCodes = [$targetLanguageCodesElement,];
    $inputConfigs = [new InputConfig()];
    $outputConfig = new OutputConfig();

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->batchTranslateText(
            $formattedParent,
            $sourceLanguageCode,
            $targetLanguageCodes,
            $inputConfigs,
            $outputConfig
        );
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var BatchTranslateResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $sourceLanguageCode = '[SOURCE_LANGUAGE_CODE]';
    $targetLanguageCodesElement = '[TARGET_LANGUAGE_CODES]';

    batch_translate_text_sample($formattedParent, $sourceLanguageCode, $targetLanguageCodesElement);
}

createGlossary

Creates a glossary and returns the long-running operation. Returns NOT_FOUND, if the project doesn't exist.

Parameters
NameDescription
parent string

Required. The project name.

glossary Google\Cloud\Translate\V3\Glossary

Required. The glossary to create.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\Glossary;
use Google\Cloud\Translate\V3\TranslationServiceClient;
use Google\Rpc\Status;

/**
 * @param string $formattedParent The project name. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $glossaryName    The resource name of the glossary. Glossary names have the form
 *                                `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`.
 */
function create_glossary_sample(string $formattedParent, string $glossaryName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $glossary = (new Glossary())
        ->setName($glossaryName);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->createGlossary($formattedParent, $glossary);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var Glossary $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $glossaryName = '[NAME]';

    create_glossary_sample($formattedParent, $glossaryName);
}

deleteGlossary

Deletes a glossary, or cancels glossary construction if the glossary isn't created yet.

Returns NOT_FOUND, if the glossary doesn't exist.

Parameters
NameDescription
name string

Required. The name of the glossary to delete.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\DeleteGlossaryResponse;
use Google\Cloud\Translate\V3\TranslationServiceClient;
use Google\Rpc\Status;

/**
 * @param string $formattedName The name of the glossary to delete. Please see
 *                              {@see TranslationServiceClient::glossaryName()} for help formatting this field.
 */
function delete_glossary_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->deleteGlossary($formattedName);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var DeleteGlossaryResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::glossaryName('[PROJECT]', '[LOCATION]', '[GLOSSARY]');

    delete_glossary_sample($formattedName);
}

detectLanguage

Detects the language of text within a request.

Parameters
NameDescription
parent string

Required. Project or location to make a call. Must refer to a caller's project.

Format: projects/{project-number-or-id}/locations/{location-id} or projects/{project-number-or-id}.

For global calls, use projects/{project-number-or-id}/locations/global or projects/{project-number-or-id}.

Only models within the same region (has same location-id) can be used. Otherwise an INVALID_ARGUMENT (400) error is returned.

optionalArgs array

Optional.

↳ model string

Optional. The language detection model to be used. Format: projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id} Only one language detection model is currently supported: projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default. If not specified, the default model is used.

↳ content string

The content of the input stored as a string.

↳ mimeType string

Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type defaults to "text/html".

↳ labels array

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/advanced/labels for more information.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\DetectLanguageResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\DetectLanguageResponse;
use Google\Cloud\Translate\V3\TranslationServiceClient;

/**
 * @param string $formattedParent Project or location to make a call. Must refer to a caller's
 *                                project.
 *
 *                                Format: `projects/{project-number-or-id}/locations/{location-id}` or
 *                                `projects/{project-number-or-id}`.
 *
 *                                For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                `projects/{project-number-or-id}`.
 *
 *                                Only models within the same region (has same location-id) can be used.
 *                                Otherwise an INVALID_ARGUMENT (400) error is returned. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function detect_language_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Call the API and handle any network failures.
    try {
        /** @var DetectLanguageResponse $response */
        $response = $translationServiceClient->detectLanguage($formattedParent);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    detect_language_sample($formattedParent);
}

getGlossary

Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist.

Parameters
NameDescription
name string

Required. The name of the glossary to retrieve.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\Glossary
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Glossary;
use Google\Cloud\Translate\V3\TranslationServiceClient;

/**
 * @param string $formattedName The name of the glossary to retrieve. Please see
 *                              {@see TranslationServiceClient::glossaryName()} for help formatting this field.
 */
function get_glossary_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Call the API and handle any network failures.
    try {
        /** @var Glossary $response */
        $response = $translationServiceClient->getGlossary($formattedName);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::glossaryName('[PROJECT]', '[LOCATION]', '[GLOSSARY]');

    get_glossary_sample($formattedName);
}

getSupportedLanguages

Returns a list of supported languages for translation.

Parameters
NameDescription
parent string

Required. Project or location to make a call. Must refer to a caller's project.

Format: projects/{project-number-or-id} or projects/{project-number-or-id}/locations/{location-id}.

For global calls, use projects/{project-number-or-id}/locations/global or projects/{project-number-or-id}.

Non-global location is required for AutoML models.

Only models within the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.

optionalArgs array

Optional.

↳ displayLanguageCode string

Optional. The language to use to return localized, human readable names of supported languages. If missing, then display names are not returned in a response.

↳ model string

Optional. Get supported languages of this model. The 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, Returns languages supported by the specified model. If missing, we get supported languages of Google general NMT model.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\SupportedLanguages
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\SupportedLanguages;
use Google\Cloud\Translate\V3\TranslationServiceClient;

/**
 * @param string $formattedParent Project or location to make a call. Must refer to a caller's
 *                                project.
 *
 *                                Format: `projects/{project-number-or-id}` or
 *                                `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                `projects/{project-number-or-id}`.
 *
 *                                Non-global location is required for AutoML models.
 *
 *                                Only models within the same region (have same location-id) can be used,
 *                                otherwise an INVALID_ARGUMENT (400) error is returned. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function get_supported_languages_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Call the API and handle any network failures.
    try {
        /** @var SupportedLanguages $response */
        $response = $translationServiceClient->getSupportedLanguages($formattedParent);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    get_supported_languages_sample($formattedParent);
}

listGlossaries

Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't exist.

Parameters
NameDescription
parent string

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

optionalArgs array

Optional.

↳ pageSize int

The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.

↳ pageToken string

A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.

↳ filter string

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.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Translate\V3\Glossary;
use Google\Cloud\Translate\V3\TranslationServiceClient;

/**
 * @param string $formattedParent The name of the project from which to list all of the glossaries. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function list_glossaries_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $translationServiceClient->listGlossaries($formattedParent);

        /** @var Glossary $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    list_glossaries_sample($formattedParent);
}

translateDocument

Translates documents in synchronous mode.

Parameters
NameDescription
parent string

Required. Location to make a regional call.

Format: projects/{project-number-or-id}/locations/{location-id}.

For global calls, use projects/{project-number-or-id}/locations/global or projects/{project-number-or-id}.

Non-global location is required for requests using AutoML models or custom glossaries.

Models and glossaries must be within the same region (have the same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.

targetLanguageCode string

Required. The ISO-639 language code to use for translation of the input document, set to one of the language codes listed in Language Support.

documentInputConfig Google\Cloud\Translate\V3\DocumentInputConfig

Required. Input configurations.

optionalArgs array

Optional.

↳ sourceLanguageCode string

Optional. The ISO-639 language code of the input document if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the API attempts to identify the source language automatically and returns the source language within the response. Source language must be specified if the request contains a glossary or a custom model.

↳ documentOutputConfig DocumentOutputConfig

Optional. Output configurations. Defines if the output file should be stored within Cloud Storage as well as the desired output format. If not provided the translated file will only be returned through a byte-stream and its output mime type will be the same as the input file's mime type.

↳ model string

Optional. The model type requested for this translation. The 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 not provided, the default Google model (NMT) will be used for translation.

↳ glossaryConfig TranslateTextGlossaryConfig

Optional. Glossary to be applied. The glossary must be within the same region (have the same location-id) as the model, otherwise an INVALID_ARGUMENT (400) error is returned.

↳ labels array

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/advanced/labels for more information.

↳ customizedAttribution string

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

↳ isTranslateNativePdfOnly bool

Optional. is_translate_native_pdf_only field for external customers. If true, the page limit of online native pdf translation is 300 and only native pdf pages will be translated.

↳ enableShadowRemovalNativePdf bool

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

↳ enableRotationCorrection bool

Optional. If true, enable auto rotation correction in DVS.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\TranslateDocumentResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\DocumentInputConfig;
use Google\Cloud\Translate\V3\TranslateDocumentResponse;
use Google\Cloud\Translate\V3\TranslationServiceClient;

/**
 * @param string $parent             Location to make a regional call.
 *
 *                                   Format: `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                   For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                   `projects/{project-number-or-id}`.
 *
 *                                   Non-global location is required for requests using AutoML models or custom
 *                                   glossaries.
 *
 *                                   Models and glossaries must be within the same region (have the same
 *                                   location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
 * @param string $targetLanguageCode The ISO-639 language code to use for translation of the input
 *                                   document, set to one of the language codes listed in Language Support.
 */
function translate_document_sample(string $parent, string $targetLanguageCode): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $documentInputConfig = new DocumentInputConfig();

    // Call the API and handle any network failures.
    try {
        /** @var TranslateDocumentResponse $response */
        $response = $translationServiceClient->translateDocument(
            $parent,
            $targetLanguageCode,
            $documentInputConfig
        );
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $parent = '[PARENT]';
    $targetLanguageCode = '[TARGET_LANGUAGE_CODE]';

    translate_document_sample($parent, $targetLanguageCode);
}

translateText

Translates input text and returns translated text.

Parameters
NameDescription
contents string[]

Required. The content of the input in string format. We recommend the total content be less than 30,000 codepoints. The max length of this field is 1024. Use BatchTranslateText for larger text.

targetLanguageCode string

Required. The ISO-639 language code to use for translation of the input text, set to one of the language codes listed in Language Support.

parent string

Required. Project or location to make a call. Must refer to a caller's project.

Format: projects/{project-number-or-id} or projects/{project-number-or-id}/locations/{location-id}.

For global calls, use projects/{project-number-or-id}/locations/global or projects/{project-number-or-id}.

Non-global location is required for requests using AutoML models or custom glossaries.

Models and glossaries must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.

optionalArgs array

Optional.

↳ mimeType string

Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type defaults to "text/html".

↳ sourceLanguageCode string

Optional. The ISO-639 language code of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the API attempts to identify the source language automatically and returns the source language within the response.

↳ model string

Optional. The model type requested for this translation. The 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, For global (non-regionalized) requests, use location-id global. For example, projects/{project-number-or-id}/locations/global/models/general/nmt. If not provided, the default Google model (NMT) will be used

↳ glossaryConfig TranslateTextGlossaryConfig

Optional. Glossary to be applied. The glossary must be within the same region (have the same location-id) as the model, otherwise an INVALID_ARGUMENT (400) error is returned.

↳ labels array

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/advanced/labels for more information.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\TranslateTextResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\TranslateTextResponse;
use Google\Cloud\Translate\V3\TranslationServiceClient;

/**
 * @param string $contentsElement    The content of the input in string format.
 *                                   We recommend the total content be less than 30,000 codepoints. The max
 *                                   length of this field is 1024. Use BatchTranslateText for larger text.
 * @param string $targetLanguageCode The ISO-639 language code to use for translation of the input
 *                                   text, set to one of the language codes listed in Language Support.
 * @param string $formattedParent    Project or location to make a call. Must refer to a caller's
 *                                   project.
 *
 *                                   Format: `projects/{project-number-or-id}` or
 *                                   `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                   For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                   `projects/{project-number-or-id}`.
 *
 *                                   Non-global location is required for requests using AutoML models or
 *                                   custom glossaries.
 *
 *                                   Models and glossaries must be within the same region (have same
 *                                   location-id), otherwise an INVALID_ARGUMENT (400) error is returned. Please see
 *                                   {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function translate_text_sample(
    string $contentsElement,
    string $targetLanguageCode,
    string $formattedParent
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $contents = [$contentsElement,];

    // Call the API and handle any network failures.
    try {
        /** @var TranslateTextResponse $response */
        $response = $translationServiceClient->translateText(
            $contents,
            $targetLanguageCode,
            $formattedParent
        );
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $contentsElement = '[CONTENTS]';
    $targetLanguageCode = '[TARGET_LANGUAGE_CODE]';
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    translate_text_sample($contentsElement, $targetLanguageCode, $formattedParent);
}

getOperationsClient

Return an OperationsClient object with the same endpoint as $this.

Returns
TypeDescription
Google\ApiCore\LongRunning\OperationsClient

resumeOperation

Resume an existing long running operation that was previously started by a long running API method. If $methodName is not provided, or does not match a long running API method, then the operation can still be resumed, but the OperationResponse object will not deserialize the final response.

Parameters
NameDescription
operationName string

The name of the long running operation

methodName string

The name of the method used to start the operation

Returns
TypeDescription
Google\ApiCore\OperationResponse

static::glossaryName

Formats a string containing the fully-qualified path to represent a glossary resource.

Parameters
NameDescription
project string
location string
glossary string
Returns
TypeDescription
stringThe formatted glossary resource.

static::locationName

Formats a string containing the fully-qualified path to represent a location resource.

Parameters
NameDescription
project string
location string
Returns
TypeDescription
stringThe formatted location resource.

static::parseName

Parses a formatted name string and returns an associative array of the components in the name.

The following name formats are supported: Template: Pattern

  • glossary: projects/{project}/locations/{location}/glossaries/{glossary}
  • location: projects/{project}/locations/{location}

The optional $template argument can be supplied to specify a particular pattern, and must match one of the templates listed above. If no $template argument is provided, or if the $template argument does not match one of the templates listed, then parseName will check each of the supported templates, and return the first match.

Parameters
NameDescription
formattedName string

The formatted name string

template string

Optional name of template to match

Returns
TypeDescription
arrayAn associative array from name component IDs to component values.

Constants

SERVICE_NAME

Value: 'google.cloud.translation.v3.TranslationService'

The name of the service.

SERVICE_ADDRESS

Value: 'translate.googleapis.com'

The default address of the service.

DEFAULT_SERVICE_PORT

Value: 443

The default port of the service.

CODEGEN_NAME

Value: 'gapic'

The name of the code generator, to be included in the agent header.