Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1b1bfe4

Browse files
authored
Merge pull request #2731 from dhermes/update-translation
Update translation
2 parents f6f02f6 + 2da0020 commit 1b1bfe4

File tree

8 files changed

+106
-53
lines changed

8 files changed

+106
-53
lines changed

CONTRIBUTING.rst

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,8 +235,6 @@ Running System Tests
235235
`docs <https://cloud.google.com/storage/docs/authentication#generating-a-private-key>`__
236236
for more details. In order for Logging system tests to work, the Service Account
237237
will also have to be made a project Owner. This can be changed under "IAM & Admin".
238-
- ``GOOGLE_CLOUD_TESTS_API_KEY``: The API key for your project with
239-
the Google Translate API (and others) enabled.
240238

241239
- Examples of these can be found in ``system_tests/local_test_setup.sample``. We
242240
recommend copying this to ``system_tests/local_test_setup``, editing the
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
export GOOGLE_APPLICATION_CREDENTIALS="app_credentials.json.sample"
22
export GOOGLE_CLOUD_TESTING_REMOTE="upstream"
33
export GOOGLE_CLOUD_TESTING_BRANCH="master"
4-
export GOOGLE_CLOUD_TESTS_API_KEY="abcd1234"

system_tests/translate.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,11 @@
1313
# limitations under the License.
1414

1515

16-
import os
17-
1816
import unittest
1917

2018
from google.cloud import translate
2119

2220

23-
ENV_VAR = 'GOOGLE_CLOUD_TESTS_API_KEY'
24-
25-
2621
class Config(object):
2722
"""Run-time configuration to be modified at set-up.
2823
@@ -33,8 +28,7 @@ class Config(object):
3328

3429

3530
def setUpModule():
36-
api_key = os.getenv(ENV_VAR)
37-
Config.CLIENT = translate.Client(api_key=api_key)
31+
Config.CLIENT = translate.Client()
3832

3933

4034
class TestTranslate(unittest.TestCase):
@@ -61,8 +55,8 @@ def test_detect_language(self):
6155
def test_translate(self):
6256
values = ['hvala ti', 'dankon',
6357
'Me llamo Jeff', 'My name is Jeff']
64-
translations = Config.CLIENT.translate(values,
65-
target_language='de')
58+
translations = Config.CLIENT.translate(
59+
values, target_language='de', model=translate.NMT)
6660
self.assertEqual(len(values), len(translations))
6761

6862
self.assertEqual(

translate/google/cloud/translate/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,7 @@
1414

1515
"""Google Cloud Translate API wrapper."""
1616

17+
from google.cloud.translate.client import BASE
1718
from google.cloud.translate.client import Client
19+
from google.cloud.translate.client import NMT
1820
from google.cloud.translate.connection import Connection

translate/google/cloud/translate/client.py

Lines changed: 52 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,37 +19,57 @@
1919
import six
2020

2121
from google.cloud._helpers import _to_bytes
22+
from google.cloud.client import Client as BaseClient
2223
from google.cloud.translate.connection import Connection
2324

2425

2526
ENGLISH_ISO_639 = 'en'
2627
"""ISO 639-1 language code for English."""
2728

29+
BASE = 'base'
30+
"""Base translation model."""
2831

29-
class Client(object):
30-
"""Client to bundle configuration needed for API requests.
32+
NMT = 'nmt'
33+
"""Neural Machine Translation model."""
3134

32-
:type api_key: str
33-
:param api_key: The key used to send with requests as a query
34-
parameter.
3535

36-
:type http: :class:`httplib2.Http` or class that defines ``request()``.
37-
:param http: (Optional) HTTP object to make requests. If not
38-
passed, an :class:`httplib.Http` object is created.
36+
class Client(BaseClient):
37+
"""Client to bundle configuration needed for API requests.
3938
4039
:type target_language: str
4140
:param target_language: (Optional) The target language used for
4241
translations and language names. (Defaults to
4342
:data:`ENGLISH_ISO_639`.)
43+
44+
:type api_key: str
45+
:param api_key: (Optional) The key used to send with requests as a
46+
query parameter.
47+
48+
:type credentials: :class:`oauth2client.client.OAuth2Credentials`
49+
:param credentials: (Optional) The OAuth2 Credentials to use for the
50+
connection owned by this client. If not passed (and
51+
if no ``http`` object is passed), falls back to the
52+
default inferred from the environment.
53+
54+
:type http: :class:`httplib2.Http` or class that defines ``request()``.
55+
:param http: (Optional) HTTP object to make requests. If not
56+
passed, an :class:`httplib.Http` object is created.
4457
"""
4558

