8000 Add Yandex Translate API support by wdv4758h · Pull Request #127 · zdict/zdict · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
This repository was archived by the owner on Jul 10, 2023. It is now read-only.

Add Yandex Translate API support #127

Merged
merged 8 commits into from
Aug 30, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ Usage
::

usage: zdict [-h] [-v] [-d] [-t QUERY_TIMEOUT] [-j [JOBS]] [-sp] [-su]
[-dt moe,moe-taiwanese,spanish,jisho,yahoo,urban,all] [-ld] [-V]
[-c] [--dump [PATTERN]] [-D]
[-dt moe,moe-taiwanese,yahoo,jisho,spanish,yandex,urban,all]
[-ld] [-V] [-c] [--dump [PATTERN]] [-D]
[word [word ...]]

positional arguments:
Expand All @@ -77,7 +77,7 @@ Usage
the number of CPUs in the system.
-sp, --show-provider Show the dictionary provider of the queried word
-su, --show-url Show the url of the queried word
-dt moe,moe-taiwanese,spanish,jisho,yahoo,urban,all, --dict moe,moe-taiwanese,spanish,jisho,yahoo,urban,all
-dt moe,moe-taiwanese,yahoo,jisho,spanish,yandex,urban,all, --dict moe,moe-taiwanese,yahoo,jisho,spanish,yandex,urban,all
Must be seperated by comma and no spaces after each
comma. Choose the dictionary you want. (default:
yahoo) Use 'all' for qureying all dictionaries. If
Expand Down Expand Up @@ -148,6 +148,12 @@ Screenshots
.. image:: http://i.imgur.com/UMP8k4e.png


`Yandex Translate <https://translate.yandex.com/>`_
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. image:: https://user-images.githubusercontent.com/2716047/29741879-ca1a3826-8a3a-11e7-9701-4a7e9a15971a.png


Development & Contributing
---------------------------

Expand Down
85 changes: 85 additions & 0 deletions zdict/dictionaries/yandex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import json

from zdict.dictionary import DictBase
from zdict.exceptions import NotFoundError, QueryError
from zdict.models import Record


# The daily request limit is 1,000,000 characters
# The monthly limit is 10,000,000 characters
API_KEY = 'trnsl.1.1.20170826T075621Z.' \
Copy link
Member
@iblislin iblislin Aug 26, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:/ I'm not a fan of escaping newline.
But I'm ok, if you do not like string concatenation within ().

'6dfcaff242c6caa8.e2b9cf136d451d9d6eb69516ec97b827e8c8229b'


class YandexDict(DictBase):
"""
Docs:

* https://tech.yandex.com/translate/
* https://tech.yandex.com/dictionary/

"""

# Change the url below to the API url of the new dictionary.
# Need to keep the `{word}` for `_get_url()` usage.
# TODO: support different translate direction
# TODO: use Dictionary API
API = 'https://translate.yandex.net/api/v1.5/tr.json/translate?' \
'key={api_key}&text={word}&lang=ru-en'

status_code = {
200: 'Operation completed successfully',
401: 'Invalid API key',
402: 'Blocked API key',
404: 'Exceeded the daily limit on the amount of translated text',
413: 'Exceeded the maximum text size',
422: 'The text cannot be translated',
501: 'The specified translation direction is not supported',
}

@property
def provider(self):
return 'yandex'

@property
def title(self):
return 'Yandex Translate'

def _get_url(self, word) -> str:
return self.API.format(api_key=API_KEY, word=word)

def show(self, record: Record):
content = json.loads(record.content)

self.color.print(record.word, 'yellow')
print()

for index, data in enumerate(content['text']):
self.color.print('{}. {}'.format(index + 1, data), 'org')

print()

def query(self, word: str):
try:
content = self._get_raw(word)
except QueryError as exception:
raise NotFoundError(exception.word)

content_json = json.loads(content)

status = content_json.get('code')
if status != 200:
# https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/#codes
message = self.status_code.get(
status,
'Some bad thing happened with Yandex'
)
print('Yandex: ' + message)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

print('Yandex:', message)?
print will append a space for you.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the concat by +, but if you like that one I can change it.

raise NotFoundError(word)

record = Record(
word=word,
content=content,
source=self.provider,
)
return record
51 changes: 51 additions & 0 deletions zdict/tests/dictionaries/test_yandex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from pytest import raises
from unittest.mock import Mock, patch

from zdict.dictionaries.yandex import YandexDict, API_KEY
from zdict.exceptions import NotFoundError, QueryError
from zdict.models import Record
from zdict.zdict import get_args


class TestYandexDict:
def setup_method(self, method):
self.dict = YandexDict(get_args())

def teardown_method(self, method):
del self.dict

def test__get_url(self):
url = 'https://translate.yandex.net/api/v1.5/tr.json/translate?' \
'key={}&text=дом&lang=ru-en'
assert url.format(API_KEY) == self.dict._get_url('дом')

def test_provider(self):
assert self.dict.provider == 'yandex'

def test_query_timeout(self):
self.dict._get_raw = Mock(side_effect=QueryError('дом', 404))

with raises(NotFoundError):
self.dict.query('дом')

self.dict._get_raw.assert_called_with('дом')

@patch('zdict.dictionaries.yandex.Record')
def test_query_normal(self, Record):
content = '{"code":200,"lang":"ru-en","text":["house"]}'
self.dict._get_raw = Mock(return_value=content)
self.dict.query('дом')
Record.assert_called_with(word='дом', content=content, source='yandex')

def test_show(self):
content = '''
{
"code": 200,
"lang": "ru-en",
"text": ["house"]
}
'''
r = Record(word='дом', content=content, source=self.dict.provider)

# god bless this method, hope that it do not raise any exception
self.dict.show(r)
0