-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.py
203 lines (162 loc) · 5.88 KB
/
translator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import aiohttp
from aiohttp_proxy import ProxyConnector
try:
import ujson as json
except ImportError:
import json
# If you reading this - hello from Rud!
# Github repo: https://github.com/Rud356/aioyatr
class Translator:
supported = {
'az', 'sq', 'am', 'en', 'ar', 'hy',
'af', 'eu', 'ba', 'be', 'bn', 'my',
'bg', 'bs', 'cy', 'hu', 'vi', 'ht',
'gl', 'nl', 'mrj', 'el', 'ka', 'gu',
'da', 'he', 'yi', 'id', 'ga', 'it',
'is', 'es', 'kk', 'kn', 'ca', 'ky',
'zh', 'ko', 'xh', 'km', 'lo', 'la',
'lv', 'lt', 'lb', 'mg', 'ms', 'ml',
'mt', 'mk', 'mi', 'mr', 'mhr', 'mn',
'de', 'ne', 'no', 'pa', 'pap', 'fa',
'pl', 'pt', 'ro', 'ru', 'ceb', 'sr',
'si', 'sk', 'sl', 'sw', 'su', 'tg',
'th', 'tl', 'ta', 'tt', 'te', 'tr',
'udm', 'uz', 'uk', 'ur', 'fi', 'fr',
'hi', 'hr', 'cs', 'sv', 'gd', 'et',
'eo', 'jv', 'ja'
}
valid_text_formats = {'plain', 'html'}
base_url = 'https://translate.yandex.net/api/v1.5/tr.json/'
def __init__(
self,
key: str, *,
proxy: str = '',
to_language: str = 'en',
text_format: str = 'plain',
hints: list = []
):
self.key = str(key)
if to_language not in Translator.supported:
raise ValueError("You setted wrong language")
self._language = to_language
if text_format not in Translator.valid_text_formats:
raise ValueError("You setted incorrect text format")
self.connector = None
self.proxy_url = proxy
if proxy:
self.connector = ProxyConnector.from_url(proxy)
for hint in hints:
if hint not in self.supported:
raise ValueError(f"Invalid language in hint list: `{hint}`")
self.hints = list(hints)
self.text_format = text_format
@property
def proxy(self) -> str:
return self.proxy_url
@proxy.setter
def proxy(self, url: str):
self.proxy_url = url
self.connector = ProxyConnector.from_url(url)
@property
def to_language(self) -> str:
return self._language
@to_language.setter
def to_language(self, value: str) -> None:
value = str(value)
if value not in Translator.supported:
raise ValueError("You setting wrong language")
self._language = value
def add_hint(self, lang: str) -> bool:
"""
Returns True if successfully added hint
"""
if lang in self.supported:
if lang not in self.hints:
self.hints.append(lang)
return True
return False
async def detect_lang(self, text: str) -> str:
url = Translator.base_url + 'detect?'
data = {
'key': self.key,
'text': text,
'hint': ','.join(self.hints)
}
async with aiohttp.ClientSession(
connector=self.connector,
json_serialize=json
) as session:
response = await session.get(
url, params=data
)
if response.status == 401:
raise self.exc.TranslatorKeyInvalid('Invalid API key')
if response.status == 402:
raise self.exc.TranslatorKeyBlocked('Blocked API key')
if response.status == 404:
raise self.exc.TranslatorError(
'Ran out of daily limit of translated text'
)
if response.status != 200:
raise self.exc.TranslatorError(
f"Failed detecting language ({response.reason})"
)
data = await response.json()
return data['lang']
async def translate(
self, text: str, from_language: str = None, to_language: str = None
) -> str:
if not from_language:
from_language = await self.detect_lang(text)
to_language = to_language or self.to_language
if to_language not in Translator.supported:
raise self.exc.TranslatorLanguage(
'Translating from language unsupported'
)
if from_language not in Translator.supported:
raise self.exc.TranslatorLanguage(
'Translating to language unsupported'
)
url = Translator.base_url + "translate?"
data = {
"key": self.key,
'text': text,
'lang': f'{from_language}-{to_language}',
'format': self.text_format
}
async with aiohttp.ClientSession(
connector=self.connector,
json_serialize=json
) as session:
response = await session.get(
url, params=data
)
if response.status == 401:
raise self.exc.TranslatorKeyInvalid('Invalid API key')
if response.status == 402:
raise self.exc.TranslatorKeyBlocked('Blocked API key')
if response.status == 404:
raise self.exc.TranslatorError(
'Ran out of daily limit of translated text'
)
if response.status == 413:
raise self.exc.TranslatorError('Too long text')
if response.status == 501:
raise self.exc.TranslatorError(
'This translation direction unsupproted'
)
if response.status != 200:
raise self.exc.TranslatorError(
f"Failed detecting language ({response.reason})"
)
data = await response.json()
return data['text'][0]
class exc:
class TranslatorError(Exception):
...
class TranslatorKeyInvalid(TranslatorError):
...
class TranslatorKeyBlocked(TranslatorError):
...
class TranslatorLanguage(TranslatorError):
...