Skip to content

google-cloud-icu-i18n-translator ​

Google Cloud Translation as a translation provider of eugene-erg/icu-i18n-translator, through either edition:

  • Basic (v2) with an API key: the quickest start.
  • Advanced (v3) with a service account: glossaries, a choice of model (Google's language model general/translation-llm among them), a project and a region.

What both do:

  • Placeholders survive. The arguments of a message (and the tags of markup) travel as <span translate="no"> that Google leaves untranslated and moves where the target language needs them. The translator checks every text that comes back, so a text whose placeholders were lost fails alone and goes to the next provider.
  • Batches. The texts of a file go in as few requests as Google takes (128 texts, 25,000 characters each). Texts without words ({count} %, —) are not sent.
  • Languages from Google. Which directions it translates is asked from Google, not hard-coded, and the closest code is picked: zh_Hant/zh_TW → zh-TW, zh → zh-CN, pt_PT → pt-PT, de_AT → de.
  • Temporary errors asked again; keys and tokens never in URLs or exceptions.

Google takes no context, so the context of a message is not sent. If your messages need it, put DeepL (eugene-erg/deepl-icu-i18n-translator) or a language model before Google.

Installation ​

bash
composer require eugene-erg/google-cloud-icu-i18n-translator

It speaks HTTP through PSR-18: bring any client, for example symfony/http-client or guzzlehttp/guzzle, and PSR-17 factories such as nyholm/psr7.

Usage ​

php
use EugeneErg\GoogleCloudIcuI18nTranslator\Api\BasicApi;
use EugeneErg\GoogleCloudIcuI18nTranslator\GoogleCloudTranslator;
use EugeneErg\HttpProviderIcuI18nTranslator\Http\HttpJsonClient;
use Nyholm\Psr7\Factory\Psr17Factory;
use Symfony\Component\HttpClient\Psr18Client;

$factory = new Psr17Factory();
$http = new HttpJsonClient(new Psr18Client(), $factory, $factory);

$google = new GoogleCloudTranslator(
    api: new BasicApi($http, getenv('GOOGLE_TRANSLATE_API_KEY')),
    cache: $psr16Cache,   // optional: the language list, a day by default
);

// one of the providers of the translator, tried in order
$translator = new Translator(..., translators: [$google], formatters: [...]);

Advanced edition ​

php
use EugeneErg\GoogleCloudIcuI18nTranslator\Api\AdvancedApi;
use EugeneErg\GoogleCloudIcuI18nTranslator\Auth\ServiceAccountCredentials;

$google = new GoogleCloudTranslator(new AdvancedApi(
    http: $http,
    credentials: ServiceAccountCredentials::fromFile($http, '/secrets/translator.json', $psr16Cache),
    projectId: 'my-project',
    location: 'global',                   // or the region of your glossaries and models
    model: 'general/translation-llm',     // optional: 'general/nmt' by default, or a custom model
    glossary: 'my-terms',                 // optional: an id in the project and location, or a full name
));

The service account needs the role Cloud Translation API User. Its token is asked for with a JWT the key signs (no Google library needed) and kept until shortly before it expires, in the PSR-16 cache when one is given, so the processes of a web server share it.

Other credentials:

ServiceAccountCredentialsa JSON key: fromFile($http, $path) or new ServiceAccountCredentials($http, $decodedJson)
MetadataServerCredentialsthe service account of the machine on Cloud Run, GKE, Compute Engine: no key at all
StaticAccessTokena token got elsewhere (gcloud auth print-access-token); renewing it is yours
your ownimplement AccessTokenProviderInterface

A glossary is applied to every request, so take one of equivalent term sets that has all your languages: a language pair it lacks makes Google refuse, and the translator goes to the next provider.

Options ​

BasicApi(model:)'nmt' (Google's default) or 'base'
AdvancedApi(glossaryIgnoresCase:)false by default
baseUrl: of bothanother endpoint (a proxy, a test server)
GoogleCloudTranslator(cache:, cacheTtl:)the language list in a PSR-16 cache, 86400 s by default; without one it is asked once per object

HttpJsonClient and its RetryPolicy come from eugene-erg/http-provider-icu-i18n-translator, shared by the HTTP providers: by default three attempts on 408, 429, 5xx and throttling errors, waits of 1 s, 2 s … or the server's Retry-After, at most 30 s. RetryPolicy::none() turns it off.

In Laravel and Symfony ​

Laravel:

php
$this->app->singleton(TranslatorInterface::class . '[]', fn () => [
    app(GoogleCloudTranslator::class),   // bound as above
]);

Symfony:

yaml
services:
    EugeneErg\GoogleCloudIcuI18nTranslator\Api\BasicApi:
        arguments: { $apiKey: '%env(GOOGLE_TRANSLATE_API_KEY)%' }
    EugeneErg\GoogleCloudIcuI18nTranslator\GoogleCloudTranslator:
        arguments: { $api: '@EugeneErg\GoogleCloudIcuI18nTranslator\Api\BasicApi' }
        tags: [icu_i18n.provider]

Errors ​

Everything thrown about the service implements ProviderExceptionInterface (namespace EugeneErg\HttpProviderIcuI18nTranslator\Exceptions):

  • TransportException: no connection, or an HTTP error after the retries, with Google's message; its code is the status (403 for a key or an account without access, 429 for a quota).
  • InvalidResponseException: an answer this package does not understand.
  • CredentialsException: a service account key that cannot be read.

A direction Google does not translate throws the translator's UnexpectedTranslateDirectionException; canTranslate() tells it beforehand. The translator moves on to the next provider in every case.

Upgrading to 2.x ​

The HTTP client, the retries, the exceptions and the placeholders moved to eugene-erg/http-provider-icu-i18n-translator:

  • GoogleCloudIcuI18nTranslator\Http\HttpJsonClient and RetryPolicy are EugeneErg\HttpProviderIcuI18nTranslator\Http\…;
  • GoogleCloudIcuI18nTranslator\Exceptions\… are EugeneErg\HttpProviderIcuI18nTranslator\Exceptions\…, and GoogleCloudExceptionInterface is ProviderExceptionInterface; TransportException keeps the type of the error the service named in $errorType.

The behaviour is the same.

Testing ​

bash
composer install
composer check      # pint --test, phpstan (level max, strict and deprecation rules), phpunit

The tests answer from a fake PSR-18 client and sign with a key made on the fly; nothing is sent to Google.

License ​

MIT


From the README.md of EugeneErg/google-cloud-icu-i18n-translator · composer require eugene-erg/google-cloud-icu-i18n-translator