feat: add an extra_data field to Translation containing the whole gtranslate response (#59)

This commit is contained in:
Jakub Molinski 2018-05-06 14:14:06 +02:00 committed by SuHun Han
parent 57076b5ad8
commit 2c85a4a976
3 changed files with 32 additions and 4 deletions

View File

@ -81,6 +81,28 @@ class Translator(object):
data = utils.format_json(r.text)
return data
def _parse_extra_data(self, data):
response_parts_name_mapping = {
0: 'translation',
1: 'all-translations',
2: 'original-language',
5: 'possible-translations',
6: 'confidence',
7: 'possible-mistakes',
8: 'language',
11: 'synonyms',
12: 'definitions',
13: 'examples',
14: 'see-also',
}
extra = {}
for index, category in response_parts_name_mapping.items():
extra[category] = data[index] if (index < len(data) and data[index]) else None
return extra
def translate(self, text, dest='en', src='auto'):
"""Translate text from source language to destination language
@ -152,6 +174,8 @@ class Translator(object):
# this code will be updated when the format is changed.
translated = ''.join([d[0] if d[0] else '' for d in data[0]])
extra_data = self._parse_extra_data(data)
# actual source language that will be recognized by Google Translator when the
# src passed is equal to auto.
try:
@ -180,7 +204,7 @@ class Translator(object):
# put final values into a new Translated object
result = Translated(src=src, dest=dest, origin=origin,
text=translated, pronunciation=pron)
text=translated, pronunciation=pron, extra_data=extra_data)
return result

View File

@ -7,19 +7,22 @@ class Translated(object):
:param text: translated text
:param pronunciation: pronunciation
"""
def __init__(self, src, dest, origin, text, pronunciation):
def __init__(self, src, dest, origin, text, pronunciation, extra_data=None):
self.src = src
self.dest = dest
self.origin = origin
self.text = text
self.pronunciation = pronunciation
self.extra_data = extra_data
def __str__(self): # pragma: nocover
return self.__unicode__()
def __unicode__(self): # pragma: nocover
return u'Translated(src={src}, dest={dest}, text={text}, pronunciation={pronunciation})'.format(
src=self.src, dest=self.dest, text=self.text, pronunciation=self.pronunciation)
return u'Translated(src={src}, dest={dest}, text={text}, pronunciation={pronunciation}, ' \
u'extra_data={extra_data})'.format(
src=self.src, dest=self.dest, text=self.text, pronunciation=self.pronunciation,
extra_data='"' + repr(self.extra_data)[:10] + '..."')
class Detected(object):

View File

@ -60,6 +60,7 @@ def format_json(original):
converted = json.loads(original)
except ValueError:
converted = legacy_format_json(original)
return converted