-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
538 lines (447 loc) · 16.9 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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#!/usr/bin/env python
"""
iWriteIt - You Like?
Copyright (C) 2014 Suriyan Laohaprapanon
For comments, suggestions or other messages, contact me at:
This file is part of iWriteIt.
iWriteIt is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
iWriteIt is distributed in the hope that it will be fun,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with iWriteIt. If not, see <http://www.gnu.org/licenses/>.
"""
### 'multistroke' just available in master branch
#import kivy
#kivy.require('1.8.1-dev')
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty, StringProperty, NumericProperty
from kivy.clock import Clock
from kivy.utils import platform
from kivy.core.audio import SoundLoader
from kivy.graphics import Color, Ellipse, Line
from kivy.multistroke import Recognizer
from threading import Thread
from random import randint
from plyer import tts
from helpers import InfoPopup
__version__ = "1.0.0"
MAX_DIGITS = 4
class Background(Image):
""" Background image
"""
pass
class DigitBox(Widget):
""" Class of single digit
"""
text = StringProperty(None)
answer = NumericProperty(None)
def __init__(self, **kwargs):
super(DigitBox, self).__init__(**kwargs)
def clear(self):
self.text = ""
class AppSettings(BoxLayout):
""" Application settings
"""
app = ObjectProperty(None)
def __init__(self, **kwargs):
super(AppSettings, self).__init__(**kwargs)
def write_settings(self):
""" Write back current settings to configuration file
"""
val = 'yes' if self.ids._music.active else 'no'
self.app.config.set('general', 'music', val)
val = 'yes' if self.ids._voice.active else 'no'
self.app.config.set('general', 'voice', val)
self.app.config.set('basicmath', 'maxdigits', self.ids._maxdigits.text)
self.app.config.set('basicmath', 'operation', self.ids._operation.text)
self.app.config.write()
self.app.play_music()
def read_settings(self):
""" Read settings to screen
"""
if self.app.config.get('general', 'music') == 'yes':
self.ids._music.active = True
else:
self.ids._music.active = False
if self.app.config.get('general', 'voice') == 'yes':
self.ids._voice.active = True
else:
self.ids._voice.active = False
self.ids._maxdigits.text = self.app.config.get('basicmath', 'maxdigits')
self.ids._operation.text = self.app.config.get('basicmath', 'operation')
class WriteBoard(FloatLayout):
""" Write board
"""
digit1 = ObjectProperty()
digit2 = ObjectProperty()
digit3 = ObjectProperty()
digit4 = ObjectProperty()
result_area = ObjectProperty()
surface = ObjectProperty()
root = ObjectProperty()
def __init__(self, **kwargs):
super(WriteBoard, self).__init__(**kwargs)
self.a = None
self.recognizer = None
self.infopopup = InfoPopup()
def on_touch_down(self, touch):
if self.menu.collide_point(*touch.pos):
return self.menu.on_touch_down(touch)
if self.collide_point(*touch.pos) and \
not self.result_area.collide_point(*touch.pos):
userdata = touch.ud
userdata['color'] = c = (1, 0, 0)
with self.canvas.after:
Color(*c, mode='rgb')
d = 6
Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d, d))
userdata['line'] = Line(points=(touch.x, touch.y), width=3)
return True
else:
return super(WriteBoard, self).on_touch_down(touch)
def on_touch_move(self, touch):
if self.menu.collide_point(*touch.pos):
return self.menu.on_touch_move(touch)
if self.collide_point(*touch.pos) and \
not self.result_area.collide_point(*touch.pos):
if 'line' in touch.ud:
touch.ud['line'].points += [touch.x, touch.y]
return True
else:
return super(WriteBoard, self).on_touch_move(touch)
def on_touch_up(self, touch):
if self.menu.collide_point(*touch.pos):
return self.menu.on_touch_up(touch)
if self.collide_point(*touch.pos) and \
not self.result_area.collide_point(*touch.pos):
return True
else:
return super(WriteBoard, self).on_touch_up(touch)
def on_enter(self):
if self.recognizer is None:
self.recognizer = Recognizer()
self.surface.bind(on_gesture_discard=self.handle_gesture_discard)
self.surface.bind(on_gesture_complete=self.handle_gesture_complete)
self.surface.bind(on_gesture_cleanup=self.handle_gesture_cleanup)
self.recognizer.db = []
self.recognizer.import_gesture(filename='gestures/user')
def clear(self, all=False):
if all:
self.canvas.after.clear()
self.digit1.clear()
self.digit2.clear()
self.digit3.clear()
self.digit4.clear()
def _to_int(self, s):
try:
i = int(s)
except:
i = 0
return i
def get_answer(self):
return eval("%d %s %s" % (self.a, self.oper, self.b))
def check(self, popup=False, voice=False):
a1 = self._to_int(self.digit1.text)
a2 = self._to_int(self.digit2.text)
a3 = self._to_int(self.digit3.text)
a4 = self._to_int(self.digit4.text)
answer = a4 * 1000 + a3 * 100 + a2 * 10 + a1
if answer == self.get_answer():
if popup:
self.infopopup.text = "Correct, very good!!!"
self.infopopup.open()
if voice:
self.root.app.speak("Correct answer")
return True
else:
return False
def set_digits(self, num, prefix):
leading = True
for i in range(MAX_DIGITS, 1, -1):
mul = 10**(i - 1)
if num >= mul:
leading = False
self.ids['%s%d' % (prefix, i)].text = str(int(num / mul))
num %= mul
else:
if leading:
self.ids['%s%d' % (prefix, i)].text = ""
else:
self.ids['%s%d' % (prefix, i)].text = "0"
self.ids['%s%d' % (prefix, 1)].text = str(num)
def set_answer(self, ans, prefix):
for i in range(MAX_DIGITS, 1, -1):
mul = 10**(i - 1)
if ans >= mul:
self.ids['%s%d' % (prefix, i)].answer = int(ans / mul)
ans %= mul
else:
self.ids['%s%d' % (prefix, i)].answer = 0
self.ids['%s%d' % (prefix, 1)].answer = ans
def new_question(self):
maxdigits = int(self.root.app.config.get('basicmath', 'maxdigits'))
maxnum = 10 ** maxdigits - 1
oper = self.root.app.config.get('basicmath', 'operation')
if oper == 'Mix':
if randint(0, 1):
self.oper = '+'
else:
self.oper = '-'
elif oper == 'Plus':
self.oper = '+'
else:
self.oper = '-'
a = randint(0, maxnum)
b = randint(0, maxnum)
if self.oper == '-' and a < b:
self.a = b
self.b = a
else:
self.a = a
self.b = b
def new(self):
if self.a is None or self.check():
self.clear(True)
self.new_question()
self.set_digits(self.a, 'a')
self.ids._operator.text = self.oper
self.set_digits(self.b, 'b')
text = ("%d %s %d" %
(self.a, 'plus' if self.oper == '+' else 'minus', self.b))
self.root.app.speak(text)
ans = self.get_answer()
self.set_answer(ans, '_digit')
else:
self.clear(True)
def handle_gesture_cleanup(self, surface, g, *l):
if hasattr(g, '_result_label'):
surface.remove_widget(g._result_label)
def handle_gesture_discard(self, surface, g, *l):
# Don't bother creating Label if it's not going to be drawn
if surface.draw_timeout == 0:
return
text = "Please write a number"
self.root.app.speak(text)
text = '[b]%s[/b]' % text
g._result_label = Label(text=text, markup=True, size_hint=(None, None),
center=(g.bbox['minx'], g.bbox['miny']))
self.surface.add_widget(g._result_label)
def handle_gesture_complete(self, surface, g, *l):
result = self.recognizer.recognize(g.get_vectors())
result._gesture_obj = g
result.bind(on_complete=self.handle_recognize_complete)
def handle_recognize_complete(self, result, *l):
# Don't bother creating Label if it's not going to be drawn
if self.surface.draw_timeout == 0:
return
best = result.best
if best['name'] is None:
num = ""
self.root.app.speak("Please write a number")
else:
num = best['name']
g = result._gesture_obj
x = g.bbox['minx']
y = g.bbox['miny']
w = Widget(pos=(x, y), size=(g.width, g.height))
if self.digit1.collide_widget(w):
self.digit1.text = num
elif self.digit2.collide_widget(w):
self.digit2.text = num
elif self.digit3.collide_widget(w):
self.digit3.text = num
elif self.digit4.collide_widget(w):
self.digit4.text = num
if self.check(voice=True):
Clock.schedule_once(lambda dt: self.new(), 3)
else:
self.root.app.speak(num)
class MyGestureLoadPopup(Popup):
""" My Gesture Load popup
"""
pass
class MyGestureSavePopup(Popup):
""" My Gesture Save Popup
"""
pass
class MyGestureWidget(BoxLayout):
""" My Gesture Widget
"""
surface = ObjectProperty()
def __init__(self, **kwargs):
super(MyGestureWidget, self).__init__(**kwargs)
self.recognizer = None
self.load_popup = None
self.save_popup = None
self.info_popup = None
def on_enter(self):
if self.recognizer is None:
self.recognizer = Recognizer()
self.surface.bind(on_gesture_discard=self.handle_gesture_discard)
self.surface.bind(on_gesture_complete=self.handle_gesture_complete)
self.surface.bind(on_gesture_cleanup=self.handle_gesture_cleanup)
self.recognizer.db = []
self.recognizer.import_gesture(filename='gestures/user')
if self.load_popup is None:
self.load_popup = MyGestureLoadPopup()
self.load_popup.ids.filechooser.bind(on_submit=self.do_load)
if self.save_popup is None:
self.save_popup = MyGestureSavePopup()
self.save_popup.ids.save_btn.bind(on_press=self.do_save)
if self.info_popup is None:
self.info_popup = InfoPopup()
def on_pre_leave(self):
self.recognizer.export_gesture(filename='gestures/user')
def do_load(self, filechooser, *l):
if len(filechooser.selection):
self.recognizer.db = []
for f in filechooser.selection:
self.recognizer.import_gesture(filename=f)
self.info_popup.text = ("Loaded %d gestures.\n" %
(len(self.recognizer.db)))
self.load_popup.dismiss()
self.info_popup.open()
def do_save(self, *l):
path = self.save_popup.ids.filename.text
if not path or path == 'default':
self.save_popup.dismiss()
self.info_popup.text = 'Empty or Invalid gesture name specify'
self.info_popup.open()
return
elif not path.lower().endswith('.kg'):
path += '.kg'
self.recognizer.export_gesture(filename='./gestures/' + path)
self.save_popup.dismiss()
self.info_popup.text = 'Gestures saved!'
self.info_popup.open()
def handle_gesture_cleanup(self, surface, g, *l):
if hasattr(g, '_result_label'):
surface.remove_widget(g._result_label)
def handle_gesture_discard(self, surface, g, *l):
# Don't bother creating Label if it's not going to be drawn
if surface.draw_timeout == 0:
return
text = '[b]Please trace a number[/b]'
g._result_label = Label(text=text, markup=True, size_hint=(None, None),
center=(g.bbox['minx'], g.bbox['miny']))
surface.add_widget(g._result_label)
def handle_gesture_complete(self, surface, g, *l):
result = self.recognizer.recognize(g.get_vectors())
result._gesture_obj = g
result.bind(on_complete=self.handle_recognize_complete)
def handle_recognize_complete(self, result, *l):
# Don't bother creating Label if it's not going to be drawn
if self.surface.draw_timeout == 0:
return
best = result.best
if best['name'] is None:
num = ""
else:
num = best['name']
g = result._gesture_obj
x = g.bbox['minx']
y = g.bbox['miny']
w = Widget(pos=(x, y), size=(g.width, g.height))
for i in range(0, 10):
digit = self.ids['_mydigit%d' % i]
if digit.collide_widget(w):
name = digit.text
break
if num == name:
text = '[b]Exist[/b]'
else:
text = '[b]Update[/b]'
self.recognizer.add_gesture(name, g.get_vectors())
g._result_label = Label(text=text, markup=True, size_hint=(None, None),
center=(g.bbox['minx'], g.bbox['miny']))
self.surface.add_widget(g._result_label)
self.root.app.speak(name)
def load(self):
# FIXME: Change filter to trig filechooser refreshing
self.load_popup.ids.filechooser.filters = ['*._kg']
self.load_popup.open()
self.load_popup.ids.filechooser.filters = ['*.kg']
def save(self):
self.save_popup.open()
def clear(self):
self.recognizer.db = []
class RootWidget(FloatLayout):
""" Root Widget of Application
"""
app = ObjectProperty()
manager = ObjectProperty()
board = ObjectProperty()
settings = ObjectProperty()
mygesture = ObjectProperty()
def __init__(self, **kwargs):
super(RootWidget, self).__init__(**kwargs)
class iWriteItApp(App):
title = 'iWriteIt - You Like?'
if platform == 'win':
icon = 'graphics/icon-64.ico'
elif platform == 'macosx':
icon = 'graphics/icon.icns'
else:
icon = 'graphics/icon-64.png'
music = None
# FIXME: to hide Kivy settings
#use_kivy_settings = False
# To fully disable settings windows
#def open_settings(self, *largs):
# pass
def build(self):
music = "sounds/music.%s" % ('wav' if platform == 'macosx' else 'ogg')
self.music = SoundLoader.load(music)
self.play_music()
self.root = RootWidget(app=self)
self.speak("Welcome to I Write It")
return self.root
def build_config(self, config):
config.adddefaultsection('general')
config.setdefault('general', 'music', 'yes')
config.setdefault('general', 'voice', 'yes')
config.adddefaultsection('basicmath')
config.setdefault('basicmath', 'maxdigits', '2')
config.setdefault('basicmath', 'operation', 'Plus')
def on_pause(self):
self.music.stop()
return True
def on_resume(self):
# Here you can check if any data needs replacing (usually nothing)
self.play_music()
pass
def play_music(self):
if self.config.get('general', 'music') == 'yes':
# Fix volume to 30% for background music
self.music.volume = 0.3
self.music.loop = True
self.music.play()
else:
self.music.stop()
def speak(self, text):
if self.config.get('general', 'voice') == "yes":
if platform == 'android':
Clock.schedule_once(lambda dt, t=text: tts.speak(t), 0.1)
else:
thread = Thread(target=tts.speak, args=(text,))
thread.start()
def start(self):
self.root.manager.current = "writing"
self.root.board.new()
def settings(self):
self.root.settings.read_settings()
self.root.manager.current = "settings"
if __name__ in ['__main__', '__android__']:
iWriteItApp().run()