-
Notifications
You must be signed in to change notification settings - Fork 5
/
__PYSHA.py
2123 lines (1923 loc) · 121 KB
/
__PYSHA.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
try:
import psutil # This imports the process utilities , for the checking of the specific application running an closing
import datetime # Importing the datetime for the timing modules since the date time is used to answer the questions
import wave # Importing the wave of for the recording(This is the format for the recording which is used .wav
from random import * # Using the random function for the creation
import pyaudio # importing the header file of the pyaudio
import speech_recognition as sr # Importing the speech recognition file for the code.!!
import random # importing the random module for the random Short term memory
import datetime as dt # date time module for the implementation of the date and the time
from urllib.request import urlopen # If there is a webpage to be downloaded
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
# For creating the resource manager and processor for the pdf
from pdfminer.converter import TextConverter # For the conversion of the Text in the pdf
from pdfminer.layout import LAParams # Taking the Linear layout in mind
# import BytesIO
from io import StringIO # String IO for conversion to string representation
from io import open # opening the file
from zipfile import ZipFile # Zip file will be used to zip word into xml
from io import BytesIO # for the conversion of the word files will be used later
import os # the module will be used to find in the correct directory and files extensions check
import docx # importing the docs module as per advised
import ntpath # for extracting filename from full path
# import pyscreenshot # for taking screenshots of the Desktop on Current command
# from .PygletMusic.Pyglet implementation import * # Music player GUI implemented
except Exception as E:
print("Missing header file which needed to be installed", E)
exit(0)
try:
from _Joke import * # For the Jokes, Cracked from the web (web scrapping Module)
from _NaturalLanguageProcessing import * # This is the Natural language processing
from _WolFrameAlphaClass import * # For computation and intelligence engine.
from __soundcloud import * # Soundcloud is for the File
# from __linksearch import * # importing for the link search
from __speakcode import * # For speaking the code from the web scrapping .
from _dbdata import * # Database function for the request and all others.
from _stackoverflow import * # Stackoverflow code implementation of the current file.
from _twitter import * # imports the twitter Pysha client which has been.
from _youtube import * # imports youtube created local header file , for searching on youtube
from __github import * # Github Repository , For accessing the Github
from _SocialMedia import * # importing the social media moduel for the implementation of the social medias
from _TextMode import * # the text mode will be used for the messaging application like look, like a bot
from AssistantProperties import _chooseassitant # importing the properties of the assistant being choosen.
from __shorttermmemory import * # Short term memory
from Chatdependencies._chat import * # importing the _chat module
# from SentimentalAnalysis.Basic_sentimentanalysis import * # imports to download tweets
from __newsupdates import * # imports the news class for the news updates.
from SentimentalAnalysis.downloadTweets import * # imports for performing the sentimetn analysis
from __facebook import * # importing the facebook module for GraphAPI.
from MouseMovments import mm # Importing the mouse movement file, to control Mouse and keyboard
from load_inall import * # script for playing the loading in All mp4 files
from __imagescheck import * # this is for the checking of the images
from sportslive import watch_live_sports_stream # This imports the funtion of the watching live streams
except Exception as E: # Taking the Exception as E
print("Missing the Built in PYSHA files for the Development", E)
exit(0) # Exiting the Application
# imports the short term memory code --> for getting the last strings backs 7 +-2
# this si the importing of the header files !
# Pre requirements : You need to Install Microsoft SDK fo Speech and all the available Tools
# Keep in mind that This is Under Heavy Construction and will be used in the later increments and
# TODO : YOU NEED TO ADD IN THE ARTIFICIAL FAST INTELLGIENCE AND THE FAST PROCESSING. !
'''
// This build is heavily under progress by , If you want to check all the dependencies,
and want to contribute to improve the particular algorithm, check Repository.
https://github.com/shafaypro/PYSHA1.0
Info Dated: 2/3/2016 , WaterFall method is being Followed
User Guideline:
Wherever you run this Project, the basic dependencies are converted in to the local machine,
--> The machine tells about her self and then wait for the user to have the specified an speech input,
The device of the microphone is connected and then it is parsed to the pyaudio where the input is then
Converted to the Audio file Formatted as WAV, under the F.L.A.C encoding, then it is parsed to the google api,
since the api is then accessed and the chunks of the audio is converted into the string and then returned into the
string.
There are some already stored procedures for the particular messages , like if a message starts from the :::
what is the ----> Time, Date and others can tell you the the time ,date and others.
Ther are some other features also added in the header file , like haviing a random chat and working on different kind of
Loops
you can ask for the questions and the Answers regarding to the Natural language processing module .
If you want to ask for the Application running modules then
for that :
RUN or OPEN _________ the Underscore should be replaced by the application name
--> This script will also be monitroing the computer (Here it contains the data analysis and the data visualization part
This will be including the statistical analysis and well as the sentimental analysis . ! so that this may be used in the
later
sequences of the version
--> ask for any operation ,, if other than all of the above , it will
--> You can ask the Mathematical operation as : 2+ 3 or integeration of 4 or General Knowledge.
--> Since It can also be asked the general knowledge questions like : who was the 6th president of Unitedstates
!!!!!!!!!!!!!!!!!!!!!!!EXAMPLE QUESTIONS !!!!!!!!!!!!!!!!!!!!!!!!
Who won the Election of 2016 in United states ?
Who wrote the book The lord of the Flies ?
What is the meaning of life ?
What is the meaning of Nostalgia?
bread <-- This will return the Other Requirements
--------------------------Example Programming Solution-----------------------
ask --> Stack over flow search _____________
______ replace this with your query
ask--> search youtube ____________ or youtube _________________
search youtube ___________________
______ replace this with your query
or youtube ___________________
ask--> search music _____________ or find music _______________
_________ replace this with your song name of artist or any :p
ask--> Read it out to me or Read it out for me
# This will read all the text from the last visited page
ask --> switch to _______ : replace the _________ with Female , male , dave , hazel , zira
ask --> tweet __________________ : posts a tweet on twitter.
ask --> search music ________________ : searched the music.
ask --> find music _______________ : finds the music from the internet.
ask --> search for ________________ : searches on google
ask --> launch ___________________ or RUN ______________ : runs the define application.
ask --> read it out for me : reads the last visited page
ask --> Search for _________: This opens up the browser for the result so that the Virtual assistant is able to read
from the
data
ask --> find me a wallpaper __________ or Find a wallpaper _____________ : replace ______ with your query
ask --> Mouse Move _________ : replace ___- with up , down, left , right , click , scroll # Controls the Mouse Movements
--ask --> Stop chrome or other applications : Stops the processes of the application
ask --> Stop,stop listening,quit : This will results in the Quiting , exiting for the virtual assistant!!
ask --> search ________ on Wikipedia : will search on wikipedia based on certain meaningful words(replaces at _____)
ask --> show me a comic : finds a comic from the internet and displayed the comic
ask --> tell me a joke : Finds a joke from the web and shows the joke
-ask --> what is the date / what is the time
-
-
-ask --> What is the integeration of 2 x squared + 3 x + 7
-
-
-ask --> which is greater in quantity 1 liter of water or 1 liter of milk
-
-
-ask --> Stack over flow search _____________
-
-
-______ replace this with your query
-
-ask--> search youtube ____________ or youtube _________________
-
-
-ask--> searh youtube playlist _________ : ___ is the query of yours
-
-search youtube ___________________: -______ replace this with your query
-
-or youtube ___________________
-
-ask--> search music _____________ or find music _______________ : replace ___ with your song name or artist or both
-ask--> Read it out to me or Read it out for me
-# This will read all the text from the last visited page
-ask --> switch to _______ : replace the _________ with Female , male , dave , hazel , zira
-ask --> tweet __________________ : posts a tweet on twitter.
-
-ask --> search music ________________ : searched the music.
-
-ask --> find music _______________ : finds the music from the internet.
-
ask --> play music : plays the music
-
-
ask --> Music Please : plays the music
-
-
ask --> music video please : plays a music video
-
-
-ask --> search for ________________ : searches on google
-
-
-ask --> launch ___________________ or RUN ______________ : runs the define application.
-
-
-ask --> read it out for me : reads the last visited page
-
-
-ask --> Search for _________: This opens up the browser for the result so that the Virtual assistant is able to read from the
-data
-
-
-ask --> Stop,stop listening,quit : This will results in the Quiting , exiting for the virtual assistant!!
-
-
-ask --> search ________ on Wikipedia : will search on wikipedia based on certain meaningful words(replaces at _____)
-
-
-ask --> show me a comic : finds a comic from the internet and displayed the comic
-
-
-ask --> tell me a joke : Finds a joke from the web and shows the joke
--
-ask --> tokenize sentence ____________________________ : will returned a tokenized sentence
-ask --> tokenize sentence ____________________________ : will returned a tokenized sen
-
-
-ask --> What did i just said : returns the last query from the short term memory(termed as the top runned query --> the last most)
-
-ask --> What did i said you: Returns maximum from the shrot term memory(last 7+-2 statments ) as per human brain.
-
-ask --> ______________________- Ask anything other than the above text the responce wil be returned based on the machine larning algorithums and then the responce data will be returned.!
-ask --> Stop __________ : replace ____ with any application name such as Calculator , windows media player and others
-ask --> Write to a file : after that you can keep saying any thing, and it will write to the specified file
unless you say exit only.
'''
# TODO : Working on EMAILS, MESSENGERS, OPEN CV, IMAGE RECOGNITION, NATURAL LANGUAGE PROCESSING, MACHINE LEARNING, DB
# TODO : SELF LEARNING, additonal Chat properties
''' Keep in mind to have all the back up things,
For the personal computer you need to have the computer access,
And all the other things given to the Assistant so that it can work in there.
'''
# TODO : USE THE Natural Language processing TOO, To improve the Virtual Assistant
__author__ = "M Shafay Amjad"
__QA__ = "[email protected]"
__copyrights__ = "© to , No changes should be made prior to his permission"
__supervisor__ = ""
__version__ = 1.0
__productname__ = "PYSHA"
__university__ = "Government College University Lahore"
# TODO : File Information needs to be implemented
# The reverse shell process is for personal use, where we will be using to ping the Updated Code, to your Home location
# Computer Code!
'''
Below Function is responsible for the writing of the file , Since if you want to write VIA through Text strings
you can use that through the Writing_to_file Function, the text is based on speech to text and Exits when you say
":EXIT" <-- it stops writing to the file and goes to General Mode.
'''
# Writing to the file , while speaking class (Writing_to_file )
# TODO : Make it more effient .!
class Writing_to_file:
def __init__(self):
total_saying = ""
while True:
temp = self.write_by_speak()
if (temp != "exit" or not temp.__contains__("exit")) and temp is not None:
total_saying += temp
print(temp)
elif temp is None:
continue # Debugging
elif temp == "exit" or temp.__contains__("exit"): # This is the Exiting condition
break # Goes outside the loop
print(total_saying)
self.write_in_file(total_saying)
print("------------")
def write_in_file(self, text):
current_directory = os.path.dirname(os.path.realpath(__file__)) # Getting the current directory from the file
print("Writing to a file")
specified_file = current_directory + "OnSpeakType\\datain.txt" # Creating the specified file
file_writer = open(specified_file, "w+") # Opening the specified file
file_writer.write(text)
print("Writte to the file data .txt ! ")
file_writer.write(" ")
file_writer.close()
def write_by_speak(self):
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source, duration=1) # Adjustment of the microphone on the basis of the required
# Envirenoment adjustment of the specified microphone
# print(r.energy_threshold)
# print("Chucking rate: ", source.CHUNK)
# print("format rate :", source.format) # Debuggin purpose
# CHUNK = 1024
# FORMAT = pyaudio.paInt16 # the Format is picked up from the pyaudio
# CHANNELS = 2 # The Cross Channels
# # RATE = 44100
# source.CHUNK = CHUNK
# source.format = FORMAT # FORMATING THE SOURCE FILE
# print(dir(source))
print("Say something!...")
# print(r.energy_threshold)
r.energy_threshold += 280
# # print(r.adjust_for_ambient_noise(source,duration=1))
audio = r.listen(source)
# Speech recognition using Google Speech Recognition
try:
print("Parsing ...") # Debugging To
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
# print(r.energy_threshold )
# print(help(r.recognize_google))
# text = r.recognize_google(audio, language='en-US')
text = r.recognize_google(audio, language='en-GB') # Recognizing the command through the google
# r.re
# r.re
print("You said: " + text) # printing the text of the input
return text
except sr.UnknownValueError: # Knowing the exception
print("Google Speech Recognition could not understand audio")
return
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return
except sr.HTTPError as e: # In Case of Server down or server not able to be found 404, 503
print("Couldn't connect to the websites perhaps , Hyper text transfer protocol error; {0}".format(e))
return # returning for the debugging
class FilestoTextFiles:
dir_path = os.path.dirname(os.path.realpath(__file__)) # Global Object accessible directory name
# Constructor aka INITIALIZER
def __init__(self):
print("FilestoTextFiles have been intialized") # Debugging
# The below function writes to a file_name as .txt extension, for later onward.
def save_to_txt(self, text_data, file_name):
file_name = ((file_name.replace(".pdf", ".txt")).replace(".docx", ".txt")).replace(".doc",
".txt") # Renaming the file to txt
exact_path = ntpath.basename(file_name)
# if not os.path.exists(self.dir_path+"\\ConvertedTexts"):
# os.makedirs(self.dir_path+"\\ConvertedTexts")
# file_writer = open(self.dir_path+"\\ConvertedTexts\\"+str(file_name), "w") # Writing option in the file
if not os.path.exists(self.dir_path + "/ConvertedTexts"):
os.makedirs(self.dir_path + "/ConvertedTexts")
file_writer = open(self.dir_path + "/ConvertedTexts/" + exact_path, "w") # Writing option in the file
# file_writer = open(file_name, "w") # Writing option in the file
# print(text_data.encode('utf-8'))
file_writer.writelines(str(text_data.encode('utf-8'))) # Writes to a file
file_writer.close() # Closes the file writer.
# The below function is responsible for the reading of the pdf File
def readPDF(self, pdfFile):
try:
rsrcmgr = PDFResourceManager() # Creates the resource manager
# resource_mang = PDFResourceManager()
retstr = StringIO() # string object for the representation of the pdf
# string represetnation from string input and output module
laparams = LAParams() # Parameters Object Creation
device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Creating the device for the conversion
process_pdf(rsrcmgr, device, pdfFile) # Process the specific pdf, to convert into string representations
device.close() # Closes the device.
# print(retstr) # Debuggin
# Decoded value is returned here UTF-8
content = retstr.getvalue() # gets the text from the string object
# print(content)5
return content # Returns the content where its called
except Exception as Ex:
print("While reading the file , there was an error in the function Readodf as :",
Ex) # printing the exception
# Check case for the pdf
def testpdf(self):
try:
pdfFile = urlopen("http://pythonscraping.com/pages/warandpeace/chapter1.pdf") # Gettting from the web
print("Converting ...")
# print(pdfFile)
outputString = self.readPDF(pdfFile) # Calls the function to read from the pdf
# pdfFile.close() # Closes the pdf File
print("Conversion Completed") # Debugging
return outputString # this returns the output string for the specified format
except Exception as Ex:
print("Unable to convert the pdf to text due to : ", Ex) # Printing the Exception
# print(Ex) # DEBUGGING
print("In function testpdf") # Testing
finally:
pdfFile.close() # keep in mind to close the file which you are working on !
# Converting the specified file to pdf
def convert_pdf(self, pdf_filelocation):
if pdf_filelocation != "":
print(pdf_filelocation)
pdf_File = open(pdf_filelocation, "rb") # Opens the pdf in the read format
print("Converting ..") # PROMPT
outputString = self.readPDF(pdf_File) # Calls the read PDF function to work on with it
lines = outputString.split("\n")
outputvalue = ""
for line in lines: # Since the line contains the next line and the unicode schemes to remove those.
if line != "":
line = line.strip()
line = line.replace("b\"", "") # replacing for the filtering
outputvalue += line # Adding in the output value again and again.
return outputvalue # Returns the output string to the function called
else:
print('There is no Location Valid , specified ') # DEBUGGING
# pdf_File.close() # Closes the specified file
# The below function recieves the list of pdf files and then convert them in to set of files.
def convert_list_pdffiles(self, list_pdfs):
# total_file_text_data = [] # This is the list storing the file information as specified
if len(list_pdfs) >= 1 and type(list_pdfs) == list:
for filelocation in list_pdfs:
# file_data = open(filelocation, "rb") # reading the specifid file
text_converted_file = self.convert_pdf(filelocation) # Converts the file data to the text format
# The below function writes to txt
file_name = filelocation.split("\\")[-1] # Gets the file name from the speified path
print("Converted -->" + file_name)
self.save_to_txt(text_converted_file, file_name) # --Saving to .txt file
# total_file_text_data.append(total_file_text_data) # Appends in the list of the text files
# return total_file_text_data # returns to the main function the total file text data with multiple files in action
print("All the pdf files have been converted") # PROMPT
else:
print(
"List of pdf files had length less equal toone and the type pf the files passed are not in the form of list") # DEbugging
def get_AllpdfFiles(self):
# Get all the PDF filenames.
pdfFiles = [] # this is the pdf file list
# for filename in os.listdir(self.dir_path + "\\Files"): # Specifying the folder and looping through the folder
for filename in os.listdir(self.dir_path + "/Files"): # Specifying the folder and looping through the folder
if filename.endswith('.pdf'):
# pdfFiles.append(self.dir_path + "\\Files\\" + filename) # Adding the pdf complete location in the list.
pdfFiles.append(self.dir_path + "/Files/" + filename) # Adding the pdf complete location in the list.
pdfFiles.sort(key=str.lower)
return pdfFiles
def get_all_running_files(self):
file_list = [] # This gets the list of the files
for proc in psutil.process_iter(): # going through all of the processes to get the list of the running processes
try:
if len(proc.open_files()) != 0: # If there is a process running
file_list.append(proc.open_files()) # adding in the file so that the data can be used.
except:
continue
return file_list # this returns the file list
def get_pdf_files(self):
pdf_files_location = []
file_list = [] # This gets the list of the files
for proc in psutil.process_iter(): # going through all of the processes to get the list of the running processes
try:
if len(proc.open_files()) != 0: # If there is a process running
file_list.append(proc.open_files()) # adding in the file so that the data can be used.
except:
continue
for list in file_list:
for inner_list in list:
if str(inner_list).split(',')[0].__contains__(
'.pdf'): # Splitting on the basis of commas as it will be providing the data !
if str(inner_list).split(',')[0][16:-1].endswith('StandardBusiness.pdf'):
continue
else:
pdf_files_location.append(
str(inner_list).split(',')[0][16:-1]) # this wil get the file location
return pdf_files_location
# print(pdf_file_list)
'''----BELOW FUNCTIONS ARE FOR WORD FILES with .doc or .docx---'''
def read_wordFile(self, filename): # Reading the file from the word file
doc = docx.Document(filename) # Creating the document of docs form the specified fule
fullText = [] # Creating a list of texts
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText) # returning by joining in the next line by line
def get_AllwordFiles(self):
wordFiles = [] # List which wil be holding the file names of word file
# for filename in os.listdir(self.dir_path + "\\Files"): # listing the current directory files
for filename in os.listdir(self.dir_path + "/Files"): # listing the current directory files
if filename.endswith('.word') or filename.endswith('.docx') or filename.endswith('.doc'):
# wordFiles.append(self.dir_path + "\\Files\\" + filename) # adds the file name in the word list
wordFiles.append(self.dir_path + "/Files/" + filename) # adds the file name in the word list
wordFiles.sort(key=str.lower) # sorts the list with respect to key value
return wordFiles # returns all the file list
def convert_allwordFiles(self, wordfilelist):
if type(wordfilelist) == list and len(wordfilelist) >= 1:
for single_wordFile in wordfilelist:
data = self.read_wordFile(single_wordFile) # Calling in the word data writing function
file_name = single_wordFile.split("\\")[-1] # Gets the file name from the speified path
lines = data.split("\n")
total_data = "" # Will hold the data
for line in lines: # Data filterning
if line != "":
line = line.strip()
total_data += line + "\n" # Appending in the line
print("Converting...." + single_wordFile)
self.save_to_txt(total_data, file_name) # Passing the data and the single file name to the list
else:
print("NOPE NOT POSSIBLE")
def convert_all(self):
pdf_files = self.get_AllpdfFiles() # Gets all the pdf file.
word_files = self.get_AllwordFiles() # Gets all the word files.
print("pdf Files found are ", pdf_files) # Prompting the message in the console
print("word_files found are", word_files) # prompting the message on console
'''----------------READING AND CONVERTING ALL THE PDF FILES TO TXT FILES -------------------------------'''
self.convert_list_pdffiles(pdf_files) # Calls in the convert function to convert all the pdfs
self.convert_allwordFiles(word_files) # Converts all the word files
# pdf_files_converted_data = self.convert_list_pdffiles(pdf_files) # Gets all the data in the pdf files .
# The Above returns a list .
class PYSHA_CLASS:
db = NONE
lastlink = "" # just to be reminded for the last link visited
engine = pyttsx.init() # intializing the engine here so that there are global engine speech , which can be changed
py_chat_bot = Chatting_PYSHA(name="PYSHA", trainable=True, train_corpus=True) # intialized the Chatting Pysha
newscheck = NEWS() # Creates an object for news
music_player = MUSIC_PLAYER() # This creates the music player object class
image_shower = IMAGE_CHECK() # This creates the object for the images , this can be accessible locally
pdf_file = None # Specifing the pdf file to be none !
fttf = FilestoTextFiles() # Creating the class of the text filtering , whic hwill be used to convert to pdf
music_check_indicator = 0 # This will be used to check the music of the
image_check_indicator = 0 # This will be used to check if the image is already there or not
def __init__(self):
print("PYSHA INITIALIZED!")
self.createlocaldb() # this creates the localdb for requests
# creating the local Database
def greetings_check(self):
try:
hour = datetime.datetime.now().hour # Getting the stat of the current hour !
if hour in [4, 5, 6, 7, 8, 9, 10]:
self.text_to_speech("Good Morning Shafay, seems like you woke up on time")
elif hour in [11, 12, 13, 14, 15]:
self.text_to_speech("Good After noon Shafay, seems like you are going to university")
elif hour in [16, 17, 18, 19]:
self.text_to_speech("Good Evening Shafay!, What are your doing ? You should be taking classes ")
elif hour in [20, 21, 22, 23, 24, 1, 2, 3]:
self.text_to_speech(
"Well seems a little off , haven't you slept Well ? . Its " + str(hour) + str(" here"))
else:
self.text_to_speech("Time checking Error faced")
except Exception as Ex:
print("Exception Occurred in function Greetings_check :", Ex)
def schedule_check(self):
try:
file_read = open("Schedule.txt", "r").readlines()
for line in file_read:
self.text_to_speech(line.strip()) # Speaks all the lines for the today schedule
except Exception as Ex:
print("Not found", Ex)
'''Having the specified short term memory in case of checking through the Brain'''
def shortterm_check(self, limit=0):
try:
stm_list_recieved = stmcheck() # calls the stm check module
list_recieved = display_stm(
stm_list_recieved) # Filterening all the sentences and specifying the current list
if limit == 0:
random.shuffle(list_recieved) # random shuffling , Using the random shuffle for the current memory
for i in range(len(list_recieved)):
self.text_to_speech("You said at " + str(i) + " " + list_recieved[i])
# just printing the list for the things.
elif limit == 1:
self.text_to_speech(list_recieved[0]) # pass the first element inthe list which is the last said.
# TODO : call the text to speech and speak the list in an specified order
except Exception as Ex:
print("short term memory check Failure at ", Ex)
# Create the local database for the function
def createlocaldb(self):
try:
self.db = db_data() # this calls the db class
self.db.create_database() # this creates the database for the class.
except Exception as Ex:
print("there was an error while creating the local database", Ex)
# Playing the video for the module trhough python check
def play_video(self):
try:
os.system("start E:\\MusicVideos\\Marshmello---Keep-it-Mello-ft-Omar-LinX-Official-Music-Video.mp4")
except Exception as Ex:
print("check the directory exception", Ex)
# TODO : more Accurate apps running
# for going through the history
def insert_into_request(self, request_text, responce_text):
# this is the function responsible for the writing in the history.
try:
self.db.insert_into_Requests(request_text, responce_text) # this is twrite into the reposce text
except Exception as Ex:
print("There was and Error inserting in to the database at insert_into_request function", Ex)
# For terminating the prgrams use the following code
def close_program(self, input_string):
if input_string == "window media player":
try:
self.text_to_speech("Closing Window Media Player")
os.system("TASKKILL /F /IM wmplayer.exe")
self.text_to_speech("Window media player has been closed")
except Exception as ex:
print("Exception occured a ", ex) # printing the exception
elif input_string == "music":
try:
os.system("TASKKILL /F /IM wmplayer.exe")
self.text_to_speech("Music stopped")
except Exception as Ex:
print("close program input string debugging requires")
elif input_string == "calculator":
try:
self.text_to_speech("Closing Calculator")
os.system("TASKKILL /F /IM calc.exe")
self.text_to_speech("calculator has been closed")
except Exception as ex:
print("Exception occured a ", ex) # printing the exception
elif input_string == "note pad" or input_string == "notepad":
try:
os.system("TASKKILL /F /IM notepad.exe")
except Exception as ex:
print("Exception occured a ", ex) # printing the exception
elif input_string == "performance monitor":
try:
os.system("TASKKILL /F /IM perfmon.exe") # Closing the performance monitor
except Exception as ex:
print("Exception occurred ", ex) # printing the exception
elif input_string == "smartscreen" or input_string == "smart screen":
try:
os.system("TASKKILL /F /IM smartscreen.exe")
except Exception as ex:
print("Exception occurred ", ex) # printing the exception
elif input_string == "space agent" or input_string == "spaceagent":
try:
os.system("TASKKILL /F /IM SpaceAgent.exe")
except Exception as ex:
print("Exception occured a ", ex) # printing the exception
elif input_string == "network status":
try:
os.system("TASKKILL /F /IM netstat.exe")
except Exception as ex:
print("Exception occurred a ", ex) # printing the exception
elif input_string == "defragment":
try:
os.system("TASKKILL /F /IM defrag.exe")
except Exception as ex:
print("Exception occurred as ", ex) # printing the exception
elif input_string == "clean manager":
try:
self.text_to_speech("")
os.system("TASKKILL /F /IM cleanmgr.exe")
except Exception as ex:
print("Exception occurred as ", ex) # printing the exception
elif input_string == "command prompt":
try:
self.text_to_speech("Closing Command prompt") # Voice
os.system("TASKKILL /F /IM cmd.exe")
self.text_to_speech("Command prompt has been closed") # Voice
except Exception as ex:
print("Exception occurred as ", ex) # printing the exception
elif input_string == "chrome" or input_string == "google chrome":
try:
os.system("TASKKILL /F /IM chrome.exe")
self.text_to_speech("Chrome has been closed") # Closed the chrome
except Exception as ex:
print("Exception occurred as ", ex) # printing the exception
else:
print("I found something new to close , I cannot locate the thing")
self.text_to_speech("I found something new to close, i cannot locate the location")
# Debugging
# TODO: For running the apps
def run_apps(self, text_input=""):
text_input = text_input.strip()
if text_input != "":
if text_input == "calculator":
self.text_to_speech("Launching Calculator")
os.startfile('calc.exe') # Running the calculator in the Operating system
self.text_to_speech("Calculator launched")
return
elif text_input == "notepad":
self.text_to_speech("Launching Notepad")
os.startfile('notepad.exe') # Running the notepad using the Os module for the specified Attrirbute !
self.text_to_speech("notepad launched")
return
elif text_input == "performance monitor":
os.startfile('perfmon.exe') # Launchign the Performance monitor from the exe
self.text_to_speech("Performance monitor has been launched")
return
elif text_input == "smart screen":
os.startfile('smartscreen.exe') # Working on the smart screen and running the Exe !
self.text_to_speech("smart screen launched ")
return
elif text_input == "space agent":
os.startfile('SpaceAgent.exe') # Running the space agent for the
self.text_to_speech("space agent has been launched")
return
elif text_input == "network status":
os.startfile('netstat.exe') # you are working ehre !
self.text_to_speech("Network status for today have been shown on the screen")
self.text_to_speech("somethings seems to be off")
return
elif text_input == "bluetooth setting":
os.startfile('fsquirt.exe') # you are working here !
return
elif text_input == "defragment":
os.startfile('Defrag.exe') # you are working here !
return
elif text_input == 'clean manager':
os.startfile("cleanmgr.exe")
return
elif text_input == "command prompt":
os.startfile("cmd.exe")
return
elif text_input == 'direct ex' or text_input == 'direct setting':
os.startfile("dxdiag.exe")
return
elif text_input == "control panel":
os.startfile('control.exe')
return
elif text_input == 'resource monitor':
os.startfile('resmon.exe')
return
# this launched the resource monitor to monitor the resource!
elif text_input == "game panel":
os.startfile('GamePanel.exe')
return
elif text_input == 'graphic settings':
os.startfile('Gfxv4_0.exe') # this access the graphic cards
return
elif text_input == 'dpi scaling':
os.startfile('DipScaling.exe') # this truns the dpi scalling for the
return
elif text_input == 'disk partition':
os.startfile('diskpart.exe')
return
elif text_input == 'python' or text_input == "python interpreter":
try:
os.startfile("C:\\Program Files\\Python35\\pythonw.exe")
# this calls the file location and then run the program of the python.
# There you should run the pyton programming language
# so that the language will be specified by the face of the
return
except Exception as Ex: # printing the exception of the assistant
print("Pycharm not found in the specificied location in the operating system", Ex)
elif text_input == "pycharm" or text_input == "python best interpreter":
try:
os.startfile("C:\\Program Files\\Python35\\Lib\\idlelib\\idle.pyw")
# --- This runs the pycharm Compiler which can be used for the Html or the python programming
# The Below function will be used to search on the browser and then show the desire result
return
except Exception as Ex:
print(
"Sorry i was unable to open the IDle of python perhaps , its not found in the specified location",
Ex)
elif text_input == "movie player":
print("started movie player!!!")
os.startfile("wmplayer.exe") # window media player execution!
return
else:
print("What you want to open or run ?") # Debuggin
self.text_to_speech("What do you want to open or run ") # Debuggin
return
# TODO : Exact Searching
def search_browser(self, text_input):
print('-searching on browser-')
try:
url = 'http://google.com/search?q=' + text_input
# Creating or generating a google link for the particular file
webbrowser.open(url)
return
except Exception as Ex:
self.text_to_speech(
"I'm sorry, I couldn't reach google", Ex)
# Calling the Function so that it can be identified that ,machine can speaks for itself
return
# Below is the code for searching on yahoo.
def search_yahoo(self, text_input):
try:
self.text_to_speech("Searching on yahoo") # Voice Message
url = "https://search.yahoo.com/search;_ylc=X3oDMTFiN25laTRvBF9TAzIwMjM1MzgwNzUEaXRjAzEEc2VjA3NyY2hfcWEEc2xrA3NyY2h3ZWI-?p=" + text_input.replace(
" ", "+") + "&fr=yfp-t&fp=1&toggle=1&cop=mss&ei=UTF-8"
webbrowser.open(url) # opens the search query
self.text_to_speech("Yahoo search has been displayed ")
except Exception as E:
print("Problem reaching to yahoo, perhaps you have no internet connection")
self.text_to_speech("Connecting to yahoo failed, there must be a connection problem")
# Below is the code to search on the bing website
def search_bing(self, text_input):
print('-searching on browser-')
try:
url = 'http://www.bing.com/search?q=' + text_input.replace(" ", "+") + "&qs=n&form=QBLH"
# Creating or generating a google link for the particular file
webbrowser.open(url)
return
except:
self.text_to_speech(
"I'm sorry, I couldn't reach bing")
# Calling the Function so that it can be identified that ,machine can speaks for itself
return
# Below is the function responsible for the searching of the wallpaper on the web
def search_wallpaper(self, search_input):
try:
link = "http://www.wallpaperup.com/search/results/" + search_input.replace(" ", "+")
webbrowser.open(link) # Opens the links for the wallpaper
self.text_to_speech("Found some of the wallpapers regarding to" + search_input)
except Exception as Ex:
print("There was an error finding the exact wallpaper", Ex)
# The below function is responsible for the search on the Wikipedia
# searching on the Wikipedia and then asking the pysha to speak the respectable result!!
# TODO : WIkI Algorithm improvements
def search_wiki(self, text_input):
# suggested_string = wikipedia.suggest(text_input) # now going for the suggestion
try:
wiki_page = wikipedia.page(text_input) # this opens up the wiki page for the particular thing
# text_to_speech(str(wiki_page.title)) # asking the machine to speak this specified word
# summary_text = wikipedia.summary(text_input, sentences=4) # search on the wikipedia!
wiki_link = str(wiki_page.url) # Converts the url of the wiki links to the url.
wiki_images = wiki_page.images # Gets all the images link references. as a list
wiki_sumry = wikipedia.summary(text_input, sentences=3)
print(wiki_sumry)
# webbrowser.open(wiki_link) # opens the link on the web browser and then search the specified text link
self.text_to_speech(wiki_sumry)
return wiki_link # this returns the wikilink , keep in mind this is just for reading in the later onward purposes
except Exception as Ex:
self.text_to_speech(
"Sorry i couldn't connect to the wikipedia!! nor find a relevant link, there must be a connection problem",
Ex)
return
def search_quora(self, text_input):
try:
search_string = text_input.replace(" ", "+")
search_link = "https://www.quora.com/search?q=" + search_string
self.text_to_speech("Searching on Quora")
webbrowser.open(search_link) # Opening the link on search quora
self.text_to_speech("Result have been Displayed")
except Exception as Ex:
print("There was an Error in the Quora, in function search_quora", Ex) # Exception Raised
def search_pc_part_picker(self, text_input):
text_input = text_input.replace(" ", "+") # This creates the search string
search_url = "https://pcpartpicker.com/search/?q=" + text_input
self.text_to_speech("Searching on pc part picker")
webbrowser.open(search_url)
self.text_to_speech("Found some things , have a look ! ")
# Getting the news from the web.
def get_news(self):
try:
news_string = self.newscheck.national_news() # Get the national news from the __newsupdate.py file
self.text_to_speech(news_string) # Speaks out the news about the particular things (current)
return news_string # The function will return the current news from the web
except Exception as Ex:
print("There was an error retrieving the news :", Ex)
self.text_to_speech("Sorry i could not connect to news center , database failure")
return None # returns none in case of failuire
# The below function is responsible for the running of the chat with the below function
# This will be used to show the Frontend for the application.
# There are two dynamic ways for storing the Frontend , since this is a Hit and run trail using the function!
# The Human computer interaction will be updated according to the software development module!
# TODO: Frontend HCI needs to be created !
def frontend_hci(self, label_text):
try:
root = Tk() # This created the tkinter , face.!
root.title("PYSHA 1.0") # Making the Title for the Py Sha 1.0 ,
root.geometry("300x300") # specifying the x and the y axis in the scenario
label1 = Label(root, text=label_text, font='size,25') # This is the label insertion for the Tkinter module
print(label1) # Showing in the console for the debuggin purposes
label1.pack() # Packing up the label1 module in the GUI
root.after(10000, lambda: root.destroy()) # Destroying after 10 seconds
root.mainloop() # Executing the main loop for the Gui Till it gets exited
return
except Exception as Ex:
print("unable to create the front end for the User interface . ", Ex)
return
# TODO : make the Chat intelligent , using the Natural language processing and AIML (artifical intelligence markup)
# language)
def chat(self, input):
insults = ["weirdo", "stupid", "weird", "dumb", "idiot", "retard", "retarded", "fat", "lazy",
"annoying", "moron", "simp", "big", "ugly", "sad", "wimp", "troll"]
complements = ["nice", "happy", "good", "smart", "wonderful", "really ", "intellegent", "awesome", "beautiful"]
ranNum = randrange(1, 4)
# chatting features of PyDa:
if input.startswith("do you want to "):
if ranNum == 1:
self.text_to_speech("Maybe later")
if ranNum == 2:
self.text_to_speech("I don't think that's a good idea")
if ranNum == 3:
self.text_to_speech("Yes! lets do it")
if input.startswith("do you like to "):
if ranNum == 1:
self.text_to_speech("Sometimes I do")
if ranNum == 2:
self.text_to_speech("No, I hate doing that")
if ranNum == 3:
self.text_to_speech("Yes, I do that all the time")
if input.startswith("i hate "):
if "Shafay" in input[6:]:
self.text_to_speech("What? Shafay is the coolest person ever!")
elif ranNum > 2:
self.text_to_speech("I think " + input[6:] + " is awesome")
elif ranNum <= 2:
self.text_to_speech("I don't like " + input[6:] + ' either')
words = input.split
if input.startswith("you are a"):
if any(input[10:].startswith(c) for c in complements):
if ranNum == 1:
self.text_to_speech("Thank you, I know")
if ranNum == 2:
self.text_to_speech("isn't it obvious?")
if ranNum == 3:
self.text_to_speech("you made my day!")
elif any(input[11:].startswith(c) for c in complements):
if ranNum == 1:
self.text_to_speech("Thank you, I know")
if ranNum == 2:
self.text_to_speech("isn't it obvious?")
if ranNum == 3:
self.text_to_speech("you made my day!")
if any(input[10:].startswith(i) for i in insults):
if ranNum == 1:
self.text_to_speech("I know you are but what am i?")
if ranNum == 2:
self.text_to_speech("Don't troll me. bad things will happen")
if ranNum == 3:
self.text_to_speech("sorry, i was to busy, BLOCKING OUT THE HATERS!")
elif any(input[11:].startswith(i) for i in insults):
if ranNum == 1:
self.text_to_speech("I know you are but what am i?")
if ranNum == 2:
self.text_to_speech("Don't troll me. bad things will happen")
if ranNum == 3:
self.text_to_speech("sorry, i was to busy, BLOCKING OUT THE HATERS!")
elif input[10:] or input[11:] not in insults:
if ranNum == 1:
self.text_to_speech("I don't know what you mean by that")
if ranNum == 2:
self.text_to_speech("Your words are not in my library")
if ranNum == 3:
self.text_to_speech("No comment")
elif input[10:] or input[11:] not in complements:
if ranNum == 1:
self.text_to_speech("I don't know what you mean by that")
if ranNum == 2:
self.text_to_speech("Your words are not in my library")
if ranNum == 3:
self.text_to_speech("No comment")
if input.startswith("are you a"):
if any(input[10:].startswith(c) for c in complements):
if ranNum == 1:
self.text_to_speech("yes i am")