Issue
Hi so I'm making a voice assistant in python and I already made a while loop so that after I ask a question or say an order I can ask again and it works but the problem is that if it doesn't recognize what i said it exits and gives me an error
i've tried watching some youtube tutorials but they are all using different variables and code than me so I can't find the solution there neither can I find the fix on stack overflow...
Here's the code I used
import speech_recognition as sr
import pyaudio
import wikipedia
import datetime
import webbrowser as wb
import pywhatkit
import os
from requests import get
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #changing index changes voices but ony 0 and 1 are working here
engine.runAndWait()
def speak(audio):
engine.say(audio)
print(audio)
engine.runAndWait()
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"user said: {query}\n")
except Exception as e:
print("Sorry i didn't catch that...")
return query
def wish():
hour = datetime.datetime.now().hour
if hour >= 6 and hour < 12:
speak("Good Morning Sir!")
elif hour >= 12 and hour < 18:
speak("Good after noon Sir!")
elif hour >= 18 and hour < 24:
speak("Good evening Sir!")
else:
speak("Good night sir")
speak("I am jarvis your personal assistant")
def time():
Time = datetime.datetime.now().strftime("%I:%M:%S")
speak(Time)
def date():
year = int(datetime.datetime.now().year)
month = int(datetime.datetime.now().month)
date = int(datetime.datetime.now().day)
speak(date)
speak(month)
speak(year)
if __name__ == "__main__":
wish()
while True:
query = takeCommand()
if 'according to wikipedia' in query.lower():
speak('Searching wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak(results)
if 'open youtube' in query.lower():
wb.open('https://youtube.com')
if 'open google' in query.lower():
wb.open('https://google.com')
if 'open reddit' in query.lower():
wb.open('https://reddit.com')
if 'open amazon' in query.lower():
wb.open('https://amazon.ae')
if 'open wikipedia' in query.lower():
wb.open('https://wikipedia.com')
if 'open discord' in query.lower():
wb.open('https://discord.com/channels/@me')
if 'open gmail' in query.lower():
wb.open('https://gmail.com')
if 'open twitter' in query.lower():
wb.open('https://twitter.com')
if 'what time is it' in query.lower():
speak(time())
if 'what is the day' in query.lower():
speak(date())
if 'search' in query.lower():
search = query.replace('search', '')
speak('searching ' + search)
pywhatkit.search(search)
if 'play' in query.lower():
song = query.replace('play', '')
speak('playing ' + song)
pywhatkit.playonyt(song)
if "launch notepad" in query.lower():
npath = "C:\\WINDOWS\\system32\\notepad.exe"
os.startfile(npath)
if "launch discord" in query.lower():
npath = "C:\\Users\\Yousif\\AppData\\Local\\Discord\\Update.exe"
os.startfile(npath)
if "launch steam" in query.lower():
npath = "C:\\Program Files (x86)\\Steam\\steam.exe"
os.startfile(npath)
if "launch epic games" in query.lower():
npath = "C:\\Program Files (x86)\\Epic Games\\Launcher\\Portal\\Binaries\\Win32\\EpicGames.exe"
os.startfile(npath)
if "what is my ip" in query.lower():
ip = get('https://api.ipify.org').text
speak(f"your IP Address is {ip}")
print(ip)
if 'hey jarvis' in query.lower():
speak("I am here sir")
print("I am here sir")
if 'thank you' in query.lower():
speak("your welcome sir")
if 'sleep' in query.lower():
speak("good bye sir")
exit()```
---
And here's the error I got
```Traceback (most recent call last):
File "C:/Users/PycharmProjects/Jarvis Mk2/main.py", line 72, in <module>
query = takeCommand()
File "C:/Users/PycharmProjects/Jarvis Mk2/main.py", line 37, in takeCommand
return query
UnboundLocalError: local variable 'query' referenced before assignment
Process finished with exit code 1```
Solution
the problem lies in your try.. expept
clause. If youre command is not recognized, the expect clause is triggerd, however after it prints "Sorry, I didn't catch that", you ask it to return query
nonetheless. query
is only assinged a value if the try
-branch is executed successfully though. Therefore you get the UnboundLocalError. To avoid this, try:
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"user said: {query}\n")
except Exception as e:
print("Sorry i didn't catch that...")
return ""
return query
This will exit without enforcing a value of query. This also will cause all of the if-statements in your while-loop to evaluate to false (trying to process a query that it didn't understand is not sensible, so skipping all ifs is desired behavior). However you might want to think about returning None
instead and handle this case differently in your while-loop (note: comparisons with None
or done like query is\is not None
rather than with the ==
operator).
Also, welcome to stackoverflow, enjoy your stay :) hope this helps,
Rawk
Answered By - RawkFist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.