-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict.py
executable file
·441 lines (365 loc) · 13.4 KB
/
dict.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import sys, os, re, errno, time
import urllib2
# invoke 'play'(linux) or 'afplay'(Mac OS X) command
import subprocess
# generate random number in exercise mode
from random import randint
from bs4 import BeautifulSoup
from colorama import Fore
import dbm
# for exercise mode, shuffle the words list
from random import shuffle
class Dictionary(wx.Frame):
def __init__(self, parent, title):
super(Dictionary, self).__init__(parent, title=title, size=(560, 420))
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
self.word=""
self.audio_url = ""
self.audio_name = ""
# store frame position
self.x = 0
self.y = 0
panel = wx.Panel(self, -1)
panel.SetBackgroundColour('#726E6D')
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
# create,add word area and search button
self.word_search = wx.TextCtrl(panel, id = 10, style = wx.PROCESS_ENTER)
self.icon = wx.StaticBitmap(panel, bitmap=wx.Bitmap('resize_voice.png'))
self.zh_check = wx.CheckBox(panel, label='中文', size=(60,30))
self.zh_check.SetValue(True)
# create chinese meaning text area
self.zh_meaning = wx.TextCtrl(panel, id = 22, size=(350,170),style = wx.TE_MULTILINE)
self.memo = wx.TextCtrl(panel, id = 30, style = wx.TE_MULTILINE)
# Add save memo button
save_btn = wx.Button(panel, label='Save')
self.exercise_btn = wx.Button(panel, label='Exercise')
hbox1.Add(self.word_search, proportion=4, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
hbox1.Add(self.icon, flag=wx.EXPAND|wx.TOP, border=10)
hbox1.Add(self.zh_check, proportion=1, flag=wx.LEFT|wx.TOP, border=10)
hbox2.Add(self.zh_meaning, proportion=1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
hbox3.Add(self.memo, proportion=1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
hbox4.Add(save_btn, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
hbox4.Add(self.exercise_btn, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add(hbox2, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add(hbox3, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add(hbox4, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
# Set focus on the word_search area
self.word_search.SetFocus()
# Bind methods to word_search and check boxes
self.word_search.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
save_btn.Bind(wx.EVT_BUTTON, self.OnSaveMemo)
self.exercise_btn.Bind(wx.EVT_BUTTON, self.InitSUBUI)
self.icon.Bind(wx.EVT_LEFT_DOWN, self.OnSound)
self.Bind(wx.EVT_MOVE, self.OnMove)
panel.SetSizer(vbox)
mkdir_p('mp3_dir')
font = wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
self.word_search.SetFont(font)
self.zh_meaning.SetFont(font)
self.memo.SetFont(font)
def OnMove(self, e):
self.x, self.y = e.GetPosition()
def OnSearch(self, event):
# Get input word to search
#http://stackoverflow.com/questions/17887503/how-can-i-improve-this-code-for-checking-if-text-fields-are-empty-in-wxpython
self.word = self.word_search.GetValue().strip() or None
if self.word is None:
self.zh_meaning.Clear()
return
# create word url
zh_word_url = 'http://dict.cn/'+self.word
zh_word_content = ""
self.audio_url = "http://translate.google.com/translate_tts?tl=en&q="+self.word
self.audio_dir = os.getcwd()+"/mp3_dir"
self.audio_name = self.audio_dir+'/'+self.word+'.mp3'
if self.zh_check.IsChecked():
zh_file = urllib2.urlopen(zh_word_url)
zh_html = zh_file.read()
soup = BeautifulSoup(zh_html)
phonetic = soup.find('div', class_ = 'phonetic')
# if can not find the word
try:
pronunciations = phonetic.find_all('bdo')
pronun = pronunciations[0].find(text=True)
zh_word_content = pronun + '\n\n'
except AttributeError:
pass
except IndexError:
pass
# basic meanings of the word
layout_dual = soup.find('div', class_ = 'layout dual')
if layout_dual is None:
basic = soup.find('div', class_ = 'layout basic clearfix')
try:
word_meanings = basic.find_all('strong')
except AttributeError:
self.zh_meaning.Clear()
self.memo.Clear()
self.word_search.SelectAll()
return
for meaning in word_meanings:
text = meaning.find(text=True)
zh_word_content = zh_word_content + text + '\n\n'
self.zh_meaning.SetValue(zh_word_content.encode('utf-8'))
else:
# word meanings in detail
li_tags = layout_dual.find_all('li')
for li in li_tags:
zh_word_content = zh_word_content + li.get_text() + '\n\n'
self.zh_meaning.SetValue(zh_word_content.encode('utf-8'))
process_audio(self.audio_url, self.audio_name)
self.word_search.SelectAll()
##############################################
#try to find the memo about the word from file
##############################################
f = dbm.open('memo_words', "c")
try:
self.memo.SetValue(f[self.word].decode('utf-8'))
except KeyError, e:
self.memo.Clear()
finally:
f.close()
def OnSaveMemo(self,e):
zh_file = dbm.open('zh_words','c')
memo_file = dbm.open('memo_words','c')
if self.word is '':
return
try:
zh_file[self.word] = self.zh_meaning.GetValue().strip().encode('utf-8')
except AttributeError:
return
memo_file[self.word] = self.memo.GetValue().strip().encode('utf-8')
zh_file.close()
memo_file.close()
self.word_search.SetFocus()
def InitSUBUI(self, e):
exercise_ui = SUBUI(None,title = 'Exercise')
exercise_ui.SetPosition((self.x, self.y))
exercise_ui.Show(True)
# MakeModal(modal):Disables all other windows in the application so that the user can only interact with this window.
exercise_ui.MakeModal(True)
def OnSound(self, event):
if self.word is "":
return
else:
process_audio(self.audio_url, self.audio_name)
class SUBUI(wx.Frame):
def __init__(self, parent, title):
super(SUBUI, self).__init__(parent, title=title, size=(560, 420))
self.InitUI()
def InitUI(self):
self.last_word = ""
self.audio_url = ""
self.audio_name = ""
self.audio_url = ""
self.audio_dir = os.getcwd()+"/mp3_dir"
self.audio_name = ""
self.db_memo = dbm.open('memo_words', 'c')
self.db_words = dbm.open('zh_words', 'c')
panel = wx.Panel(self, -1)
panel.SetBackgroundColour('#726E6D')
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
self.zh_meaning = wx.TextCtrl(panel, id = 50, size=(350,170),style = wx.TE_MULTILINE)
self.memo = wx.TextCtrl(panel, id = 60, style = wx.TE_MULTILINE)
self.word_search = wx.TextCtrl(panel, id = 70, style = wx.PROCESS_ENTER)
self.start_btn = wx.Button(panel, id = 72,label='Start')
self.icon = wx.StaticBitmap(panel, bitmap=wx.Bitmap('resize_voice.png'))
self.gauge = wx.Gauge(panel)
self.del_btn = wx.Button(panel, id = 80, label = 'Delete word')
self.sc = wx.SpinCtrl(panel, id = 82, value='15', size=(60,25) )
self.sc.SetRange(1,1000)
hbox1.Add(self.zh_meaning, proportion=1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
hbox2.Add(self.memo, proportion=1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
hbox3.Add(self.word_search, proportion=1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
hbox3.Add(self.start_btn, flag=wx.EXPAND| wx.LEFT|wx.RIGHT, border=10)
hbox3.Add(self.icon, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
hbox3.Add(self.gauge, proportion=2, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
hbox4.Add(self.del_btn, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
hbox4.Add(self.sc, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)
vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add(hbox2, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add(hbox3, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add(hbox4, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
panel.SetSizer(vbox)
self.start_btn.SetFocus()
# Start timer
self.timer1 = wx.Timer(self, id = 100)
self.Bind(wx.EVT_TIMER, self.update, self.timer1)
self.Bind(wx.EVT_BUTTON, self.OnStartTimer, self.start_btn)
self.icon.Bind(wx.EVT_LEFT_DOWN, self.OnSound)
self.Bind(wx.EVT_CLOSE, self.on_close)
self.Bind(wx.EVT_TEXT_ENTER, self.OnCheck, self.word_search)
self.Bind(wx.EVT_BUTTON, self.OnDeleteWord, self.del_btn)
font = wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
self.zh_meaning.SetFont(font)
self.memo.SetFont(font)
def OnStartTimer(self, event):
if self.timer1.IsRunning():
self.timer1.Stop()
self.start_btn.SetLabel("Start")
else:
self.start_btn.SetLabel("Typing...")
self.word_search.SetFocus()
self.timer1.Start(1000)
self.start = time.time()
self.exercise_mode()
def update(self, event):
end = time.time() - self.start
def on_close(self, evt):
self.MakeModal(False)
evt.Skip()
# Get the value from word_search area
def OnCheck(self, event):
#http://effbot.org/librarybook/dbm.htm
input_str = self.word_search.GetValue() or None
if self.last_word == "":
self.word_search.Clear()
return
if input_str == self.last_word:
self.count = self.count + 1
self.gauge.SetValue(self.count)
if self.count == self.task_range:
self.last_word = ''
self.word_search.Clear()
self.zh_meaning.Clear()
self.memo.Clear()
self.timer1.Stop()
self.start_btn.SetLabel("Start")
self.start_btn.SetFocus()
self.gauge.SetLabel("Task Completed")
return
try:
self.last_word = self.zh_li.pop()
except IndexError:
self.start_btn.SetFocus()
self.word_search.Clear()
self.zh_meaning.Clear()
self.memo.Clear()
self.timer1.Stop()
self.start_btn.SetLabel("Start")
return
self.zh_meaning.SetValue(self.db_words[self.last_word].decode('utf-8'))
try:
self.memo.SetValue(self.db_memo[self.last_word].decode('utf-8'))
except KeyError:
pass
self.audio_url = "http://translate.google.com/translate_tts?tl=en&q="+self.last_word
self.audio_name = self.audio_dir+'/'+self.last_word+'.mp3'
process_audio(self.audio_url, self.audio_name)
self.word_search.Clear()
else:
self.word_search.SetValue(self.last_word)
self.word_search.SelectAll()
def exercise_mode(self):
self.zh_li = []
for key in self.db_words.keys():
self.zh_li.append(key)
if len(self.zh_li)== 0:
self.timer1.Stop()
self.start_btn.SetLabel("Start")
return
shuffle(self.zh_li)
practice_number = self.sc.GetValue()
self.zh_li = self.zh_li[0:practice_number]
# gauge count
self.count = 0
self.task_range = len(self.zh_li)
self.gauge.SetRange(self.task_range)
try:
self.last_word = self.zh_li.pop()
except IndexError:
self.word_search.Clear()
self.zh_meaning.Clear()
self.memo.Clear()
return
self.zh_meaning.SetValue(self.db_words[self.last_word].decode('utf-8'))
try:
self.memo.SetValue(self.db_memo[self.last_word].decode('utf-8'))
except KeyError:
pass
# play sound after press Start button
self.audio_url = "http://translate.google.com/translate_tts?tl=en&q="+self.last_word
self.audio_name = self.audio_dir+'/'+self.last_word+'.mp3'
process_audio(self.audio_url, self.audio_name)
def OnDeleteWord(self,event):
if self.last_word == "":
return
try:
del self.db_words[self.last_word]
del self.db_memo[self.last_word]
self.count = self.count + 1
self.gauge.SetValue(self.count)
self.word_search.SetFocus()
except KeyError:
pass
try:
self.last_word = self.zh_li.pop()
except IndexError:
self.timer1.Stop()
self.start_btn.SetLabel("Start")
self.word_search.Clear()
self.zh_meaning.Clear()
self.memo.Clear()
return
self.zh_meaning.SetValue(self.db_words[self.last_word].decode('utf-8'))
try:
self.memo.SetValue(self.db_memo[self.last_word].decode('utf-8'))
except KeyError:
pass
self.audio_url = "http://translate.google.com/translate_tts?tl=en&q="+self.last_word
self.audio_name = self.audio_dir+'/'+self.last_word+'.mp3'
process_audio(self.audio_url, self.audio_name)
def OnSound(self, event):
if self.last_word is "":
return
else:
process_audio(self.audio_url, self.audio_name)
def process_audio(audio_url, mp3_name):
if os.path.exists(mp3_name):
if sys.platform == 'darwin':
process = subprocess.Popen(['afplay', mp3_name], stdout=open("/dev/null","w"),stderr=subprocess.STDOUT)
else:
process = subprocess.Popen(['play', mp3_name], stdout=open("/dev/null","w"), stderr=subprocess.STDOUT)
# retcode = process.wait()
else:
# download mp3 file to $HOME/mp3.dir
download_mp3(audio_url, mp3_name)
# find wait function on the last line
if sys.platform == 'darwin':
process = subprocess.Popen(['afplay', mp3_name], stdout=open("/dev/null","w"), stderr=subprocess.STDOUT)
else:
process = subprocess.Popen(['play', mp3_name], stdout=open("/dev/null","w"), stderr=subprocess.STDOUT)
# retcode = process.wait()
def download_mp3(audio_url, mp3_name):
headers = {'User-Agent':'Mozilla/5.0'}
request = urllib2.Request(audio_url, None, headers)
mp3file = urllib2.urlopen(request)
with open(mp3_name, 'wb') as output_mp3:
output_mp3.write(mp3file.read())
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
if __name__ == '__main__':
app = wx.App(False)
main_frame = Dictionary(None, title='Dictionary')
app.MainLoop()