-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathanytranslate.lua
81 lines (63 loc) · 2.86 KB
/
anytranslate.lua
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
-- Anytranslate
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "T", function()
-- Basic api URL's
local DETECT = "https://translate.yandex.net/api/v1.5/tr.json/detect?"
local DICT = "https://dictionary.yandex.net/api/v1/dicservice.json/lookup?"
-- Insert your keys here
local TRANS_KEY = "<YOUR KEY>"
local DICT_KEY = "<YOUR KEY>"
-- Define the language you want to use
local NATIVE_LANG = "de"
local INTO_LANG = "en"
local LANG_HINTS = "de,en"
local current = hs.application.frontmostApplication()
local chooser = hs.chooser.new(function(choosen)
current:activate()
hs.eventtap.keyStrokes(choosen.text)
end)
chooser:queryChangedCallback(function(string)
if (string.len(string) < 1) then return end
-- make sure e.g. ä ö ü work
local query = hs.http.encodeForQuery(string)
local trans_query = DETECT .. "key=" .. TRANS_KEY .. "&text=" .. query .. "&hint=" .. LANG_HINTS
-- detect language of input
hs.http.asyncGet(trans_query, nil, function(code, body)
if code ~= 200 then return end
local query_lang = hs.json.decode(body)["lang"]
local translate_lang = INTO_LANG
local dest_lang = NATIVE_LANG
if query_lang == NATIVE_LANG then
translate_lang = NATIVE_LANG
dest_lang = INTO_LANG
else
translate_lang = query_lang
dest_lang = NATIVE_LANG
end
local from_to = translate_lang .. "-" .. dest_lang
local query_string = DICT .. "key=" .. DICT_KEY .. "&lang=" .. from_to .. "&text=" .. query
-- get dictionary entries
hs.http.asyncGet(query_string, nil, function(status, data)
if not data then return end
local ok, results = pcall(function() return hs.json.decode(data) end)
if not ok then return end
if not results["def"] or not next(results["def"]) then return end
local result_arr = {}
table.insert(result_arr, results["def"][1]["tr"][1]["text"])
if results["def"][1]["tr"][1]["syn"] then
for i in pairs(results["def"][1]["tr"][1]["syn"]) do
table.insert(result_arr, results["def"][1]["tr"][1]["syn"][i]["text"])
end
end
-- insert the found words into the
choices = hs.fnutils.imap(result_arr, function(result)
return {
["text"] = result,
}
end)
chooser:choices(choices)
end)
end)
end)
chooser:searchSubText(false)
chooser:show()
end)