|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2014 - 2022 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing the Microsoft translation engine. |
|
8 """ |
|
9 |
|
10 import json |
|
11 |
|
12 from PyQt6.QtCore import QUrl, QByteArray, QTimer |
|
13 |
|
14 from .TranslationEngine import TranslationEngine |
|
15 |
|
16 |
|
17 class MicrosoftEngine(TranslationEngine): |
|
18 """ |
|
19 Class implementing the translation engine for the Microsoft |
|
20 translation service. |
|
21 """ |
|
22 TranslatorUrl = ( |
|
23 "https://api.cognitive.microsofttranslator.com/translate" |
|
24 "?api-version=3.0" |
|
25 ) |
|
26 |
|
27 def __init__(self, plugin, parent=None): |
|
28 """ |
|
29 Constructor |
|
30 |
|
31 @param plugin reference to the plugin object |
|
32 @type TranslatorPlugin |
|
33 @param parent reference to the parent object |
|
34 @type QObject |
|
35 """ |
|
36 super().__init__(plugin, parent) |
|
37 |
|
38 self.__mappings = { |
|
39 "zh-CN": "zh-CHS", |
|
40 "zh-TW": "zh-CHT", |
|
41 } |
|
42 |
|
43 QTimer.singleShot(0, self.availableTranslationsLoaded.emit) |
|
44 |
|
45 def engineName(self): |
|
46 """ |
|
47 Public method to return the name of the engine. |
|
48 |
|
49 @return engine name |
|
50 @rtype str |
|
51 """ |
|
52 return "microsoft" |
|
53 |
|
54 def supportedLanguages(self): |
|
55 """ |
|
56 Public method to get the supported languages. |
|
57 |
|
58 @return list of supported language codes |
|
59 @rtype list of str |
|
60 """ |
|
61 return ["ar", "bg", "ca", "cs", "da", "de", "en", |
|
62 "es", "et", "fi", "fr", "hi", "hu", "id", |
|
63 "it", "ja", "ko", "lt", "lv", "mt", |
|
64 "nl", "no", "pl", "pt", "ro", "ru", "sk", "sl", |
|
65 "sv", "th", "tr", "uk", "vi", "zh-CN", "zh-TW", |
|
66 ] |
|
67 |
|
68 def __mapLanguageCode(self, code): |
|
69 """ |
|
70 Private method to map a language code to the Microsoft code. |
|
71 |
|
72 @param code language code |
|
73 @type str |
|
74 @return mapped language code |
|
75 @rtype str |
|
76 """ |
|
77 if code in self.__mappings: |
|
78 return self.__mapping[code] |
|
79 else: |
|
80 return code |
|
81 |
|
82 def __getClientDataAzure(self): |
|
83 """ |
|
84 Private method to retrieve the client data. |
|
85 |
|
86 @return tuple giving the API subscription key, the API subscription |
|
87 region and a flag indicating validity |
|
88 @rtype tuple of (str, str, bool) |
|
89 """ |
|
90 subscriptionKey = self.plugin.getPreferences("MsTranslatorKey") |
|
91 subscriptionRegion = self.plugin.getPreferences("MsTranslatorRegion") |
|
92 valid = bool(subscriptionKey) and bool(subscriptionRegion) |
|
93 return subscriptionKey, subscriptionRegion, valid |
|
94 |
|
95 def getTranslation(self, requestObject, text, originalLanguage, |
|
96 translationLanguage): |
|
97 """ |
|
98 Public method to translate the given text. |
|
99 |
|
100 @param requestObject reference to the request object |
|
101 @type TranslatorRequest |
|
102 @param text text to be translated |
|
103 @type str |
|
104 @param originalLanguage language code of the original |
|
105 @type str |
|
106 @param translationLanguage language code of the translation |
|
107 @type str |
|
108 @return tuple of translated text and flag indicating success |
|
109 @rtype tuple of (str, bool) |
|
110 """ |
|
111 subscriptionKey, subscriptionRegion, valid = ( |
|
112 self.__getClientDataAzure() |
|
113 ) |
|
114 if not valid: |
|
115 return (self.tr("""You have not registered for the Microsoft""" |
|
116 """ Azure Translation service."""), |
|
117 False) |
|
118 |
|
119 params = "&from={0}&to={1}".format( |
|
120 self.__mapLanguageCode(originalLanguage), |
|
121 self.__mapLanguageCode(translationLanguage), |
|
122 ) |
|
123 url = QUrl(self.TranslatorUrl + params) |
|
124 |
|
125 requestList = [{"Text": text}] |
|
126 request = QByteArray(json.dumps(requestList).encode("utf-8")) |
|
127 |
|
128 headers = [ |
|
129 (b"Ocp-Apim-Subscription-Key", subscriptionKey.encode("utf8")), |
|
130 (b"Ocp-Apim-Subscription-Region", |
|
131 subscriptionRegion.encode("utf8")), |
|
132 (b"Content-Type", b"application/json; charset=UTF-8"), |
|
133 (b"Content-Length", str(len(request)).encode("utf-8")), |
|
134 ] |
|
135 response, ok = requestObject.post( |
|
136 url, request, dataType="json", extraHeaders=headers |
|
137 ) |
|
138 if ok: |
|
139 try: |
|
140 responseList = json.loads(response) |
|
141 responseDict = responseList[0] |
|
142 except ValueError: |
|
143 return (self.tr("MS Translator: Invalid response received"), |
|
144 False) |
|
145 |
|
146 if "translations" not in responseDict: |
|
147 return (self.tr("MS Translator: No translation available."), |
|
148 False) |
|
149 |
|
150 result = "" |
|
151 translations = responseDict["translations"] |
|
152 for translation in translations: |
|
153 result += translation["text"] |
|
154 if translation != translations[-1]: |
|
155 result += "<br/>" |
|
156 else: |
|
157 result = response |
|
158 return result, ok |