|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2014 - 2022 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing the Google V1 translation engine. |
|
8 """ |
|
9 |
|
10 import json |
|
11 import re |
|
12 |
|
13 from PyQt6.QtCore import QByteArray, QUrl, QTimer |
|
14 |
|
15 import Utilities |
|
16 |
|
17 from .TranslationEngine import TranslationEngine |
|
18 |
|
19 |
|
20 class GoogleV1Engine(TranslationEngine): |
|
21 """ |
|
22 Class implementing the translation engine for the old Google |
|
23 translation service. |
|
24 """ |
|
25 TranslatorUrl = "https://translate.googleapis.com/translate_a/single" |
|
26 TextToSpeechUrl = "https://translate.google.com/translate_tts" |
|
27 TextToSpeechLimit = 100 |
|
28 |
|
29 def __init__(self, plugin, parent=None): |
|
30 """ |
|
31 Constructor |
|
32 |
|
33 @param plugin reference to the plugin object |
|
34 @type TranslatorPlugin |
|
35 @param parent reference to the parent object |
|
36 @type QObject |
|
37 """ |
|
38 super().__init__(plugin, parent) |
|
39 |
|
40 QTimer.singleShot(0, self.availableTranslationsLoaded.emit) |
|
41 |
|
42 def engineName(self): |
|
43 """ |
|
44 Public method to return the name of the engine. |
|
45 |
|
46 @return engine name |
|
47 @rtype str |
|
48 """ |
|
49 return "googlev1" |
|
50 |
|
51 def supportedLanguages(self): |
|
52 """ |
|
53 Public method to get the supported languages. |
|
54 |
|
55 @return list of supported language codes |
|
56 @rtype list of str |
|
57 """ |
|
58 return ["ar", "be", "bg", "bs", "ca", "cs", "da", "de", "el", "en", |
|
59 "es", "et", "fi", "fr", "ga", "gl", "hi", "hr", "hu", "id", |
|
60 "is", "it", "iw", "ja", "ka", "ko", "lt", "lv", "mk", "mt", |
|
61 "nl", "no", "pl", "pt", "ro", "ru", "sk", "sl", "sq", "sr", |
|
62 "sv", "th", "tl", "tr", "uk", "vi", "zh-CN", "zh-TW", |
|
63 ] |
|
64 |
|
65 def hasTTS(self): |
|
66 """ |
|
67 Public method indicating the Text-to-Speech capability. |
|
68 |
|
69 @return flag indicating the Text-to-Speech capability |
|
70 @rtype bool |
|
71 """ |
|
72 return True |
|
73 |
|
74 def getTranslation(self, requestObject, text, originalLanguage, |
|
75 translationLanguage): |
|
76 """ |
|
77 Public method to translate the given text. |
|
78 |
|
79 @param requestObject reference to the request object |
|
80 @type TranslatorRequest |
|
81 @param text text to be translated |
|
82 @type str |
|
83 @param originalLanguage language code of the original |
|
84 @type str |
|
85 @param translationLanguage language code of the translation |
|
86 @type str |
|
87 @return tuple of translated text and flag indicating success |
|
88 @rtype tuple of (str, bool) |
|
89 """ |
|
90 params = QByteArray( |
|
91 "client=gtx&sl={0}&tl={1}&dt=t&dt=bd&ie=utf-8&oe=utf-8&q=".format( |
|
92 originalLanguage, translationLanguage).encode("utf-8")) |
|
93 encodedText = ( |
|
94 QByteArray(Utilities.html_encode(text).encode("utf-8")) |
|
95 .toPercentEncoding() |
|
96 ) |
|
97 request = params + encodedText |
|
98 response, ok = requestObject.post(QUrl(self.TranslatorUrl), request) |
|
99 if ok: |
|
100 try: |
|
101 # clean up the response |
|
102 response = re.sub(r',{2,}', ',', response) |
|
103 responseDict = json.loads(response) |
|
104 except ValueError: |
|
105 return self.tr("Google V1: Invalid response received"), False |
|
106 |
|
107 if isinstance(responseDict, dict): |
|
108 sentences = responseDict["sentences"] |
|
109 result = "" |
|
110 for sentence in sentences: |
|
111 result += sentence["trans"].replace("\n", "<br/>") |
|
112 |
|
113 if ( |
|
114 self.plugin.getPreferences("GoogleEnableDictionary") and |
|
115 "dict" in responseDict |
|
116 ): |
|
117 dictionary = responseDict["dict"] |
|
118 for value in dictionary: |
|
119 result += "<hr/><u><b>{0}</b> - {1}</u><br/>".format( |
|
120 text, value["pos"]) |
|
121 for entry in value["entry"]: |
|
122 previous = (entry["previous_word"] + " " |
|
123 if "previous_word" in entry else "") |
|
124 word = entry["word"] |
|
125 reverse = entry["reverse_translation"] |
|
126 result += "<br/>{0}<b>{1}</b> - {2}".format( |
|
127 previous, word, ", ".join(reverse)) |
|
128 if value != dictionary[-1]: |
|
129 result += "<br/>" |
|
130 elif isinstance(responseDict, list): |
|
131 sentences = responseDict[0] |
|
132 result = ( |
|
133 "".join([s[0] for s in sentences]).replace("\n", "<br/>") |
|
134 ) |
|
135 if ( |
|
136 self.plugin.getPreferences("GoogleEnableDictionary") and |
|
137 len(responseDict) > 2 |
|
138 ): |
|
139 if not responseDict[1]: |
|
140 result = self.tr("Google V1: No translation found.") |
|
141 ok = False |
|
142 else: |
|
143 for wordTypeList in responseDict[1]: |
|
144 result += "<hr/><u><b>{0}</b> - {1}</u>".format( |
|
145 wordTypeList[0], wordTypeList[-2]) |
|
146 for wordsList in wordTypeList[2]: |
|
147 reverse = wordsList[0] |
|
148 words = wordsList[1] |
|
149 result += "<br/><b>{0}</b> - {1}".format( |
|
150 reverse, ", ".join(words)) |
|
151 else: |
|
152 result = responseDict |
|
153 else: |
|
154 result = response |
|
155 return result, ok |
|
156 |
|
157 def getTextToSpeechData(self, requestObject, text, language): |
|
158 """ |
|
159 Public method to pronounce the given text. |
|
160 |
|
161 @param requestObject reference to the request object |
|
162 @type TranslatorRequest |
|
163 @param text text to be pronounced |
|
164 @type str |
|
165 @param language language code of the text |
|
166 @type str |
|
167 @return tuple with pronounce data or error string and success flag |
|
168 @rtype tuple of (QByteArray or str, bool) |
|
169 """ |
|
170 text = text.split("\n\n", 1)[0] |
|
171 if len(text) > self.TextToSpeechLimit: |
|
172 return (self.tr("Google V1: Only texts up to {0} characters are" |
|
173 " allowed.") |
|
174 .format(self.TextToSpeechLimit), False) |
|
175 |
|
176 url = QUrl(self.TextToSpeechUrl + |
|
177 "?client=tw-ob&ie=utf-8&tl={0}&q={1}".format( |
|
178 language, text)) |
|
179 return requestObject.get(url) |