-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvirtualAssistant.py
227 lines (189 loc) · 7.57 KB
/
virtualAssistant.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
#############################################################################
# VIRTUAL ASSISTANT USING PYTHON
#############################################################################
# Devloped By:
# Name: Souraj Mukhopadhyay
# Github: Souraj239
# Emailid: [email protected]
# LinkedIn : https://www.linkedin.com/in/souraj-mukhopadhyay-a00002161/
#Twitter: @souraj239
#instagram: souraj.m
##############################################################################
# Do read the Readme file before using the code
##############################################################################
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import smtplib
from googlesearch import *
import requests
import json
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[2].id) #Toggle between [0] & [1] for male and female voice
def speak(audio):
print(audio)
engine.say(audio)
engine.runAndWait()
def wishMe():
hour=int(datetime.datetime.now().hour)
if(hour>=0 and hour <12):
speak("Good Morning!")
elif (hour>=12 and hour <18):
speak("Good Afternoon!")
else:
speak('Good Evening!')
speak("I am your Personal Virtual Assistant! Please tell me how may I help you ?")
def takeCommand():
r=sr.Recognizer()
with sr.Microphone() as source:
print("Listening....")
r.pause_threshold = 1
audio=r.adjust_for_ambient_noise(source)
audio=r.listen(source,10)
try:
print("Recognizing...")
query=r.recognize_google(audio,language='en-in') #Change the language as per requirements
print(f"You said : {query}\n")
except sr.WaitTimeoutError:
speak("Couldn't hear you. Did you say anything?")
except Exception as e:
#print(e)
print("Didn't get that! Please Repeat")
return "None"
return query
def googleSearch(query):
chrome_path = r'C:\\Program Files (x86)\\Google\\Chrome\\Application %s'
for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
webbrowser.open("https://google.com/search?q=%s" % query)
def readNotes():
with open("notes.txt","r") as f:
notes=f.read()
speak(notes)
def openApp(appName):
appdir={}
try:
with open("applicationpaths.txt","r") as f: #add the apps and their path names in the file
for line in f:
(app,path)= line.split(" ")
appdir[app]=path
os.startfile((appdir.get(appName)).strip())
except Exception as e:
print(e)
speak("Cannot find the Application. Searching on google")
googleSearch(f"open {query}")
def addressbook(first_name):
addDict={}
with open("addressbook.txt",'r') as f: #populate the addressbook.txt with your contacts
for line in f:
(name,email)=line.split(" ")
addDict[name]=email
return addDict.get(first_name,"Error")
def takeNotes():
while(True):
speak("Please dictate your notes")
notes=takeCommand()
with open("notes.txt","a+") as f:
f.writelines(notes)
speak("Do you want to add anything else ? ")
choice=takeCommand().lower()
if "no" in choice or 'exit' in choice:
speak("notes saved..")
break
def sendEmail(to, message):
server=smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
with open('credentials.txt','r') as f: #put your credentials in cred.txt fie as shown in example
cred=f.read()
eid,passw=cred.split(" ")[0], cred.split(" ")[1]
server.login(eid,passw)
server.sendmail(eid,to,message)
def readNews():
speak("Today's Headlines.:")
url="http://newsapi.org/v2/top-headlines?country=in&apiKey=xxxxxxxxxxxxxxxxxxxxxxxx" #Modify with your own api key here
news=requests.get(url).text
news_json=json.loads(news)
articles=news_json.get('articles')
for article in articles:
speak(article.get("title"))
speak("Moving to next news")
if __name__=="__main__":
wishMe()
while True:
query=takeCommand().lower()
if 'wikipedia'in query:
speak("Searching wikipedia......")
query=query.replace("wikipedia"," ")
results=wikipedia.summary(query,sentences=3)
speak("According to Wikipedia...")
speak(results)
elif 'who is'in query:
speak("Searching wikipedia......")
query=query.replace("who is"," ")
results=wikipedia.summary(query,sentences=3)
speak("According to Wikipedia...")
speak(results)
elif "open youtube" in query:
speak("opening youtube")
chrome_path = r'C:\\Program Files (x86)\\Google\\Chrome\\Application %s'
webbrowser.open("youtube.com")
elif "open google" in query:
speak("opening google")
chrome_path = r'C:\\Program Files (x86)\\Google\\Chrome\\Application %s'
webbrowser.open("google.com")
elif "play music" in query or 'play songs' in query:
music_dir="D:\\music" #Add your own music directory
songs=os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir,songs[0]))
elif "time" in query:
strTime=datetime.datetime.now().strftime("%H:%M:%S")
speak(f"The time is {strTime}")
elif "send email" in query:
try:
speak("To whom? (First Name Only)")
contact=takeCommand().lower()
mailid=addressbook(contact)
if mailid=="Error":
speak("You have entered a Invalid name. Please Try again")
raise "InvalidEmailIdException"
speak("what should I say?")
message=takeCommand()
sendEmail( mailid ,message)
speak("Your email has been sent")
except Exception as e:
print(e)
speak("Error sending email")
elif "email id" in query:
speak("Who's email id do you want? (First Name Only)")
contact=takeCommand().lower()
mailid=addressbook(contact)
if mailid=="Error":
speak("You have entered a Invalid name. Please Try again")
else:
speak(f"{contact}'s email id is : {mailid}")
elif "open" in query:
query=(query.replace("open ","")).strip()
openApp(query)
elif "take notes" in query:
takeNotes()
elif "read" in query and "notes" in query:
readNotes()
elif "news" in query:
readNews()
elif "exit" in query:
speak("Have a Good day!")
break
else:
googleSearch(query)
'''
query=takeCommand() #comment out if you want to respond it only on "Hey Assistant" Command
while("assistant" not in query):
query=takeCommand()
continue
speak("How may I help you?")
'''