Plugins/UiExtensionPlugins/Translator/TranslatorEngines/YandexEngine.py

changeset 6018
1c858879d3d0
child 6048
82ad8ec9548c
equal deleted inserted replaced
6017:dab01678626d 6018:1c858879d3d0
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2014 - 2017 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing the Yandex translation engine.
8 """
9
10 from __future__ import unicode_literals
11 try:
12 str = unicode
13 except NameError:
14 pass
15
16 import json
17
18 from PyQt5.QtCore import QUrl, QByteArray
19
20 import Utilities
21
22 from .TranslationEngine import TranslationEngine
23
24
25 class YandexEngine(TranslationEngine):
26 """
27 Class implementing the translation engine for the Yandex
28 translation service.
29 """
30 TranslatorUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate"
31 TranslatorLimit = 10000
32
33 def __init__(self, plugin, parent=None):
34 """
35 Constructor
36
37 @param plugin reference to the plugin object (TranslatorPlugin)
38 @param parent reference to the parent object (QObject)
39 """
40 super(YandexEngine, self).__init__(plugin, parent)
41
42 self.__errors = {
43 401: self.tr("Invalid API key."),
44 402: self.tr("API key has been blocked."),
45 403: self.tr("Daily limit for requests has been reached."),
46 404: self.tr("Daily limit for the volume of translated text"
47 " reached."),
48 413: self.tr("Text size exceeds the maximum."),
49 422: self.tr("Text could not be translated."),
50 501: self.tr("The specified translation direction is not"
51 " supported."),
52 }
53
54 def engineName(self):
55 """
56 Public method to return the name of the engine.
57
58 @return engine name (string)
59 """
60 return "yandex"
61
62 def supportedLanguages(self):
63 """
64 Public method to get the supported languages.
65
66 @return list of supported language codes (list of string)
67 """
68 return ["ar", "be", "bg", "bs", "ca", "cs", "da", "de", "el", "en",
69 "es", "et", "fi", "fr", "ga", "gl", "hi", "hr", "hu", "id",
70 "is", "it", "iw", "ja", "ka", "ko", "lt", "lv", "mk", "mt",
71 "nl", "no", "pl", "pt", "ro", "ru", "sk", "sl", "sq", "sr",
72 "sv", "th", "tl", "tr", "uk", "vi", "zh-CN", "zh-TW",
73 ]
74
75 def getTranslation(self, requestObject, text, originalLanguage,
76 translationLanguage):
77 """
78 Public method to translate the given text.
79
80 @param requestObject reference to the request object
81 (TranslatorRequest)
82 @param text text to be translated (string)
83 @param originalLanguage language code of the original (string)
84 @param translationLanguage language code of the translation (string)
85 @return tuple of translated text (string) and flag indicating
86 success (boolean)
87 """
88 if len(text) > self.TranslatorLimit:
89 return (self.tr("Only texts up to {0} characters are allowed.")
90 .format(self.TranslatorLimit), False)
91
92 apiKey = self.plugin.getPreferences("YandexKey")
93 if not apiKey:
94 return self.tr("A valid Yandex key is required."), False
95
96 params = QByteArray(
97 "key={0}&lang={1}-{2}&text=".format(
98 apiKey, originalLanguage, translationLanguage).encode("utf-8"))
99 encodedText = QByteArray(Utilities.html_encode(text).encode("utf-8"))\
100 .toPercentEncoding()
101 request = params + encodedText
102 response, ok = requestObject.post(QUrl(self.TranslatorUrl), request)
103 if ok:
104 try:
105 responseDict = json.loads(response)
106 except ValueError:
107 return self.tr("Invalid response received"), False
108
109 if responseDict["code"] != 200:
110 try:
111 error = self.__errors[responseDict["code"]]
112 except KeyError:
113 error = self.tr("Unknown error code ({0}) received.")\
114 .format(responseDict["code"])
115 return error, False
116
117 sentences = responseDict["text"]
118 result = ""
119 for sentence in sentences:
120 result += sentence.replace("\n", "<br/>")
121 else:
122 result = response
123 return result, ok

eric ide

mercurial