forked from albertlauncher/python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google_translate.py
50 lines (40 loc) · 1.74 KB
/
google_translate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# -*- coding: utf-8 -*-
"""Translate text using Google Translate.
Check available languages here: https://cloud.google.com/translate/docs/languages
Synopsis: <trigger> <src_lang> <dest_lang> <text>"""
import json
import urllib.parse
import urllib.request
from albertv0 import *
__iid__ = "PythonInterface/v0.1"
__prettyname__ = "Google Translate"
__version__ = "1.0"
__trigger__ = "tr "
__author__ = "Manuel Schneider"
__dependencies__ = []
ua = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"
urltmpl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=%s&tl=%s&dt=t&q=%s"
iconPath = iconLookup('config-language')
if not iconPath:
iconPath = ":python_module"
def handleQuery(query):
if query.isTriggered:
fields = query.string.split()
item = Item(id=__prettyname__, icon=iconPath, completion=query.rawString)
if len(fields) >= 3:
src = fields[0]
dst = fields[1]
txt = " ".join(fields[2:])
url = urltmpl % (src, dst, urllib.parse.quote_plus(txt))
req = urllib.request.Request(url, headers={'User-Agent': ua})
with urllib.request.urlopen(req) as response:
data = json.loads(response.read().decode('utf-8'))
result = data[0][0][0]
item.text = result
item.subtext = "%s-%s translation of %s" % (src.upper(), dst.upper(), txt)
item.addAction(ClipAction("Copy translation to clipboard", result))
return item
else:
item.text = __prettyname__
item.subtext = "Enter a query in the form of \"<srclang> <dstlang> <text>\""
return item