Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/las.py
blob: 04bf17e929fd22103b12adbcfda0041b257a580f (plain)
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
#!/bin/env python
import sys
import os
import dbus
import random
import time
import speechd
import commands
import simplejson
#import csnd
from dict import Dict
from dict import Word

# My class for key detection
class _Getch:
	"""Gets a single character from standard input.  Does not echo to the screen."""
	def __init__(self):
		try:
			self.impl = _GetchWindows()
		except ImportError:
			self.impl = _GetchUnix()

	def __call__(self): return self.impl()

class _GetchUnix:
	def __init__(self):
		import tty, sys

	def __call__(self):
		import sys, tty, termios
		fd = sys.stdin.fileno()
		old_settings = termios.tcgetattr(fd)
		try:
			tty.setraw(sys.stdin.fileno())
			ch = sys.stdin.read(1)
		finally:
			termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
		return ch

class _GetchWindows:
	def __init__(self):
		import msvcrt

	def __call__(self):
		import msvcrt
		return msvcrt.getch()

class Listenspell():

	def __init__(self):
		self.skill_level = 0
		self.points = 0
		self.words_played = 0
		self.words_correct = 0
		self.config_file = 'ls-speechd-config'
		self.path = "."
		self.speechd_init = False
		self.__speechd_default_config = {'pitch':0, 'rate':0, 'language':'en', 'volume':100, 'voice':'MALE1',
							   'spelling':False, 'punctuation':speechd.PunctuationMode.SOME }
		self.__speechd_config = self.__speechd_default_config
		
	def load_db(self, SQLiteDB):
		if self.path == ".":
			return False
		#print self.path + SQLiteDB
		self.dict_obj = Dict(self.path + SQLiteDB)	#Always intitiate first Dict object then Word object
		self.word_obj = Word()
		

	def set_path(self, path):
		if path != "":
			self.path = path + "/"
		else:
			self.path = path

	def play_sound(self,event):

		os.popen("aplay --quiet " + self.path + event + ".wav")

	def set_skill_level(self,level):
		self.skill_level = level
		self.reset_counters()

	def reset_counters(self):
		self.points = 0
		self.words_played = 0
		self.words_correct = 0
	
	def get_skill_level(self):
		return self.skill_level

	def get_words_played(self):
		return self.words_played

	def get_words_correct(self):
		return self.words_correct

	def get_points(self):
		return self.points

	def ans_correct(self, wordid):
		self.play_sound("correct")
		self.points = self.points + self.skill_level
		self.words_correct = self.words_correct + 1
		self.word_obj.update_score(wordid)

	def ans_incorrect(self, wordid):
		self.play_sound("incorrect")
		self.word_obj.update_score(wordid, "incorrect")

	def clear_screen(self,numlines=100):
		"""Clear the console.
        numlines is an optional argument used only as a fall-back.
        """
		import os
		if os.name == "posix":
			# Unix/Linux/MacOS/BSD/etc
			os.system('clear')
		elif os.name in ("nt", "dos", "ce"):
			# DOS/Windows
			os.system('CLS')
		else:
			# Fallback for other operating systems.
			print '\n' * numlines 

	def load_wordid(self, num_words = 0):
		temp_list = []
		self.wordid_list = []
		temp_list = self.dict_obj.get_random_wordid(self.skill_level, num_words)
		for(wordid, ) in temp_list:
			self.wordid_list.append(wordid)
		return self.wordid_list

	def get_word_info(self,wordid, attribute):
		if self.word_obj.get_wordid() != wordid:
			self.word_obj.__init__(identifier = "wordid", value= wordid)
			self.words_played = self.words_played + 1

		if attribute == "def":
			return self.word_obj.get_def()
		elif attribute == "usage":
			return self.word_obj.get_usage()
		elif attribute == "word":
			return self.word_obj.get_word()  
		elif attribute == "phnm":
			phnm = self.word_obj.get_phoneme()
			if phnm == None:
				phnm = self.__get_phoneme(self.word_obj.get_word())
				return phnm
			else:
				(phoneme, is_correct) = phnm
				return phoneme
		else: return False
		
	def __get_phoneme(self, word = None):
		if word == None:
			return False
		phnm = commands.getoutput("/usr/bin/espeak -q -x " + word)
		self.word_obj.update_phoneme(phnm)
		return phnm
		
	
	def get_speechd_config(self, default =0):
		if default == 1:
			return self.__speechd_default_config
		else:
			return self.__speechd_config
		
	
	def load_speechd_config(self):
		try:
			fp = open(self.path + self.config_file)
		except IOError:
			#File doesn't exist, create it and write default config
			fp = open(self.path + self.config_file, 'w', 0)
			speech_config = self.get_speechd_config(1)
			simplejson.dump(speech_config, fp)
		else:
			speech_config = simplejson.load(fp)
		for attr in speech_config:
			self.speechd_config(attr, speech_config[attr])
		fp.close()
		return speech_config
		
		
		
	def __start_speechd(self):  
		try:
			self.client = speechd.SSIPClient('spd-test')
			self.client.set_output_module('espeak')
			self.client.set_language('en')
			self.client.set_punctuation(speechd.PunctuationMode.SOME)
			self.speech_state = None
		except dbus.exceptions.DBusException:
			print "Speech Dispatcher is not turned on."
			return False
		self.speechd_init = True
		
	def __set_speechd_config(self, attribute = None, value = None, mode = 'one', config_obj = None):
		if mode == 'one':
			if attribute == None or value == None:
				return False
			#print attribute + ":" + str(value)
			self.__speechd_config[attribute] = value
			fp = open(self.path + self.config_file, 'w', 0)
			simplejson.dump(self.__speechd_config, fp)
			fp.close()
		elif mode == 'all':
			if config_obj == None:
				return False
			fp = open(self.path + self.config_file, 'w', 0)
			self.__speechd_config = config_obj
			simplejson.dump(self.__speechd_config, fp)
			fp.close()
			
	def speechd_config(self, attribute = None, data = None):
		
		if attribute == None or data == None:
			return False
		
		if self.speechd_init == False:
			if self.__start_speechd() == False:
				return False
		
		attribute_list = ['pitch', 'rate', 'volume', 'voice', 'output_module', 
						  'language', 'punctuation', 'spelling', 'synthesis_voice']
		
		if attribute in attribute_list:
			try:
				self.__set_speechd_config(attribute, data)
				if attribute == "pitch":
					self.client.set_pitch(int(data)) #-100 to 100
				elif attribute == "rate":
					self.client.set_rate(int(data)) # -100 to 100
				elif attribute == "volume":
					self.client.set_volume(int(data))#-100 to 100
				elif attribute == "voice":
					self.client.set_voice(str(data))#(FE)MALE(1,2,3), CHILD_(FE)MALE
				elif attribute == "output_module":
					self.client.set_output_module(str(data))
				elif attribute == "language":
					self.client.set_language(str(data))
				elif attribute == "punctuation":
					self.client.set_punctuation(data)
				elif attribute == "spelling":
					self.client.set_spelling(bool(data)) # True or False
				elif attribute == "synthesis_voice":
					self.client.set_synthesis_voice(str(data))#self.client.list_synthesis_voices()
			except AssertionError, e:
				print "Assertion Error: " + str(e) + ":" + str(attribute) + ":" + str(data)
				return False
		else: return False
		
	def __speechd_callback(self,callback_type):
		self.speech_state = callback_type

	def say_text(self, text, wait= True):
		#wait: to wait for the text to be spoken or not
		#os.popen("espeak " + text)
		if self.speechd_init == False:
			if self.__start_speechd() == False:
				return False

		text = str(text)
		self.speech_state = None
				
		self.client.speak(text, callback=self.__speechd_callback,event_types=(speechd.CallbackType.BEGIN, 
														speechd.CallbackType.CANCEL,
														speechd.CallbackType.END))
		if wait == True:
			while(self.speech_state != "end"):
				time.sleep(1)
			
	

	def get_key(self):
		for longestinput in range(15):
			inkey = _Getch()
			for i in xrange(sys.maxint):
				k=inkey()
				if k<>'':break
				elif k == '\r': break
			return k

	def exit_game(self):
		self.word_obj.exit_game()
		self.dict_obj.exit_game()
		self.say_text("goodbye")
		self.client.close()
		sys.exit()