Update translate.py

Uses the new google v2 translate service which is more accurate. Also reduces code ugliness by quite a bit.
This commit is contained in:
dngfx 2020-07-12 00:30:10 +01:00 committed by GitHub
parent 85198974e0
commit eff99aff05
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,16 +1,19 @@
#--depends-on commands #--depends-on commands
#--require-config google-api-key
import json, re import json, re
from src import ModuleManager, utils from src import ModuleManager, utils
URL_TRANSLATE = "http://translate.googleapis.com/translate_a/single" URL_TRANSLATE = "https://translation.googleapis.com/language/translate/v2"
URL_LANGUAGES = "https://cloud.google.com/translate/docs/languages" URL_LANGUAGES = "https://cloud.google.com/translate/docs/languages"
REGEX_LANGUAGES = re.compile("(\w+)?:(\w+)? ") REGEX_LANGUAGES = re.compile("(\w+)?:(\w+)? ")
class Module(ModuleManager.BaseModule): class Module(ModuleManager.BaseModule):
@utils.hook("received.command.tr", alias_of="translate") @utils.hook("received.command.tr", alias_of="translate")
@utils.hook("received.command.translate") @utils.hook("received.command.translate")
@utils.spec("!<phrase>lstring") @utils.spec("?<from:to>lstring !<phrase>lstring")
def translate(self, event): def translate(self, event):
""" """
:help: Translate the provided phrase or the last line in thie current :help: Translate the provided phrase or the last line in thie current
@ -29,21 +32,19 @@ class Module(ModuleManager.BaseModule):
target_language = language_match.group(2) target_language = language_match.group(2)
phrase = phrase.split(" ", 1)[1] phrase = phrase.split(" ", 1)[1]
page = utils.http.request(URL_TRANSLATE, get_params={ page = utils.http.request(URL_TRANSLATE,
"client": "gtx", "dt": "t", "q": phrase, method="POST",
"sl": source_language, "tl": target_language}) post_data={
"q": phrase,
"format": "text",
"source": source_language,
"target": target_language,
"key": self.bot.config["google-api-key"]
}).json()
if page and not page.data.startswith(b"[null,null,"): if "data" in page:
data = page.decode("utf8") translation = page["data"]["translations"][0]["translatedText"]
while ",," in data: event["stdout"].write("(%s -> %s) %s" % (source_language, target_language, translation))
data = data.replace(",,", ",null,")
data = data.replace("[,", "[null,")
data_json = json.loads(data)
detected_source = data_json[2]
event["stdout"].write("(%s -> %s) %s" % (
detected_source, target_language.lower(),
data_json[0][0][0]))
else: else:
event["stderr"].write("Failed to translate, try checking " event["stderr"].write("Failed to translate, try checking "
"source/target languages (" + URL_LANGUAGES + ")") "source/target languages (" + URL_LANGUAGES + ")")