This repository was archived by the owner on Jul 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
Add Yandex Translate API support #127
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
be7d120
Add Yandex Translate API support
wdv4758h 807469c
Fix some flake8 complain in yandex
wdv4758h 3343ef3
Remove unused comments
wdv4758h ebc5f84
Handle the NotFoundError correctly
wdv4758h 36f0389
Add test case for YandexDict
wdv4758h a058842
Show error message for status code of Yandex
wdv4758h c0daf1e
Add screenshot for Yandex Translate
wdv4758h 46963f9
Update README for Yandex
wdv4758h File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.' \ | ||
'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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like the concat by |
||
raise NotFoundError(word) | ||
|
||
record = Record( | ||
word=word, | ||
content=content, | ||
source=self.provider, | ||
) | ||
return record |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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
()
.