-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
400 lines (304 loc) · 12.8 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Description: A simple translator based on translate API
"""A simple translator demo"""
import os
import uuid
import tkinter as tk
import requests
##############################################################################
# Translate API
##############################################################################
class TranslateAPI:
"""This is the base class of Translate API"""
def translate(self, text: str) -> str:
"""The API to translate a string to a string"""
return text
def load_conf(self, key, default=None):
"""Utility to load configuration"""
if key not in os.environ and default is None:
raise NotImplementedError(f"Please Set {key}")
return os.environ.get(key, default)
class MicrosoftTranslateAPI(TranslateAPI):
"""Microsoft Azure Translate API"""
def __init__(self):
default_region = "eastasia"
default_endpoint = "https://api.cognitive.microsofttranslator.com"
default_timeout = 10
self.resource_key = self.load_conf("ST_RES_KEY")
self.region = self.load_conf("ST_REGION", default_region)
self.endpoint = self.load_conf("ST_ENDPOINT", default_endpoint)
self.timeout = self.load_conf("ST_TIMEOUT", default_timeout)
self.headers = {
'Ocp-Apim-Subscription-Key': self.resource_key,
'Ocp-Apim-Subscription-Region': self.region,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
self.api_url = self.endpoint + '/translate'
self.params = {
'api-version': '3.0',
'from': 'en',
'to': ['zh-Hans']
}
def translate(self, text):
translated_text = ""
body = [
{'text': text}
]
try:
request = requests.post(self.api_url,
params=self.params,
headers=self.headers,
timeout=self.timeout,
json=body)
response = request.json()
if (len(response)) == 0:
return translated_text
response = response[0]
response = response['translations']
if (len(response)) == 0:
return translated_text
response = response[0]
translated_text = response['text']
except requests.exceptions.ConnectTimeout:
translated_text = "请求超时"
return translated_text
class DeepLTranslateAPI(TranslateAPI):
"""DeepL Translator API"""
def __init__(self):
default_endpoint = "https://api-free.deepl.com/v2"
default_timeout = 10
self.resource_key = self.load_conf("DEEPL_RES_KEY")
self.endpoint = self.load_conf("DEEPL_ENDPOINT", default_endpoint)
self.timeout = self.load_conf("DEEPL_TIMEOUT", default_timeout)
self.headers = {
'Authorization': f'DeepL-Auth-Key {self.resource_key}',
}
self.api_url = self.endpoint + '/translate'
self.params = {
'source_lang': 'en',
'target_lang': 'zh'
}
def translate(self, text: str) -> str:
translated_text = ""
body = dict(self.params)
body["text"] = text
try:
request = requests.post(self.api_url,
headers=self.headers,
timeout=self.timeout,
data=body)
response = request.json()
if (len(response)) == 0:
return translated_text
response = response['translations']
if (len(response)) == 0:
return translated_text
response = response[0]
translated_text = response['text']
except requests.exceptions.ConnectTimeout:
translated_text = "请求超时"
return translated_text
API_FACTORIES : dict[str, TranslateAPI] = {
"Microsoft": MicrosoftTranslateAPI(),
"DeepL": DeepLTranslateAPI(),
}
DEFAULT_API_VENDOR = "Microsoft"
##############################################################################
# GUI (generated by chatgpt)
##############################################################################
class TranslateGUIModel:
"""The Model part of GUI"""
def __init__(self) -> None:
self.original_text = ""
self.translated_text = ""
self.api_factories = API_FACTORIES
self.select_vendor(DEFAULT_API_VENDOR)
def translate(self, orig_text):
"""Invoke the translate API"""
self.original_text = orig_text
self.translated_text = self.tapi.translate(self.original_text)
def original(self):
"""the original text"""
return self.original_text
def translated(self):
"""the translated text"""
return self.translated_text
def select_vendor(self, vendor):
"""Select the real API"""
# print(f"Change vendor to {vendor}")
if vendor in self.api_factories:
self.tapi = self.api_factories[vendor]
class GUI:
"""GUI structure"""
def __init__(self) -> None:
"""Initialize"""
self.root = None
self.control_frame = None
self.vendor_frame = None
self.frame = None
self.selected_vendor_buttons = {}
self.button = None # translate
def get_root(self):
"""get the root frame"""
return self.root
def get_frames(self):
"""get frames in root frame"""
return self.control_frame, self.vendor_frame, self.frame
class TranslateGUIView:
"""The View part of GUI"""
def __init__(self) -> None:
self.gui = GUI()
self.initialize_main_window()
self.initialize_control_widgets()
self.initialize_vendors()
self.initialize_text_widgets()
def initialize_main_window(self):
"""Initialize the Tk main window"""
self.gui.root = tk.Tk()
self.gui.root.title('Simple Translator Demo')
self.gui.root.geometry('800x600')
def initialize_control_widgets(self):
"""Initialize the control widgets"""
# The frame includes control widgets
self.gui.control_frame = tk.Frame(self.gui.root)
self.gui.control_frame.pack(fill='both', padx=10, pady=10, expand=True)
# create the button
self.gui.button = tk.Button(self.gui.control_frame, text="Paste and Translate")
check_box_trim_var = tk.IntVar()
check_box_trim_var.set(1)
check_box_trim = tk.Checkbutton(self.gui.control_frame,
text="去除换行符",
variable=check_box_trim_var)
self.trim_widget = (check_box_trim_var, check_box_trim)
check_box_monitor_var = tk.IntVar()
check_box_monitor_var.set(0)
check_box_monitor = tk.Checkbutton(self.gui.control_frame,
text="监听剪贴板",
variable=check_box_monitor_var)
self.monitor_widget = (check_box_monitor_var, check_box_monitor)
self.gui.button.grid(row=0, column=0)
self.trim_widget[1].grid(row=0, column=1)
self.monitor_widget[1].grid(row=0, column=2)
def initialize_text_widgets(self):
"""Initialize the text widgets"""
# The frame includes two text widgets
self.gui.frame = tk.Frame(self.gui.root)
self.gui.frame.pack(fill='both', padx=10, pady=10, expand=True)
font = ("DejaVu Sans Mono", 12)
self.texts = [] # there will be two text widgets
for i in range(2):
self.texts.append(tk.Text(self.gui.frame, font=font))
self.texts[0].insert(tk.END, "请点击按钮翻译剪贴板中的内容")
for i in range(2):
self.texts[i].grid(row=i, column=0, pady=5, sticky='nsew')
self.gui.frame.grid_columnconfigure(0, weight=1)
for i in range(2):
self.gui.frame.grid_rowconfigure(i, weight=1)
self.gui.frame.grid_rowconfigure(i, minsize=self.gui.frame.winfo_height()//2)
def initialize_vendors(self):
"""Initialize the vendor radiobuttons"""
self.gui.vendor_frame = tk.Frame(self.gui.root)
self.gui.vendor_frame.pack(fill='both', padx=10, pady=2, expand=True)
self.selected_vendor = tk.StringVar(value=DEFAULT_API_VENDOR)
self.selected_vendor.set(DEFAULT_API_VENDOR)
support_vendors = API_FACTORIES.keys()
for i, vendor_name in enumerate(support_vendors):
radio_button = tk.Radiobutton(self.gui.vendor_frame,
variable=self.selected_vendor,
text=vendor_name, value=vendor_name)
radio_button.grid(row=0, column=i)
self.gui.selected_vendor_buttons[vendor_name] = radio_button
def get_clipboard(self):
"""Get the content from clipboard"""
return self.gui.root.clipboard_get()
def get_trim_flag(self):
"""Get the flag of trim or not"""
return self.trim_widget[0].get()
def get_monitor_flag(self):
"""Get the flag of monitor or not"""
return self.monitor_widget[0].get()
def configure_monitor(self, command):
"""Set the callback of monitor widget"""
self.monitor_widget[1].config(command=command)
def configure_button(self, command):
"""Set the callback of the paste button"""
self.gui.button.config(command=command)
def set_original_text(self, text):
"""Set the content in the original text widget"""
self.texts[0].delete("1.0", tk.END)
self.texts[0].insert(tk.END, text)
def set_translated_text(self, text):
"""Set the content in the translated text widget"""
self.texts[1].delete("1.0", tk.END)
self.texts[1].insert(tk.END, text)
def configure_vendor(self, command):
"""Configure the vendor buttons"""
for button in self.gui.selected_vendor_buttons.values():
button.config(command=command)
def get_selected_vendor(self):
"""Get the vendor name"""
return self.selected_vendor.get()
class TranslateGUIController:
"""The Controller part of GUI"""
def __init__(self, model, view) -> None:
self.model = model
self.view = view
self.view.configure_button(command=self.paste_and_translate)
self.view.configure_monitor(command=self.monitor_clipboard)
self.view.configure_vendor(command=self.select_vendor)
self.run_after_id = None
def paste_and_translate(self):
"""Paste and Translate"""
orig_text = self.view.get_clipboard()
# remove the CR
if self.view.get_trim_flag() == 1:
orig_text = orig_text.splitlines()
orig_text = " ".join(orig_text)
else:
pass
self.model.translate(orig_text)
self.view.set_original_text(self.model.original_text)
self.view.set_translated_text(self.model.translated_text)
def monitor_clipboard(self):
"""When the checkbox is selected or unselected, this method is used"""
if self.view.get_monitor_flag() == 1:
self.run_monitor()
elif self.view.get_monitor_flag() == 0 and self.run_after_id:
self.view.root.after_cancel(self.run_after_id)
self.run_after_id = None
def run_monitor(self):
"""The monitor of clipboard"""
if self.view.get_monitor_flag() == 0 and self.run_after_id:
self.view.root.after_cancel(self.run_after_id)
old_text = self.model.original_text
orig_text = self.view.get_clipboard()
if orig_text != old_text:
self.view.set_original_text(orig_text)
self.run_after_id = self.view.root.after(1000, self.run_monitor)
def select_vendor(self):
"""Select vendor according to the radiobutton"""
vendor = self.view.get_selected_vendor()
self.model.select_vendor(vendor)
class TranslateGUI:
"""The Main part to put MVC together"""
def __init__(self):
self.model = None
self.view = None
self.controller = None
self.init_mvc()
def run(self):
"""Run the GUI"""
self.view.gui.root.mainloop()
def init_mvc(self):
"""Initialize MVC"""
self.model = TranslateGUIModel()
self.view = TranslateGUIView()
self.controller = TranslateGUIController(self.model, self.view)
##############################################################################
# main
##############################################################################
if __name__ == "__main__":
gui = TranslateGUI()
gui.run()