46-
def __init__(self, api_key, http=None, target_language=ENGLISH_ISO_639):
59+
_connection_class = Connection
60+
61+
def __init__(self, target_language=ENGLISH_ISO_639, api_key=None,
62+
credentials=None, http=None):
4763
self.api_key = api_key
48-
if http is None:
49-
http = httplib2.Http()
50-
self._connection = Connection(http=http)
5164
self.target_language = target_language
5265

66+
if api_key is not None:
67+
# If API key auth is desired, make it so that no credentials
68+
# will be auto-detected by the base class constructor.
69+
if http is None:
70+
http = httplib2.Http()
71+
super(Client, self).__init__(credentials=credentials, http=http)
72+
5373
def get_languages(self, target_language=None):
5474
"""Get list of supported languages for translation.
5575
@@ -70,7 +90,9 @@ def get_languages(self, target_language=None):
7090
dictionary will also contain the name of each supported
7191
language (localized to the target language).
7292
"""
73-
query_params = {'key': self.api_key}
93+
query_params = {}
94+
if self.api_key is not None:
95+
query_params['key'] = self.api_key
7496
if target_language is None:
7597
target_language = self.target_language
7698
if target_language is not None:
@@ -114,7 +136,9 @@ def detect_language(self, values):
114136
single_value = True
115137
values = [values]
116138

117-
query_params = [('key', self.api_key)]
139+
query_params = []
140+
if self.api_key is not None:
141+
query_params.append(('key', self.api_key))
118142
query_params.extend(('q', _to_bytes(value, 'utf-8'))
119143
for value in values)
120144
response = self._connection.api_request(
@@ -146,7 +170,8 @@ def detect_language(self, values):
146170
return detections
147171

148172
def translate(self, values, target_language=None, format_=None,
149-
source_language=None, customization_ids=()):
173+
source_language=None, customization_ids=(),
174+
model=None):
150175
"""Translate a string or list of strings.
151176
152177
See: https://cloud.google.com/translate/v2/\
@@ -173,7 +198,11 @@ def translate(self, values, target_language=None, format_=None,
173198
for translation. Sets the ``cid`` parameter
174199
in the query.
175200
176-
:rtype: str or list list
201+
:type model: str
202+
:param model: (Optional) The model used to translate the text. The
203+
only accepted values are :attr:`BASE` and :attr:`NMT`.
204+
205+
:rtype: str or list
177206
:returns: A list of dictionaries for each queried value. Each
178207
dictionary typically contains three keys (though not
179208
all will be present in all cases)
@@ -183,10 +212,11 @@ def translate(self, values, target_language=None, format_=None,
183212
* ``translatedText``: The translation of the text into the
184213
target language.
185214
* ``input``: The corresponding input value.
215+
* ``model``: The model used to translate the text.
186216
187217
If only a single value is passed, then only a single
188218
dictionary will be returned.
189-
:raises: :class:`ValueError <exceptions.ValueError>` if the number of
219+
:raises: :class:`~exceptions.ValueError` if the number of
190220
values and translations differ.
191221
"""
192222
single_value = False
@@ -199,14 +229,18 @@ def translate(self, values, target_language=None, format_=None,
199229
if isinstance(customization_ids, six.string_types):
200230
customization_ids = [customization_ids]
201231

202-
query_params = [('key', self.api_key), ('target', target_language)]
232+
query_params = [('target', target_language)]
233+
if self.api_key is not None:
234+
query_params.append(('key', self.api_key))
203235
query_params.extend(('q', _to_bytes(value, 'utf-8'))
204236
for value in values)
205237
query_params.extend(('cid', cid) for cid in customization_ids)
206238
if format_ is not None:
207239
query_params.append(('format', format_))
208240
if source_language is not None:
209241
query_params.append(('source', source_language))
242+
if model is not None:
243+
query_params.append(('model', model))
210244

211245
response = self._connection.api_request(
212246
method='GET', path='', query_params=query_params)

translate/google/cloud/translate/connection.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,14 @@
2020
class Connection(_http.JSONConnection):
2121
"""A connection to Google Cloud Translate via the JSON REST API."""
2222

23-
API_BASE_URL = 'https://www.googleapis.com'
23+
API_BASE_URL = 'https://translation.googleapis.com'
2424
"""The base of the API call URL."""
2525

2626
API_VERSION = 'v2'
2727
"""The version of the API, used in building the API call's URL."""
2828

2929
API_URL_TEMPLATE = '{api_base_url}/language/translate/{api_version}{path}'
3030
"""A template for the URL of a particular API call."""
31+
32+
SCOPE = ('https://www.googleapis.com/auth/cloud-platform',)
33+
"""The scopes required for authenticating."""

translate/tox.ini

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ envlist =
66
localdeps =
77
pip install --quiet --upgrade {toxinidir}/../core
88
deps =
9+
mock
910
pytest
1011
covercmd =
1112
py.test --quiet \

0 commit comments

Comments
 (0)