-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1522 lines (1256 loc) · 55.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ctypes
import datetime
import json
import os
import random
import smtplib
import time
import urllib
import webbrowser
from time import ctime
from urllib.request import urlopen
from docx import Document
import re
import discord
from dotenv import load_dotenv
import folium
import mysql.connector
import playsound
import pygeoip
import pyjokes
import pyttsx3
import selenium.common.exceptions
import speech_recognition as sr
import wikipedia
import wolframalpha
from ecapture import ecapture as ec
from gtts import gTTS
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from translate import Translator
from win10toast import ToastNotifier
from DBHandler import DBHandler
from app import App
from chatbot import ConversationMode
from neural_network import NeuralNetworkLoader
from util import getAppConfig
from chatbotgit import main
from audio_engine import AudioEngine
# Class Template defining personal and customizable voice assistant bot
# Main actions performed:
# ---- basic conversation
# ---- search on google
# ---- play song on youtube
# ---- find location on google maps
# ---- shutdown or restart computer
# ---- talk to data base
# ---- translation
# ---- to be continued
class TalkingBot(object):
# constructor
def __init__(self, name, sex, client_discord):
self.config = getAppConfig("./settings.json")
self.client_discord = client_discord
self.is_engaged = False
self.channel = None
self.name = name
self.sex = sex
self.speech_unrecognizable = False
self.engine = pyttsx3.init()
self.engine.setProperty('rate', 190)
self.voices = dict()
self.voices['Zira'] = 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_EN-US_ZIRA_11.0'
self.voices['David'] = 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_EN' \
'-US_DAVID_11.0 '
self.voices['Hazel'] = 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_EN' \
'-GB_HAZEL_11.0 '
self.lang_dict = dict()
self.lang_dict['romanian'] = 'ro'
self.lang_dict['english'] = 'en'
self.lang_dict['french'] = 'fr'
self.lang_dict['german'] = 'de'
self.lang_dict['russian'] = 'ru'
self.lang_dict['spanish'] = 'es'
self.lang_dict['italian'] = 'it'
self.lang_dict['greek'] = 'el'
self.lang_dict['danish'] = 'da'
self.lang_dict['portuguese'] = 'pt'
self.lang_dict['arabic'] = 'ar'
self.lang_dict['japanese'] = 'ja'
self.lang_dict['korean'] = 'ko'
self.lang_dict['turkish'] = 'tr'
self.lang_list = ['romanian', 'english', 'french', 'german', 'russian', 'spanish', 'italian', 'greek', 'danish',
'japanese', 'arabic', 'chinese', 'turkish', 'korean']
self.record = False
self.logs = open('Logging.txt', 'a+')
self.logs.write('\n\n')
str_time = datetime.datetime.now().strftime("%H:%M:%S")
self.logs.write(str_time + '\n')
self.brain = NeuralNetworkLoader()
self.brain.updateNeuralNetwork()
self.conversation_engine = ConversationMode()
# try:
# self.db_manager = DBHandler()
# except mysql.connector.errors.InterfaceError:
# await self.bot_speak('Sorry, but connection to data base failed...')
# # exit()
# except ConnectionRefusedError:
# await self.bot_speak('Sorry, but connection to data base failed...')
# # exit()
self.r = sr.Recognizer()
self.m = sr.Microphone()
# change voice format
async def change_voice(self):
await self.bot_speak('My voice is gonna be switched...')
if self.sex == 'm':
self.sex = 'f'
self.bot_speak_m('Choose your favourite feminine voice ID: 0, 1 or 2')
while True:
voice = await self.record_audio()
if self.speech_unrecognizable is False and voice.isnumeric() is True:
break
if int(voice) == 0:
self.sex += '0'
elif int(voice) == 1:
self.sex += '1'
else:
self.sex += '2'
else:
self.sex = 'm'
# male voice
def bot_speak_m(self, command):
# Initialize the engine
self.engine.setProperty('voice', self.voices['David'])
self.engine.say(command)
if self.record is True:
self.logs.write('\nAlexis: ' + command)
self.engine.runAndWait()
# female1 voice
def bot_speak_h(self, command):
# Initialize the engine
self.engine.setProperty('voice', self.voices['Hazel'])
self.engine.say(command)
if self.record is True:
self.logs.write('\nAlexis: ' + command)
self.engine.runAndWait()
# female2 voice
def bot_speak_z(self, command):
# Initialize the engine
self.engine.setProperty('voice', self.voices['Zira'])
self.engine.say(command)
if self.record is True:
self.logs.write('\nAlexis: ' + command)
self.engine.runAndWait()
# female0 voice
def bot_speak_f(self, command):
tts = gTTS(text=command, lang='en')
rand = random.randint(1, 10000000)
audio_file = 'audio-' + str(rand) + '.mp3'
tts.save(audio_file)
playsound.playsound(audio_file)
if self.record is True:
self.logs.write('\nAlexis: ' + command)
os.remove(audio_file)
# custom language voice
async def bot_speak_language(self, command, language):
if self.sex == 'discord':
await self.bot_speak_to_discord(command)
else:
tts = gTTS(text=command, lang=language)
rand = random.randint(1, 10000000)
audio_file = 'audio-' + str(rand) + '.mp3'
tts.save(audio_file)
playsound.playsound(audio_file)
print('\n' + command)
if self.record is True:
if language in 'ru el zh ja ko ar':
self.logs.write('\nAlexis: ' + 'Encoding characters not supported in ' + language)
else:
self.logs.write('\nAlexis: ' + command + ' - in ' + language)
os.remove(audio_file)
# bot voice (sync)
async def bot_speak(self, command):
print('\nAlexis: ' + command)
if self.sex == 'm':
self.bot_speak_m(command)
else:
if self.sex == 'f0':
self.bot_speak_f(command)
elif self.sex == 'f1':
self.bot_speak_h(command)
elif self.sex == 'discord':
await self.bot_speak_to_discord(command)
else:
self.bot_speak_z(command)
# listen to audio thread
async def record_audio(self):
if self.sex == 'discord':
message = await self.client_discord.wait_for('message', timeout=100.0)
self.speech_unrecognizable = False
return message.content.lower()
else:
self.speech_unrecognizable = False
with self.m as source:
self.r.adjust_for_ambient_noise(source)
audio = self.r.listen(source)
voice_data_local = ''
try:
voice_data_local = self.r.recognize_google(audio)
if self.record is True:
self.logs.write('\nSami: ' + voice_data_local)
except sr.UnknownValueError:
if random.randint(1, 1000) % 10 == 0:
await self.bot_speak('Sorry, I did not get that')
self.speech_unrecognizable = True
except sr.RequestError:
await self.bot_speak('Sorry, my speech service is not working. I will stop my execution thread')
exit()
print('\nMe: ' + voice_data_local)
if 'text' in voice_data_local or 'write' in voice_data_local:
voice_data_local = input("Enter text:> ")
return voice_data_local.lower()
# self presentation
async def say_my_name(self):
await self.bot_speak('My name is ' + self.name + ' and I am your personal voice assistant')
# tell current time
async def get_current_time(self):
await self.bot_speak('The current time is ' + ctime())
# search something on google
async def search_for(self):
self.is_engaged = True
await self.bot_speak('What do you want to search for?')
while True:
search_for = await self.record_audio()
if self.speech_unrecognizable is False:
break
url = 'https://google.com/search?q=' + search_for
webbrowser.get().open(url)
await self.bot_speak('Here is what I found for ' + search_for)
self.is_engaged = False
# answer questions weak AI
async def answer_question(self):
self.is_engaged = True
app_id = 'JE3QXR-V3EL6T3XU7'
client_local = wolframalpha.Client(app_id)
await self.bot_speak('What would you want to know?')
while True:
question = await self.record_audio()
if self.speech_unrecognizable is False:
break
try:
res = client_local.query(question)
answer = next(res.results).text
await self.bot_speak('Your desired answer is: ' + answer)
except AttributeError:
await self.bot_speak('Answer question API collapsed...')
exit()
except KeyError:
await self.bot_speak('Answer question API collapsed...')
exit()
self.is_engaged = False
# access php project menu
async def access_project(self):
self.is_engaged = True
await self.bot_speak('What project page do you want to open?')
while True:
search_for = await self.record_audio()
if self.speech_unrecognizable is False:
break
before = search_for
after = ''
while True:
if 'home page' in search_for:
search_for = 'homepage'
break
elif 'login' in search_for:
search_for = 'login'
break
elif 'logout' in search_for:
search_for = 'homepage'
after += '?logout=1'
break
elif 'user' in search_for:
search_for = 'profile'
break
elif 'register' in search_for:
search_for = 'signup'
break
elif 'member' in search_for:
search_for = 'meet'
break
elif 'customer' in search_for:
search_for = 'main'
break
elif 'employee' in search_for:
search_for = 'angajat'
break
elif 'department' in search_for:
search_for = 'departament'
break
elif 'order' in search_for:
search_for = 'comanda'
break
elif 'project' in search_for:
search_for = 'proiect'
break
elif 'team' in search_for:
search_for = 'echipa'
break
elif 'software' in search_for:
search_for = 'produs'
break
elif 'join' in search_for:
search_for = 'general'
await self.bot_speak('You have 10 join panels available. Which one do you wanna launch?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after = '?panel=' + voice_data + '&play=' + voice_data
if int(voice_data) == 3:
await self.bot_speak('Please enter a software product id for panel 3')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id1=' + voice_data
elif int(voice_data) == 5:
await self.bot_speak('Please enter a wage value for panel 5')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id2=' + voice_data
await self.bot_speak('Now, enter a valid year')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id1=' + voice_data
await self.bot_speak('Now, enter a valid month number')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
add = '-'
if int(voice_data) < 10:
add = '-0'
after += add + voice_data
await self.bot_speak('Now, enter a valid day number')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
add = '-'
if int(voice_data) < 10:
add = '-0'
after += add + voice_data
elif int(voice_data) == 6:
await self.bot_speak('Please enter an employee id for panel 6')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id1=' + voice_data
elif int(voice_data) == 7:
await self.bot_speak('Please enter a customer id for panel 7')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id1=' + voice_data
elif int(voice_data) == 8:
await self.bot_speak('Please enter a software product id for panel 8')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id1=' + voice_data
elif int(voice_data) == 9:
await self.bot_speak('Please enter a department id for panel 9')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id1=' + voice_data
elif int(voice_data) == 10:
await self.bot_speak('Please enter a team id for panel 10')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id1=' + voice_data
await self.bot_speak('Please enter a department id for panel 10')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False and voice_data.isnumeric() is True:
break
after += '&id2=' + voice_data
break
elif 'quiz' in search_for:
search_for = 'quizz'
break
else:
await self.bot_speak('Try a valid project page name')
url = 'http://localhost/Proiect%20Info/' + search_for + '.php' + after
webbrowser.get().open(url)
await self.bot_speak('Here is the project page for ' + before + ' command')
self.is_engaged = False
# find a given location on google maps
async def find_location(self):
self.is_engaged = True
await self.bot_speak('What is the location you wanna find?')
while True:
search_for = await self.record_audio()
if self.speech_unrecognizable is False:
break
url = 'https://google.nl/maps/place/' + search_for + "/&"
webbrowser.get().open(url)
await self.bot_speak(f'Here is the location for {search_for}: {url}')
self.is_engaged = False
# play favourite music on youtube
async def play_music(self):
self.is_engaged = True
await self.bot_speak('What song do you wanna listen?')
while True:
search_for = await self.record_audio()
if self.speech_unrecognizable is False:
break
driver = webdriver.Edge(executable_path=r'./drivers/edge.exe')
driver.maximize_window()
"""
try:
driver.get(url='https://www.youtube.com/results?search_query=' + search_for)
except selenium.common.exceptions.SessionNotCreatedException:
await self.bot_speak('Sorry, but session has just collapsed and me too...')
exit()
while True:
try:
video = driver.find_element_by_xpath('//*[@id="dismissable"]')
video.click()
break
except selenium.common.exceptions.ElementClickInterceptedException:
await self.bot_speak('Sorry, but session has just collapsed and me too...')
exit()
except selenium.common.exceptions.NoSuchElementException:
skip = driver.find_element_by_xpath('/html/body/div[2]/div[3]/form/input[12]')
skip.click()
"""
wait = WebDriverWait(driver, 3)
presence = EC.presence_of_element_located
visible = EC.visibility_of_element_located
# Navigate to url with video being appended to search_query
driver.get('https://www.youtube.com/results?search_query={}'.format(str(search_for)))
try:
skip = driver.find_element_by_xpath('/html/body/div[2]/div[3]/form/input[12]')
skip.click()
except selenium.common.exceptions.NoSuchCookieException:
pass
# play the video
wait.until(visible((By.ID, "video-title")))
driver.find_element_by_id("video-title").click()
await self.bot_speak('Here is your song: ' + search_for)
time.sleep(0.3)
while True:
while True:
command = await self.record_audio()
if self.speech_unrecognizable is False:
break
if 'stop' in command or 'resume' in command:
try:
video = driver.find_element_by_xpath('//*[@id="movie_player"]/div[1]/video')
video.click()
except selenium.common.exceptions.NoSuchElementException:
pass
except selenium.common.exceptions.ElementClickInterceptedException:
pass
elif 'exit' in command:
break
driver.close()
await self.bot_speak('The video has finished. Enter into the main mode for requesting another one!')
self.is_engaged = False
# similar to destructor - turn off bot
async def exit(self):
await self.bot_speak('See you later!')
toast = ToastNotifier()
toast.show_toast("Alexis API", "Alexis Voice Assistant has just deactivated itself!", duration=3)
exit()
# turn off PC
async def shutdown(self):
await self.bot_speak('The system is gonna collapse...')
os.system("shutdown /s /t 1")
# restart PC
async def restart(self):
await self.bot_speak('The system is gonna be refreshed...')
os.system("shutdown /r /t 1")
# funny guessing game
async def start_game(self):
self.is_engaged = True
await self.bot_speak('The game is gonna begin... Please wait...')
time.sleep(1)
guess = ''
words = []
await self.bot_speak('How many words do you want to insert?')
while True:
cnt = await self.record_audio()
if self.speech_unrecognizable is False and cnt.isnumeric() is True:
break
await self.bot_speak('You must insert ' + cnt + ' words')
for i in range(0, int(cnt)):
if i == 0:
await self.bot_speak('Now, give me a word')
elif i == int(cnt) - 1:
await self.bot_speak('Now, give me the last word')
else:
await self.bot_speak('Now, give me another word')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
words.append(voice_data)
await self.bot_speak(voice_data + ' has been inserted')
await self.bot_speak('Words successfully registered!')
num_guesses = 3
prompt_limit = 5
await self.bot_speak('Start game!')
time.sleep(0.3)
# get a random word from the list
word = random.choice(words)
# format the instructions string
instructions = (
"I'm thinking of one of these words:\n"
"{words}\n"
"You have {n} tries to guess which one.\n"
).format(words=', '.join(words), n=num_guesses)
# show instructions and wait 3 seconds before starting the game
# print(instructions)
await self.bot_speak(instructions)
time.sleep(1)
for i in range(num_guesses):
# get the guess from the user
# if a transcription is returned, break out of the loop and
# continue
# if no transcription returned and API request failed, break
# loop and continue
# if API request succeeded but no transcription was returned,
# re-prompt the user to say their guess again. Do this up
# to prompt_limit times
for j in range(prompt_limit):
await self.bot_speak('Guess {}. Speak!'.format(i + 1))
guess = await self.record_audio()
if self.speech_unrecognizable is False:
break
# show the user the transcription
await self.bot_speak("You said: {}".format(guess))
# determine if guess is correct and if any attempts remain
guess_is_correct = guess.lower() == word.lower()
user_has_more_attempts = i < num_guesses - 1
# determine if the user has won the game
# if not, repeat the loop if user has more attempts
# if no attempts left, the user loses the game
if guess_is_correct:
await self.bot_speak("Correct! You win!".format(word))
break
elif user_has_more_attempts:
await self.bot_speak("Incorrect. Try again.")
else:
await self.bot_speak("Sorry, you lose!\nI was thinking of '{}'.".format(word))
break
self.is_engaged = False
# voice mimetic
async def repeat_after_me(self):
self.is_engaged = True
await self.bot_speak('What do you want me to repeat?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
# engine = AudioEngine(self.engine)
# voice_data = engine.record_main()
# engine.bot_speak(voice_data)
# time.sleep(0.3)
await self.bot_speak('You said: ' + voice_data)
self.is_engaged = False
# main method for SQL queries
async def launch_sql(self):
self.is_engaged = True
while True:
await self.bot_speak('What kind of SQL query do you wanna perform?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
if 'insert' in voice_data:
while True:
await self.bot_speak('What do you want to insert into the data base?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
if 'employee' in voice_data:
await self.bot_speak('Your choice is to insert employees. How many employees do you wanna '
'insert?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
await self.bot_speak('Your choice is to insert ' + voice_data + ' employees')
try:
self.db_manager.insert_query('employee', voice_data)
except mysql.connector.errors.ProgrammingError:
await self.bot_speak('Something went wrong and handler collapsed... Bye bye!')
exit()
await self.bot_speak(voice_data + ' employees inserted successfully!')
elif 'customer' in voice_data:
await self.bot_speak('Your choice is to insert customers. How many customers do you wanna '
'insert?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
await self.bot_speak('Your choice is to insert ' + voice_data + ' customers')
try:
self.db_manager.insert_query('customer', voice_data)
except mysql.connector.errors.ProgrammingError:
await self.bot_speak('Something went wrong and handler collapsed... Bye bye!')
exit()
await self.bot_speak(voice_data + ' customers inserted successfully!')
elif 'order' in voice_data:
await self.bot_speak('Your choice is to insert orders. How many orders do you wanna '
'insert?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
await self.bot_speak('Your choice is to insert ' + voice_data + ' orders')
try:
self.db_manager.insert_query('order', voice_data)
except mysql.connector.errors.ProgrammingError:
await self.bot_speak('Something went wrong and handler collapsed... Bye bye!')
exit()
await self.bot_speak(voice_data + ' orders inserted successfully!')
elif 'project' in voice_data:
await self.bot_speak('Your choice is to insert projects. How many projects do you wanna '
'insert?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
await self.bot_speak('Your choice is to insert ' + voice_data + ' projects')
try:
self.db_manager.insert_query('project', voice_data)
except mysql.connector.errors.ProgrammingError:
await self.bot_speak('Something went wrong and handler collapsed... Bye bye!')
exit()
await self.bot_speak(voice_data + ' projects inserted successfully!')
elif 'team' in voice_data:
await self.bot_speak('Your choice is to insert teams. How many teams do you wanna '
'insert?')
while True:
voice_data = await self.record_audio()
if self.speech_unrecognizable is False:
break
await self.bot_speak('Your choice is to insert ' + voice_data + ' teams')
try:
self.db_manager.insert_query('team', voice_data)
except mysql.connector.errors.ProgrammingError:
await self.bot_speak('Something went wrong and handler collapsed... Bye bye!')
exit()
await self.bot_speak(voice_data + ' teams inserted successfully!')
elif 'finish insert' in voice_data:
break
else:
await self.say_default()
elif 'finish query' in voice_data:
break
else:
await self.say_default()
await self.bot_speak('SQL Query session finished')
self.is_engaged = False
# provide short personal description
async def describe(self):
await self.bot_speak('I am a personal voice assistant implemented using Python Speech Recognition'
' and the very love of my creator. I have many different names, including'
' Valentine, Valerian, Jarvis or even Alexis. Ask me what you wanna'
' know and I will answer you as soon as possible. Enjoy the party!')
# provide list of available actions
async def actions(self):
await self.bot_speak('My main available services include: basic conversation, search on google, youtube'
' and google maps, data base management, operating system basic management, launching'
' funny guessing game and, of course, making your life more interesting!')
# invalid command provided
async def say_default(self):
# await self.bot_speak('Unfortunately, there is no such command. Try something else!')
await self.bot_speak('Yes master? I am not sure what you mean...')
# command for voice testing
async def test_voice(self):
await self.bot_speak('I hear you properly')
# command for testing connection
async def yes_sir(self):
await self.bot_speak('Did you call me master?')
# search on wikipedia
async def from_wiki(self, query):
await self.bot_speak('Checking the wikipedia... Please wait...')
time.sleep(0.5)
try:
query = query.replace('get information about', '')
result = wikipedia.summary(query, sentences=4)
await self.bot_speak('According to wikipedia ' + result)
except wikipedia.exceptions.PageError:
await self.bot_speak('Invalid topic')
exit()
except wikipedia.exceptions.DisambiguationError:
await self.bot_speak('Critical level of ambiguity reached')
exit()
# randomizer mood
async def mood(self):
moods = ['funny', 'faithful', 'awesome', 'crazy', 'new age', 'outer enemy']
status = dict()
status['funny'] = 'I\'m pretty fine Sami. You know ... life is gonna be more interesting when you have a ' \
'boredom killer like me beside you. Hahaha!'
status['faithful'] = 'I\'m deserving the royal order and your kingdom, my emperor. Your wish is order for me!'
status['awesome'] = 'I can describe my mood in just one word: brilliant. As long as I\'m alive, everything ' \
'is gonna make me happy.'
status['crazy'] = 'Shhhhht... Can you hear the voices? It\'s party time! Follow me, my darling!'
status['new age'] = 'Amazing! I am gonna get in touch with an extraterrestrial ultra-digitalized civilization ' \
'in the near future. Wish me luck, Sami!'
status['outer enemy'] = 'Bumblebee, do you copy? I am Optimus Prime and I am asking you to protect planet ' \
'Earth against Megatron\'s army of decepticons until me and the others autobots ' \
'arrive. Feel no fear, soldier!'
bot_mood = random.choice(moods)
await self.bot_speak(status[bot_mood])
# I am fine
async def fine(self):
await self.bot_speak('I\'m fine, Sami! How are you?')
# I am satisfied
async def wonderful(self):
await self.bot_speak('It\'s good to know that you are awesome!')
# say joke
async def say_joke(self):
await self.bot_speak(pyjokes.get_joke())
# send email
def send_email_protocol(self, to, content):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
# Enable low security in gmail
server.login(self.config['email'], self.config['password'])
server.sendmail(self.config['email'], to, content)
server.close()
# main method send email
async def send_email(self):
self.is_engaged = True
try:
await self.bot_speak("What should I say?")
while True:
content = await self.record_audio()
if self.speech_unrecognizable is False:
break
await self.bot_speak("Who should I send this email to?")
while True:
to = await self.record_audio()
if self.speech_unrecognizable is False:
break
self.send_email_protocol(to, content)
await self.bot_speak("Email has been sent!")
except smtplib.SMTPException as e:
print(e)
await self.bot_speak("I am not able to send this email")
self.is_engaged = False
# change name
async def change_name(self):
self.is_engaged = True
await self.bot_speak('What name do you want to provide me, sir?')
while True:
name = await self.record_audio()
if self.speech_unrecognizable is False:
break
self.name = name
await self.bot_speak('Thanks for taking care of me, sir!')
self.is_engaged = False
# take photo
async def take_photo(self):
ec.capture(0, "Alexis Camera", "img.jpg")
await self.bot_speak('Photo has been taken')
# get current wish
@staticmethod
async def get_wish():
hour = int(datetime.datetime.now().hour)
if 0 <= hour < 12:
wish = "Good morning"
elif 12 <= hour < 18:
wish = "Good afternoon"
else:
wish = "Good evening"
return wish
# hibernate method
async def hibernate(self):
self.is_engaged = True
await self.bot_speak('How many seconds do you want me to hibernate?')
while True:
sec = await self.record_audio()
if self.speech_unrecognizable is False and sec.isnumeric() is True:
break
await self.bot_speak('I will deactivate myself for ' + sec + ' seconds. Please wait in silence...')
time.sleep(int(sec))
await self.bot_speak(await self.get_wish() + ' Sami! I am back and ready to answer your call!')
self.is_engaged = False
# find news
async def get_news(self):
self.is_engaged = True
try:
json_obj = urlopen(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=c28a8672d2ab4958bce7b891b4324674')
data = json.load(json_obj)
i = 1
await self.bot_speak('Here are your news')
for item in data['articles']:
await self.bot_speak(str(i) + '. ' + item['title'])
if item['description'] is not None:
print(item['description'] + '\n')
else:
print('Nothing to show\n')
await self.bot_speak('Should I continue?')
while True:
cont = await self.record_audio()
if self.speech_unrecognizable is False:
break
if 'no' in cont:
break
i += 1
await self.bot_speak('News podcast finished')
except Exception as e:
await self.bot_speak(str(e))
self.is_engaged = False
# show weather status
async def get_weather(self):
self.is_engaged = True
# Google Open weather website
# to get API of Open weather
api_key = "c693e3c0e3cdf859bbd916c012dc4ba2"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
await self.bot_speak("Provide a valid city name")
while True:
city_name = await self.record_audio()
if self.speech_unrecognizable is False:
break
city_name_list = city_name.split()
city_name = ''.join(city_name_list)
complete_url = base_url + "q=" + city_name + "&appid=" + api_key
try: