forked from meshchaninov/alfred-translate-workflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
237 lines (218 loc) · 5.3 KB
/
main.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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#!/usr/bin/python
import json
from typing import List
import urllib.parse
import random
import http.client
import sys
import os
class Translate:
"""
Translate API
Thanks to Telegram MacOS client for the idea
https://github.com/TelegramOrg/Telegram-macos-Swift/blob/67e4cf8de2f060ec8152ce68562c9489a6073534/packages/Translate/Sources/Translate/Translate.swift
"""
languages = {
"af",
"sq",
"am",
"ar",
"hy",
"as",
"ay",
"az",
"bm",
"eu",
"be",
"bn",
"bho",
"bs",
"bg",
"ca",
"ceb",
"zh-CN",
"zh-TW",
"co",
"hr",
"cs",
"da",
"dv",
"doi",
"nl",
"en",
"eo",
"et",
"ee",
"fil",
"fi",
"fr",
"fy",
"gl",
"ka",
"de",
"el",
"gn",
"gu",
"ht",
"ha",
"haw",
"he",
"hi",
"hmn",
"hu",
"is",
"ig",
"ilo",
"id",
"ga",
"it",
"ja",
"jv",
"kn",
"kk",
"km",
"rw",
"gom",
"ko",
"kri",
"ku",
"ckb",
"ky",
"lo",
"la",
"lv",
"ln",
"lt",
"lg",
"lb",
"mk",
"mai",
"mg",
"ms",
"ml",
"mt",
"mi",
"mr",
"mni-Mtei",
"lus",
"mn",
"my",
"ne",
"no",
"ny",
"or",
"om",
"ps",
"fa",
"pl",
"pt",
"pa",
"qu",
"ro",
"ru",
"sm",
"sa",
"gd",
"nso",
"sr",
"st",
"sn",
"sd",
"si",
"sk",
"sl",
"so",
"es",
"su",
"sw",
"sv",
"tl",
"tg",
"ta",
"tt",
"te",
"th",
"ti",
"ts",
"tr",
"tk",
"ak",
"uk",
"ur",
"ug",
"uz",
"vi",
"cy",
"xh",
"yi",
"yo",
"zu",
}
user_agent = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36"
]
def __init__(self, lang: str = "en"):
if lang not in self.languages:
raise ValueError(f"Language {lang} is not supported")
self.lang = lang
@classmethod
def _get_user_agent(cls):
return random.choice(cls.user_agent)
def _generate_url(self, text):
text_encoded = urllib.parse.quote(text)
return "translate.goo" + \
"gleapis.c" + \
"om", "/tr" + \
"anslate_a" + \
"/singl" + \
f"e?client=gtx&sl=auto&tl={self.lang}&dt=t&ie=UTF-8&oe=UTF-8&otf=1&ssel=0&tsel=0&kc=7&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&q={text_encoded}"
def _get_request(self, text):
url, path = self._generate_url(text)
conn = http.client.HTTPSConnection(url)
headers = {
"User-Agent": self._get_user_agent(),
}
conn.request("GET", path, headers=headers)
res = conn.getresponse()
if res.status != 200:
raise RuntimeError(f"HTTP Error: {res.status}")
return json.loads(res.read())
def _parse_response(self, data: List) -> List[str]:
if data[1] is None:
return data[2], [data[0][0][0]]
return data[2], data[1][0][1]
def get_translation(self, text: str):
return self._parse_response(self._get_request(text))
def generate_workflow_output(translations, original_text):
items = [
{
"title": translation,
"subtitle": "",
"arg": translation,
}
for translation in translations
]
items.insert(0, {
"title": original_text,
"subtitle": "Pronunciation",
"arg": original_text,
})
return json.dumps({"items": items}, ensure_ascii=False)
if __name__ == "__main__":
text_list = sys.argv[1:]
original_text = ' '.join(text_list)
out_lang = os.getenv("output_language", "zh-CN")
in_lang = os.getenv("input_language", "en")
try:
recognised_lang, translate = Translate(out_lang).get_translation(original_text)
if recognised_lang == out_lang:
_, translate = Translate(in_lang).get_translation(original_text)
output = generate_workflow_output(translate, original_text)
except Exception as e:
output = json.dumps({"items": [{"title": str(e), "subtitle": "Error", "arg": ""}]})
print(output)