mirror of
https://github.com/Hopiu/django-rosetta.git
synced 2026-04-10 16:50:59 +00:00
Fix Google translation api
This commit is contained in:
parent
fd340eb054
commit
e234befcbc
2 changed files with 44 additions and 29 deletions
|
|
@ -7,7 +7,7 @@ Rosetta can be configured via the following parameters, to be defined in your pr
|
|||
* ``ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS``: Enable AJAX translation suggestions. Defaults to ``False``.
|
||||
* ``YANDEX_TRANSLATE_KEY``: Translation suggestions from Yandex `Yandex.Translate API <http://api.yandex.com/translate/>`_. To use this service you must first `obtain an AppID key <http://api.yandex.com/key/form.xml?service=trnsl>`_, then specify the key here. Defaults to ``None``.
|
||||
* ``AZURE_CLIENT_SECRET``: Translation suggestions using the Microsoft Azure Translator API. To use this service, you must first `register for the service <https://docs.microsoft.com/en-us/azure/cognitive-services/Translator/translator-text-how-to-signup>`_, and set ``AZURE_CLIENT_SECRET`` to either of the keys listed for your subscription. Defaults to ``None``.
|
||||
* ``GOOGLE_APPLICATION_CREDENTIALS_PATH`` and ``GOOGLE_PROJECT_ID``: Translation suggestions using Google Translation API. To use this service, you must first `register the project <https://cloud.google.com/translate/docs/quickstart-client-libraries-v3>`_. You do not have to register ENV variable. GOOGLE_APPLICATION_CREDENTIALS_PATH is path to JSON credentials file. Defaults to ``None``. You also have to install google-cloud-translate package `pip install --upgrade google-cloud-translate`
|
||||
* ``GOOGLE_APPLICATION_CREDENTIALS_PATH`` and ``GOOGLE_PROJECT_ID``: Translation suggestions using Google Translation API. To use this service, you must first `register the project <https://cloud.google.com/translate/docs/quickstart-client-libraries-v3>`_. You do not have to register ENV variable. GOOGLE_APPLICATION_CREDENTIALS_PATH is path to JSON credentials file. Defaults to ``None``. You also have to install google-cloud-translate package `pip install google-cloud-translate==3.0.2`
|
||||
* ``ROSETTA_MESSAGES_SOURCE_LANGUAGE_CODE`` and ``ROSETTA_MESSAGES_SOURCE_LANGUAGE_NAME``: Change these if the source language in your PO files isn't English. Default to ``'en'`` and ``'English'`` respectively.
|
||||
* ``ROSETTA_WSGI_AUTO_RELOAD`` and ``ROSETTA_UWSGI_AUTO_RELOAD``: When running WSGI daemon mode, using ``mod_wsgi`` 2.0c5 or later, this setting controls whether the contents of the gettext catalog files should be automatically reloaded by the WSGI processes each time they are modified. For performance reasons, this setting should be disabled in production environments. Default to ``False``.
|
||||
* ``ROSETTA_EXCLUDED_APPLICATIONS``: Exclude applications defined in this list from being translated. Defaults to ``()``.
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import json
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
import requests
|
||||
import json
|
||||
|
||||
|
||||
class TranslationException(Exception):
|
||||
|
|
@ -12,19 +12,25 @@ class TranslationException(Exception):
|
|||
|
||||
def translate(text, from_language, to_language):
|
||||
AZURE_CLIENT_SECRET = getattr(settings, 'AZURE_CLIENT_SECRET', None)
|
||||
GOOGLE_APPLICATION_CREDENTIALS_PATH = getattr(settings, 'GOOGLE_APPLICATION_CREDENTIALS_PATH', None)
|
||||
GOOGLE_APPLICATION_CREDENTIALS_PATH = getattr(
|
||||
settings, 'GOOGLE_APPLICATION_CREDENTIALS_PATH', None
|
||||
)
|
||||
GOOGLE_PROJECT_ID = getattr(settings, 'GOOGLE_PROJECT_ID', None)
|
||||
|
||||
if AZURE_CLIENT_SECRET:
|
||||
return translate_by_azure(text, from_language, to_language, AZURE_CLIENT_SECRET)
|
||||
elif GOOGLE_APPLICATION_CREDENTIALS_PATH and GOOGLE_PROJECT_ID:
|
||||
return translate_by_google(text, from_language, to_language, GOOGLE_APPLICATION_CREDENTIALS_PATH, GOOGLE_PROJECT_ID)
|
||||
return translate_by_google(
|
||||
text,
|
||||
from_language,
|
||||
to_language,
|
||||
GOOGLE_APPLICATION_CREDENTIALS_PATH,
|
||||
GOOGLE_PROJECT_ID,
|
||||
)
|
||||
else:
|
||||
raise TranslationException('No translation API service is configured.')
|
||||
|
||||
|
||||
|
||||
|
||||
def translate_by_azure(text, from_language, to_language, subscription_key):
|
||||
"""
|
||||
This method does the heavy lifting of connecting to the translator API and fetching a response
|
||||
|
|
@ -43,20 +49,20 @@ def translate_by_azure(text, from_language, to_language, subscription_key):
|
|||
headers = {
|
||||
'Ocp-Apim-Subscription-Key': subscription_key,
|
||||
'Content-type': 'application/json',
|
||||
'X-ClientTraceId': str(uuid.uuid4())
|
||||
'X-ClientTraceId': str(uuid.uuid4()),
|
||||
}
|
||||
|
||||
url_parameters = {
|
||||
"from": from_language,
|
||||
"to": to_language
|
||||
}
|
||||
url_parameters = {"from": from_language, "to": to_language}
|
||||
|
||||
request_data = [
|
||||
{"text": text}
|
||||
]
|
||||
request_data = [{"text": text}]
|
||||
|
||||
api_hostname = AZURE_TRANSLATOR_HOST + AZURE_TRANSLATOR_PATH
|
||||
r = requests.post(api_hostname, headers=headers, params=url_parameters, data=json.dumps(request_data))
|
||||
r = requests.post(
|
||||
api_hostname,
|
||||
headers=headers,
|
||||
params=url_parameters,
|
||||
data=json.dumps(request_data),
|
||||
)
|
||||
api_response = json.loads(r.text)
|
||||
|
||||
try:
|
||||
|
|
@ -71,7 +77,11 @@ def translate_by_azure(text, from_language, to_language, subscription_key):
|
|||
error_code = api_error.get("code")
|
||||
error_message = api_error.get("message")
|
||||
|
||||
raise TranslationException("Microsoft Translation API error: Error code {}, {}".format(error_code, error_message))
|
||||
raise TranslationException(
|
||||
"Microsoft Translation API error: Error code {}, {}".format(
|
||||
error_code, error_message
|
||||
)
|
||||
)
|
||||
else:
|
||||
# response body will be of the form:
|
||||
# [
|
||||
|
|
@ -89,26 +99,31 @@ def translate_by_azure(text, from_language, to_language, subscription_key):
|
|||
|
||||
return translated_text
|
||||
except requests.exceptions.RequestException as err:
|
||||
raise TranslationException("Error connecting to Microsoft Translation Service: {0}".format(err))
|
||||
raise TranslationException(
|
||||
"Error connecting to Microsoft Translation Service: {0}".format(err)
|
||||
)
|
||||
|
||||
|
||||
def translate_by_google(text, input_language, output_language, creadentials_path, project_id):
|
||||
from google.cloud import translate_v3beta1 as google_translate
|
||||
|
||||
# using new v3beta Translation API
|
||||
client = google_translate.TranslationServiceClient.from_service_account_json(creadentials_path)
|
||||
parent = client.location_path(project_id, 'global')
|
||||
def translate_by_google(
|
||||
text, input_language, output_language, creadentials_path, project_id
|
||||
):
|
||||
from google.cloud import translate as google_translate
|
||||
|
||||
client = google_translate.TranslationServiceClient.from_service_account_json(
|
||||
creadentials_path
|
||||
)
|
||||
parent = "projects/{}/locations/{}".format(project_id, 'global')
|
||||
try:
|
||||
api_response = client.translate_text(
|
||||
parent=parent,
|
||||
contents=[text],
|
||||
mime_type='text/plain',
|
||||
source_language_code=input_language,
|
||||
target_language_code=output_language
|
||||
request=dict(
|
||||
parent=parent,
|
||||
contents=[text],
|
||||
mime_type='text/plain',
|
||||
source_language_code=input_language,
|
||||
target_language_code=output_language.split('.', 1)[0],
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
raise TranslationException('Google API error: {}'.format(e))
|
||||
else:
|
||||
return str(api_response.translations[0].translated_text)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue