src/eric7/Plugins/UiExtensionPlugins/Translator/TranslatorEngines/GoogleV2Engine.py

branch
eric7
changeset 9209
b99e7fd55fd3
parent 9148
b31f0d894b55
child 9221
bf71ee032bb4
equal deleted inserted replaced
9208:3fc8dfeb6ebe 9209:b99e7fd55fd3
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2014 - 2022 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing the Google V2 translation engine.
8 """
9
10 import json
11
12 from PyQt6.QtCore import QByteArray, QTimer, QUrl
13
14 from .TranslationEngine import TranslationEngine
15
16 import Utilities
17
18
19 class GoogleV2Engine(TranslationEngine):
20 """
21 Class implementing the translation engine for the new Google
22 translation service.
23 """
24 TranslatorUrl = "https://translation.googleapis.com/language/translate/v2"
25
26 def __init__(self, plugin, parent=None):
27 """
28 Constructor
29
30 @param plugin reference to the plugin object
31 @type TranslatorPlugin
32 @param parent reference to the parent object
33 @type QObject
34 """
35 super().__init__(plugin, parent)
36
37 QTimer.singleShot(0, self.availableTranslationsLoaded.emit)
38
39 def engineName(self):
40 """
41 Public method to return the name of the engine.
42
43 @return engine name
44 @rtype str
45 """
46 return "googlev2"
47
48 def supportedLanguages(self):
49 """
50 Public method to get the supported languages.
51
52 @return list of supported language codes
53 @rtype list of str
54 """
55 return ["ar", "be", "bg", "bs", "ca", "cs", "da", "de", "el", "en",
56 "es", "et", "fi", "fr", "ga", "gl", "hi", "hr", "hu", "id",
57 "is", "it", "iw", "ja", "ka", "ko", "lt", "lv", "mk", "mt",
58 "nl", "no", "pl", "pt", "ro", "ru", "sk", "sl", "sq", "sr",
59 "sv", "th", "tl", "tr", "uk", "vi", "zh-CN", "zh-TW",
60 ]
61
62 def getTranslation(self, requestObject, text, originalLanguage,
63 translationLanguage):
64 """
65 Public method to translate the given text.
66
67 @param requestObject reference to the request object
68 @type TranslatorRequest
69 @param text text to be translated
70 @type str
71 @param originalLanguage language code of the original
72 @type str
73 @param translationLanguage language code of the translation
74 @type str
75 @return tuple of translated text and flag indicating success
76 @rtype tuple of (str, bool)
77 """
78 apiKey = self.plugin.getPreferences("GoogleV2Key")
79 if not apiKey:
80 return self.tr("Google V2: A valid Google Translate key is"
81 " required."), False
82
83 params = QByteArray(
84 "key={2}&source={0}&target={1}&format=text&q=".format(
85 originalLanguage, translationLanguage, apiKey).encode("utf-8"))
86 encodedText = (
87 QByteArray(Utilities.html_encode(text).encode("utf-8"))
88 .toPercentEncoding()
89 )
90 request = params + encodedText
91 response, ok = requestObject.post(QUrl(self.TranslatorUrl), request)
92 if ok:
93 response = str(response, "utf-8", "replace")
94 try:
95 responseDict = json.loads(response)
96 except ValueError:
97 return self.tr("Google V2: Invalid response received"), False
98
99 if (
100 "data" not in responseDict or
101 "translations" not in responseDict["data"]
102 ):
103 return self.tr("Google V2: No translation available."), False
104
105 result = ""
106 translations = responseDict["data"]["translations"]
107 for translation in translations:
108 result += translation["translatedText"]
109 if translation != translations[-1]:
110 result += "<br/>"
111 else:
112 result = response
113 return result, ok

eric ide

mercurial