Repository navigation
Expand file tree
/
Copy pathTranslateClient.php
More file actions
421 lines (387 loc) · 15.5 KB
/
Copy pathTranslateClient.php
File metadata and controls
421 lines (387 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<?php
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Translate;
use Google\Auth\FetchAuthTokenInterface;
use Google\Cloud\Core\ClientTrait;
use Google\Cloud\Translate\Connection\ConnectionInterface;
use Google\Cloud\Translate\Connection\Rest;
use Psr\Cache\CacheItemPoolInterface;
/**
* Google Cloud Translation provides the ability to dynamically translate
* text between thousands of language pairs and lets websites and programs
* integrate with translation service programmatically. Find more
* information at the the
* [Google Cloud Translation docs](https://cloud.google.com/translation/docs/).
*
* The Google Cloud Translation API is available as a paid
* service. See the [Pricing](https://cloud.google.com/translation/v2/pricing)
* and [FAQ](https://cloud.google.com/translation/v2/faq) pages for details.
*
* Please note that while the Google Cloud Translation API supports
* authentication via service account and application default credentials
* like other Cloud Platform APIs, it also supports authentication via a
* public API access key. If you wish to authenticate using an API key,
* follow the
* [before you begin](https://cloud.google.com/translation/v2/translating-text-with-rest#before-you-begin)
* instructions to learn how to generate a key.
*
* Example:
* ```
* use Google\Cloud\Translate\TranslateClient;
*
* $translate = new TranslateClient();
* ```
*/
class TranslateClient
{
use ClientTrait;
const VERSION = '1.5.0';
const ENGLISH_LANGUAGE_CODE = 'en';
const FULL_CONTROL_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
/**
* @var ConnectionInterface
*/
protected $connection;
/**
* @var string
*/
private $targetLanguage;
/**
* @var string
*/
private $key;
/**
* Create a Translate client.
*
* Note that when creating a TranslateClient instance, setting
* `$config.projectId` is not supported. To switch between projects, you
* must provide credentials with access to the project.
*
* @param array $config [optional] {
* Configuration Options.
*
* @type string $apiEndpoint A hostname with optional port to use in
* place of the service's default endpoint.
* @type string $key A public API access key.
* @type string $target The target language to assign to the client.
* Must be a valid ISO 639-1 language code. **Defaults to** `"en"`
* (English).
* @type CacheItemPoolInterface $authCache A cache used storing access
* tokens. **Defaults to** a simple in memory implementation.
* @type array $authCacheOptions Cache configuration options.
* @type callable $authHttpHandler A handler used to deliver Psr7
* requests specifically for authentication.
* @type FetchAuthTokenInterface $credentialsFetcher A credentials
* fetcher instance.
* @type callable $httpHandler A handler used to deliver Psr7 requests.
* Only valid for requests sent over REST.
* @type array $keyFile The contents of the service account credentials
* .json file retrieved from the Google Developer's Console.
* Ex: `json_decode(file_get_contents($path), true)`.
* @type string $keyFilePath The full path to your service account
* credentials .json file retrieved from the Google Developers
* Console.
* @type float $requestTimeout Seconds to wait before timing out the
* request. **Defaults to** `0` with REST and `60` with gRPC.
* @type int $retries Number of retries for a failed request.
* **Defaults to** `3`.
* @type array $scopes Scopes to be used for the request.
* }
* @throws \InvalidArgumentException
*/
public function __construct(array $config = [])
{
$this->key = (isset($config['key']))
? $config['key']
: null;
$this->targetLanguage = isset($config['target'])
? $config['target']
: self::ENGLISH_LANGUAGE_CODE;
if (!isset($config['scopes'])) {
$config['scopes'] = [self::FULL_CONTROL_SCOPE];
}
if (!$this->key) {
$config = $this->configureAuthentication($config);
} else {
$config['shouldSignRequest'] = false;
}
unset($config['key']);
unset($config['target']);
$this->connection = new Rest($config);
}
/**
* Translate a string from one language to another.
*
* Example:
* ```
* $result = $translate->translate('Hello world!');
*
* echo $result['text'];
* ```
*
* @see https://cloud.google.com/translation/v2/translating-text-with-rest Translating Text
*
* @param string $string The string to translate.
* @param array $options [optional] {
* Configuration Options.
*
* @type string $source The source language to translate from. Must be a
* valid ISO 639-1 language code. If not provided the value will
* be automatically detected by the server.
* @type string $target The target language to translate to. Must be a
* valid ISO 639-1 language code. **Defaults to** the value assigned
* to the client (`"en"` by default).
* @type string $format Indicates whether the string to be translated is
* either plain-text or HTML. Acceptable values are `html` or
* `text`. **Defaults to** `"html"`.
* @type string $model The model to use for the translation request. May
* be `nmt` (for the NMT model) or `base` (for the PBMT model).
* **Defaults to** using the NMT model. If the NMT model is not
* supported for the requested language translation pair, the PBMT
* model will be defaulted instead. For a list of supported
* languages for the model types, please see the
* [Language Support](https://cloud.google.com/translate/docs/languages)
* documentation.
* }
* @return array|null A translation result including a `source` key containing
* the detected or provided language of the provided input, an
* `input` key containing the original string, and a `text` key
* containing the translated result.
*/
public function translate($string, array $options = [])
{
$res = $this->translateBatch([$string], $options);
if (count($res) > 0) {
return $res[0];
}
}
/**
* Translate multiple strings from one language to another.
*
* Example:
* ```
* $results = $translate->translateBatch([
* 'Hello world!',
* 'My name is David.'
* ]);
*
* foreach ($results as $result) {
* echo $result['text'];
* }
* ```
*
* @see https://cloud.google.com/translation/v2/translating-text-with-rest Translating Text
*
* @param array $strings An array of strings to translate.
* @param array $options [optional] {
* Configuration Options.
*
* @type string $source The source language to translate from. Must be a
* valid ISO 639-1 language code. If not provided the value will
* be automatically detected by the server.
* @type string $target The target language to translate to. Must be a
* valid ISO 639-1 language code. **Defaults to** the value assigned
* to the client (`"en"` by default).
* @type string $format Indicates whether the string to be translated is
* either plain-text or HTML. Acceptable values are `html` or
* `text`. **Defaults to** `"html"`.
* @type string $model The model to use for the translation request. May
* be `nmt` (for the NMT model) or `base` (for the PBMT model).
* **Defaults to** using the NMT model. If the NMT model is not
* supported for the requested language translation pair, the PBMT
* model will be defaulted instead. For a list of supported
* languages for the model types, please see the
* [Language Support](https://cloud.google.com/translate/docs/languages)
* documentation.
* }
* @return array A set of translation results. Each result includes a
* `source` key containing the detected or provided language of the
* provided input, an `input` key containing the original string,
* and a `text` key containing the translated result.
*/
public function translateBatch(array $strings, array $options = [])
{
$options += [
'model' => null,
];
$options = array_filter($options + [
'q' => $strings,
'key' => $this->key,
'target' => $this->targetLanguage,
'model' => $options['model']
], function ($opt) {
return !is_null($opt);
});
$response = $this->connection->listTranslations($options);
$translations = [];
$strings = array_values($strings);
if (isset($response['data']['translations'])) {
foreach ($response['data']['translations'] as $key => $translation) {
$source = isset($translation['detectedSourceLanguage'])
? $translation['detectedSourceLanguage']
: $options['source'];
$model = (isset($translation['model']))
? $translation['model']
: null;
$translations[] = [
'source' => $source,
'input' => $strings[$key],
'text' => $translation['translatedText'],
'model' => $model
];
}
}
return $translations;
}
/**
* Detect the language of a string.
*
* Example:
* ```
* $result = $translate->detectLanguage('Hello world!');
*
* echo $result['languageCode'];
* ```
*
* @see https://cloud.google.com/translation/v2/detecting-language-with-rest Detecting Langauge
*
* @param string $string The string to detect the language of.
* @param array $options [optional] Configuration Options.
* @return array A result including a `languageCode` key
* containing the detected ISO 639-1 language code, an `input` key
* containing the original string, and in most cases a `confidence`
* key containing a value between 0 - 1 signifying the confidence of
* the result.
*/
public function detectLanguage($string, array $options = [])
{
return $this->detectLanguageBatch([$string], $options)[0];
}
/**
* Detect the language of multiple strings.
*
* Example:
* ```
* $results = $translate->detectLanguageBatch([
* 'Hello World!',
* 'My name is David.'
* ]);
*
* foreach ($results as $result) {
* echo $result['languageCode'];
* }
* ```
*
* @see https://cloud.google.com/translation/v2/detecting-language-with-rest Detecting Langauge
*
* @param string $string The string to detect the language of.
* @param array $options [optional] Configuration Options.
* @return array A set of results. Each result includes a `languageCode` key
* containing the detected ISO 639-1 language code, an `input` key
* containing the original string, and in most cases a `confidence`
* key containing a value between 0 - 1 signifying the confidence of
* the result.
*/
public function detectLanguageBatch(array $strings, array $options = [])
{
$response = $this->connection->listDetections($options + [
'q' => $strings,
'key' => $this->key
]);
$detections = [];
foreach ($response['data']['detections'] as $key => $detection) {
$detection = $detection[0];
$detections[] = array_filter([
'languageCode' => $detection['language'],
'input' => $strings[$key],
'confidence' => isset($detection['confidence']) ? $detection['confidence'] : null
]);
}
return $detections;
}
/**
* Get all supported languages.
*
* Example:
* ```
* $languages = $translate->languages();
*
* foreach ($languages as $language) {
* echo $language;
* }
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/translation/v2/discovering-supported-languages-with-rest Discovering Supported Languages
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] Configuration Options.
* @return array A list of supported ISO 639-1 language codes.
*/
public function languages(array $options = [])
{
$response = $this->localizedLanguages($options + ['target' => null]);
return array_map(function ($language) {
return $language['code'];
}, $response);
}
/**
* Get the supported languages for translation in the targeted language.
*
* Unlike {@see Google\Cloud\Translate\TranslateClient::languages()} this
* will return the localized language names in addition to the ISO 639-1
* language codes.
*
* Example:
* ```
* $languages = $translate->localizedLanguages();
*
* foreach ($languages as $language) {
* echo $language['code'];
* }
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/translation/v2/discovering-supported-languages-with-rest Discovering Supported Languages
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] {
* Configuration Options.
*
* @type string $target The language to discover supported languages
* for. Must be a valid ISO 639-1 language code. **Defaults to** the
* value assigned to the client (`"en"` by default).
* }
* @return array A set of language results. Each result includes a `code`
* key containing the ISO 639-1 code for the supported language and
* a `name` key containing the name of the language written in the
* target language.
*/
public function localizedLanguages(array $options = [])
{
$response = $this->connection->listLanguages($options + [
'key' => $this->key,
'target' => $this->targetLanguage
]);
return array_map(function ($language) {
return array_filter([
'code' => $language['language'],
'name' => isset($language['name']) ? $language['name'] : null
]);
}, $response['data']['languages']);
}
}