-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
732 lines (619 loc) · 23.6 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
# builtins
import json
import os
import sys
import subprocess
import threading
import difflib
import multiprocessing
# outcasts
import bs4
import duckduckpy as doge # for ze MayMays B)
import pyttsx3
import requests
import speech_recognition as Recognizer
import urbandictionary as ud
from youtubesearchpython import SearchVideos
import pychromecast
from pychromecast.controllers.youtube import YouTubeController
# in house
import datestuff as dateSig
import dictionaryAPI as dictAPI
from winApps import winapps
import chromecastchecker as ccc
from lowerUtils import lowerUtils as lU
from newsApi import news as newsApi
from music import youtubeAudio
import fileSearch
from speechMath import speechMath as mathForSpeech
# One Class to rule em all
# One Class to find them
# One Class to bring them all
# in the darkness and bind them
class voiceCommands:
class speechMath:
def __init__(self, arg, fullcmd):
mathObj = mathForSpeech(arg)
utilities.SpeakText(mathObj.getAnswer())
class searchFile:
def __init__(self, arg, fullcmd):
utilities.SpeakText('Opening file search dialog')
proc = multiprocessing.Process(target=fileSearch.guiMethods.fileSearch)
proc.start()
# cless for ze myusike
class music:
def __init__(self, song, fullcmd):
utilities.SpeakText("hold tight while I get you your spicy music")
self.vidUrl = self.searchVid(song)
print(self.vidUrl)
aud = youtubeAudio(self.vidUrl)
def searchVid(self, keyword):
results = SearchVideos(keyword, offset = 1, mode = "dict", max_results = 1)
url = results.result()['search_result'][0]['link']
return url
# stop the voice assistant from saying anything more
class stopVoice:
def __init__(self, date, fullcmd):
print('reaching to ze end')
youtubeAudio.killAll()
engine.stop()
# engine.start()
# gets you info about the date
class sup:
def __init__(self, date, fullcmd):
utilities.SpeakText(f'I am doing excellent! thanks for asking. {dateSig.dateSignificance.dateHolidays()}')
# gives historical sig of the day
class onThisDay:
def __init__(self, dateToday, fullcmd):
utilities.SpeakText(dateSig.dateSignificance.getImportantEventToday())
# get all the news
class news:
def __init__(self, arg, fullcmd):
print('here')
print(newsApi.getNews())
utilities.SpeakText(newsApi.getNews())
# this class deals with launching windows apps
# that are installed onto thy systeme
class win:
class launchThread:
def __init__(self, app):
try:
self.thread = threading.Thread(target=winapps.launch, args=(app, ))
self.thread.daemon = True
self.thread.start()
except Exception:
utilities.SpeakText(f"Oops I ran into an issue, I am unable to launch {app} at the moment")
def __init__(self, app, fullcmd):
utilities.SpeakText(f"Opening {app}")
voiceCommands.win.launchThread(winapps.searchForApp(app))
# this class is for the sole purpose of todos
# probably the largest subclass yet * G U L P S *
class toDo:
# initialise a todos object and process
# the voice command that voice provided
# by it's masters
def __init__(self, task, fullcmd):
print(f"todo {task}")
self.task = task
self.fullcmd = fullcmd
self.processTodo()
# scan the todos.json file and see that
# what on earth are the person's to dos
@staticmethod
def listToDos(lst = ''):
print("listing")
try:
with open("todos.json", 'a+') as jsonFile:
jsonFile.seek(0)
if json.load(jsonFile)['todos'] != []:
utilities.SpeakText("you have the to dos. ")
for todo in json.load(jsonFile)['todos']:
utilities.SpeakText(todo)
else:
utilities.SpeakText("it seems that you don't have anything to do! enjoy your day!")
except json.decoder.JSONDecodeError:
utilities.SpeakText("it seems that you don't have anything to do! enjoy your day!")
# listen to the to dos on voice
# and then add the to dos to the
# todos.json file and if it doesn't
# exist then heck create one smh
@staticmethod
def addToDos(task):
try:
with open('todos.json', 'r') as jsonFile:
out = {}
todos = json.load(jsonFile)["todos"]
todos.append(task.strip())
out["todos"] = todos
os.remove("todos.json")
utilities.writeToJson(out, "todos.json")
except Exception as e:
print(e)
try:
os.remove("todos.json")
except Exception:
pass
todos = {"todos" : []}
todos["todos"].append(task.strip())
utilities.writeToJson(todos, "todos.json")
finally:
utilities.SpeakText(f"Added the to do, {task}")
# remove the lonely todo that has been used
# poor lil to do was emotionally tortured :(
@staticmethod
def remove(task):
with open("todos.json", 'r') as jsonFile:
data = json.load(jsonFile)
try:
data["todos"].pop(data["todos"].index(task.strip()))
os.remove("todos.json")
utilities.writeToJson(data, 'todos.json')
utilities.SpeakText(f"Removed to do, {task}")
except Exception as e:
print(e)
utilities.SpeakText("I can't seem to find that task")
# perform a mass genocide of todos OwO
@staticmethod
def removeAll(lst):
try:
os.remove("todos.json")
except FileNotFoundError:
utilities.SpeakText("You don't seem to have any thing to do ")
finally:
utilities.SpeakText("Removed all todos")
# the dreaded SCUFFED NLP UwU
def processTodo(self):
todoCommands = {
"list": [
'what are my to dos',
'what are the things to do',
'show my to dos',
'list my to dos',
'things to do',
{
'command': voiceCommands.toDo.listToDos
}
],
"add": [
'add to my to dos',
'add to do',
'at to do',
{
'command': voiceCommands.toDo.addToDos
}
],
"done": [
'mark as done',
'remove to do',
'done to do ',
{
'command': voiceCommands.toDo.remove
}
],
"removeAll": [
'remove all',
'remove all to dos',
'remove all to do',
'mark all to do as done',
'done all to dos',
'remove all to do',
'remove all two doors',
'done all to do',
'dun all to dos',
'done all',
'dun all',
'remove all tuduz',
'remove all todos',
{
'command': voiceCommands.toDo.removeAll
}
]
}
for command in todoCommands:
try:
for cmd in todoCommands[command]:
if cmd in self.fullcmd:
try:
task = utilities.greaterOf(self.task.split('cmd')[0], self.task.split('cmd')[1])
todoCommands[command][-1]['command'](task)
except IndexError:
task = self.task.split('cmd')[0]
todoCommands[command][-1]['command'](task)
except TypeError:
pass
class dictionary:
# use the scalper thing I made in the dictionaryAPI.py
# and use its function to get the meaning of the word
# requested by it's masters ^ \\\ ^
def __init__(self, word, fullcmd):
print(f'searching for the meaning of {word}')
self.word = word
self.meaning = dictAPI.getMeaning(word)
if self.meaning:
utilities.SpeakText(f'the meaning of {self.word} is, {self.meaning}')
else:
utilities.SpeakText("hmmmmmmmmmm, I don't know that word")
class youtubeSearch:
# search ze zutube for content
# then play the content B)
def __init__(self, keyword, fullcmd):
self.keyword = keyword
try:
results = SearchVideos(keyword, offset = 1, mode = "dict", max_results = 1)
url = results.result()['search_result'][0]['link']
if sys.platform=='win32':
os.startfile(url)
elif sys.platform=='darwin':
subprocess.Popen(['open', url])
else:
try:
subprocess.Popen(['xdg-open', url])
except OSError:
utilities.SpeakText("You ran into browser issue")
except Exception as e:
print(e)
class searchWeb:
# use the doge, sorry duckduckpy API to
# get the top result and speak that
def __init__(self, keyword, fullcmd):
self.keyword = keyword
print(keyword, fullcmd)
print(f"searching for {keyword}")
if 'search the' not in keyword:
try:
response = doge.query(keyword)
utilities.SpeakText(f'top result on internet says that, {response.related_topics[0].text}')
return
except IndexError:
utilities.SpeakText("I can't seem to find any result for that")
return
class googleCast:
def __init__(self, device, fullcmd):
print('Reached atleast here....')
self.connection = False
self.processCmd(fullcmd)
def connect(self):
try:
self.chromecasts, browser = pychromecast.get_listed_chromecasts(friendly_names=[self.device])
print('reached here')
utilities.SpeakText('Connection succeeded!')
self.connection = True
except Exception as e:
utilities.SpeakText(f'{e}')
def concheck(self):
while True:
if self.chromecasts:
continue
else:
utilities.SpeakText('Connection Broke!')
self.connection = False
return
def processCmd(self, fullcmd):
cmd = fullcmd.split('cast')
cmdlets = ['to my device', 'on the device', 'on device', 'to device']
print('reached to processing')
for cmdlet in cmdlets:
print(cmdlet, cmd)
cmd = sorted(cmd)[-1]
if cmdlet in cmd:
deviceName = cmd.split(cmdlet)[1]
self.cccComparator(deviceName)
url = self.searchVid(cmd.split(cmdlet)[0])
if self.connection == False:
self.connect()
vidId = url.split("?v=")[-1].split("&")[0]
self.playContent(vidId)
def playContent(self, videoID):
print("video shud play but won't :(")
cast = self.chromecasts[0]
cast.wait()
yt = YouTubeController()
cast.register_handler(yt)
yt.play_video(videoID)
def searchVid(self, keyword):
results = SearchVideos(keyword, offset = 1, mode = "dict", max_results = 1)
url = results.result()['search_result'][0]['link']
return url
def cccComparator(self, device):
with open('temp/chromecast.txt', 'r+') as f:
shit = f.readlines()
newshit=[]
for element in shit:
newelement = element[0:-1]
newshit.append(newelement)
f.close()
print(newshit)
self.device = (lU.fuzzyCompare(device, newshit))
class urban:
# urban dictionary OwO
def __init__(self, word, fullcmd):
print(f"searching for {word}")
self.word = word
# try:
self.meaning = ud.define(word)[0].definition
utilities.SpeakText(f"according to urban dictionary, {word} means {self.meaning}")
# except Exception as e:
# print(e)
# utilities.SpeakText(f"oof, stupid urban dictionary doesn't even know the meaning of {word}.")
# Scuffed Natural Language Processing
# this class is gonna be * H E C T I C *
class naturalLanguage:
# so basically ughh I would
# initialize some shit here and
# then we would convert it to command
# please end this fast ;_;
# a dictionary of commands to figure out
# that the hell is the thing that the voice
# assistant is asked to bloody do
commands = {
'dictionary' : [
'what is the meaning of ',
'meaning of ',
'what is the definition of',
'what is ',
'define ',
{
'command': voiceCommands.dictionary
}
],
'web': [
'search the web for',
'search the web',
'search on the internet',
'search internet',
'search the internet for',
'search internet for',
{
'command': voiceCommands.searchWeb
}
],
'urban': [
'urban dictionary',
{
'command': voiceCommands.urban
}
],
'toDo': [
'to do',
'to dos',
'todo',
'todos',
{
'command': voiceCommands.toDo
}
],
'youtube':[
'search youtube for',
'search on youtube for',
'search youtube',
'search yt',
{
'command': voiceCommands.youtubeSearch
}
],
'connect': [
'connect to',
'cast',
'cast to',
{
'command': voiceCommands.googleCast
}
],
'win': [
'open the app',
'launch ',
'open ',
'run ',
{
'command': voiceCommands.win
}
],
'news': [
'get news',
'latest news',
'news flash',
'what is happing',
'get headlines',
{
'command': voiceCommands.news
}
],
'dateSig': [
'on this day',
{
'command': voiceCommands.onThisDay
}
],
'sup': [
'how are you',
'sup',
'wassup',
'what\'s up',
'what is up',
{
"command": voiceCommands.sup
}
],
'stop': [
'cut it out',
'stop',
'shut up',
{
"command": voiceCommands.stopVoice
}
],
'music': [
'play song',
'play the song',
'play the track',
'play the music',
'play music',
'play track',
{
'command': voiceCommands.music
}
],
'fileSearch': [
'file search',
'document search',
{
'command': voiceCommands.searchFile
}
],
'math': [
'math',
{
'command': voiceCommands.speechMath
}
]
}
def __init__(self, command, trigger):
self.command = command
for command in list(self.__class__.commands.keys()):
try:
for cmd in self.__class__.commands[command]:
if cmd in self.command:
try:
self.command = self.command.split(trigger, 1)[1]
argument = utilities.greaterOf(self.command.split(cmd, 1)[0], self.command.split(cmd, 1)[1])
except IndexError:
argument = self.command.split(command, 1)[0]
finally:
self.__class__.commands[command][-1]['command'](argument, self.command)
except TypeError:
pass
# class related to utilites.
# primarily contains static methods
class utilities:
@staticmethod
def startSlaves():
chromecastchecker = threading.Thread(target=ccc.check, args=())
chromecastchecker.daemon = True
chromecastchecker.start()
# this static method is for checking
# which of the two arguments is greater
@staticmethod
def greaterOf(arg1, arg2, category="str"):
if category == "str":
if len(arg1) > len(arg2):
return arg1
else:
return arg2
elif category == "int":
if arg1 > arg2:
return arg1
else:
return arg2
# speak text that has been passed :)
@classmethod
def SpeakText(cls, command):
engine.say(command)
engine.runAndWait()
# write stuff to json, what else did you think this would do LMAO
@staticmethod
def writeToJson(data, file = "settings.json"):
with open(file, 'a+') as f:
json.dump(data, f)
# reset settings
@staticmethod
def runConfigurator():
try:
os.remove("settings.json")
except Exception:
pass
settings = {}
triggerWord = input("what would you like your personal assistant to be called ?\n--> ")
settings['trigger'] = triggerWord
print("\n==============================================================\n")
for index, name in enumerate(Recognizer.Microphone.list_microphone_names()):
print(f" [ devide id : {index} ] {name} ")
print("\n==============================================================\n")
device_id = input("enter device id of the microphone you would like to use\n--> ")
settings["micID"] = device_id
print("\n==============================================================\n")
gender = input('What gender would you like your assistant to sound like?\n[ m ] Male\n[ f ] Female\n\n--> ')
print("\n==============================================================\n")
engine = input('What voice recognition engine would you like to use?\nPlease note that while CMU Sphinx is known to not log your data it is very unreliable. Google API is considerably better but well we all know how google is when it comes to privacy ¯\_(ツ)_/¯\n[ 0 ] Google\n[ 1 ] PocketSphinx\n\n--> ')
settings["engine"] = engine
settings["gender"] = gender
utilities.writeToJson(settings)
if __name__ == "__main__":
# so here we start the shitty recognizer
# code totally not stolen from GeeksForGeeks
# :sweatsmile:
recognizer = Recognizer.Recognizer()
engine = pyttsx3.init()
engine.setProperty('rate', 140)
def main():
utilities.startSlaves()
# read the config which has already been defined
# and use bloody use that LOL
try:
with open('settings.json', 'r') as settingsFile:
settings = json.load(settingsFile)
triggerWord = settings["trigger"]
micId = int(settings["micID"])
voiceEngine = int(settings["engine"])
voiceGender = settings['gender']
except KeyError or json.decoder.JSONDecodeError:
print("your local configuration appears to have been corrupted")
print("Press [y] to continue with resseting your voice assistant or [n] to cancel")
inp = input("--> ")
if inp.lower().strip() == "y":
utilities.runConfigurator()
main()
elif inp.lower().strip() == "n":
sys.exit()
else:
print("ALERT : invalid input\n")
main()
# setting voice gender
voices = engine.getProperty('voices')
if voiceGender == "m":
engine.setProperty('voice', voices[0].id)
elif voiceGender == "f":
engine.setProperty('voice', voices[1].id)
while True:
try:
# { mic ---> sphinx ---> text } ==> STONKS
# ^ /// ^
with Recognizer.Microphone(device_index=micId) as source:
recognizer.adjust_for_ambient_noise(source, duration=0.1)
audio = recognizer.listen(source)
if voiceEngine == 0:
MyText = recognizer.recognize_google(audio)
MyText = MyText.lower()
elif voiceEngine ==1:
MyText = recognizer.recognize_sphinx(audio)
MyText = MyText.lower()
else:
utilities.runConfigurator()
print(MyText)
if triggerWord in MyText:
naturalLanguage(MyText, triggerWord)
# ignore errors like a good programmer LMAO
# it's all in ze mind
except Recognizer.RequestError:
pass
# ignore errors like a good programmer LMAO
# it's all in ze mind
except Recognizer.UnknownValueError:
pass
if "settings.json" in os.listdir():
try:
main()
except Exception:
print("your local configuration appears to have been corrupted")
print("Press [y] to continue with resseting your voice assistant or [n] to cancel")
inp = input("--> ")
if inp.lower().strip() == "y":
utilities.runConfigurator()
main()
elif inp.lower().strip() == "n":
sys.exit()
else:
print("ALERT : invalid input\n")
main()
else:
utilities.runConfigurator()
main()