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-llmamong 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
composer require eugene-erg/google-cloud-icu-i18n-translatorIt 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
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
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:
ServiceAccountCredentials | a JSON key: fromFile($http, $path) or new ServiceAccountCredentials($http, $decodedJson) |
MetadataServerCredentials | the service account of the machine on Cloud Run, GKE, Compute Engine: no key at all |
StaticAccessToken | a token got elsewhere (gcloud auth print-access-token); renewing it is yours |
| your own | implement 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 both | another 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
$this->app->singleton(TranslatorInterface::class . '[]', fn () => [
app(GoogleCloudTranslator::class), // bound as above
]);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 (403for a key or an account without access,429for 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\HttpJsonClientandRetryPolicyareEugeneErg\HttpProviderIcuI18nTranslator\Http\…;GoogleCloudIcuI18nTranslator\Exceptions\…areEugeneErg\HttpProviderIcuI18nTranslator\Exceptions\…, andGoogleCloudExceptionInterfaceisProviderExceptionInterface;TransportExceptionkeeps the type of the error the service named in$errorType.
The behaviour is the same.
Testing
composer install
composer check # pint --test, phpstan (level max, strict and deprecation rules), phpunitThe 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