' UnboundLocalError: local variable 'command' referenced before assignment ' - python

I am making a microphone class that recognize user voice. It gives me an UnboundLocalError. That happens when I add a return command to the mic_config() method.
import speech_recognition as sr
import pyaudio
from speaker import Speaker
class Microphone:
"""Microphone class that represent mic and get user's voice..."""
def __init__(self):
"""Initializing of class"""
self.recognizer = sr.Recognizer() # Voice recognizer
self.microphone = sr.Microphone() # Mic
def mic_config(self):
try:
with self.microphone as source: # Getting mic
print('Listening...')
voice = self.recognizer.listen(source)
command = self.recognizer.recognize_google(voice, language='en-IN') # Using google api
print(command)
except:
pass
return command
m1 = Microphone() # just a test
m1.mic_config()```

Yeah as Carcigenicate said it is because command is only defined in the try block. This means that if there is an error then command is not defined. I don't know if it is just in the code you posted here but there is an indent error in the with statement
try:
with self.microphone as source:
print('Listening...')
voice = self.recognizer.listen(source)
command = self.recognizer.recognize_google(voice, language='en-IN')
print(command)
except:
raise CustomError
# or return None, command = None, etc just define command before the last line
# or don't let the function reach the return command statement
return command

Related

I am building a simple AI assistant in python but the if statement is not working

I am building a simple AI assistant in python and so far everything has worked pretty well. The voice recognition and text to speech are working also fine. I wanted to make it work like, I am going to speak something and depending on the input it would answer some simple questions. But with the if statement I tried to make conditions depending on the input but it doesn't get executed instead the else statement gets executed.
import speech_recognition as sr
import pyttsx3
engine = pyttsx3.init()
listener = sr.Recognizer()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty("rate", 178)
def talk(text):
engine.say(text)
print(text)
engine.runAndWait()
def command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
print(command)
except:
pass
command = ''
return command
def run():
data = command()
if 'hello' in data:
talk('Hello')
elif 'who are you' in data:
talk('I am an AI.')
else:
talk("I couldn't hear it.")
while True:
run()
I have tried to use it without a function but still the same problem. It doesn't work even if the if statement is true.
I think you wanted to put the command = '' in the except block. It is an indentation error.

I'm trying to learn how to create a virtual assistant, and I encountered this error

import speech_recognition as sr
import pyttsx3
import pywhatkit
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'robot' in command:
command = command.replace('robot', '')
print(command)
except:
pass
return command
def run_robot():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing' + song)
pywhatkit.playonyt(song)
run_robot()
Error:
listening...
Traceback (most recent call last):
File "C:/Users/CyberDash-/PycharmProjects/AIProject/main.py", line 40, in <module>
run_robot()
File "C:/Users/CyberDash-/PycharmProjects/AIProject/main.py", line 32, in run_robot
command = take_command()
File "C:/Users/CyberDash-/PycharmProjects/AIProject/main.py", line 28, in take_command
return command
UnboundLocalError: local variable 'command' referenced before assignment
Process finished with exit code 1
What's the problem here? While I'm using my headset everything is going fine, but after I remove my headset, the program works but without interaction with the robot. I can see the word "listening...." but nothing happens after, until I stop the program and see this message.
Catch and pass all exception is a very bad idea.
def take_command():
try: # <- GOOD
with sr.Microphone() as source: # <- (1) The problem may be HERE
print('listening...')
voice = listener.listen(source) # <- (2) or HERE
command = listener.recognize_google(voice)
command = command.lower()
if 'robot' in command:
command = command.replace('robot', '')
print(command)
except: # <- BAD, you catch all exception
pass # <- BAD++, an exception is raised and you do... nothing
return command # <- (3) because the command variable is undefined so the problem occurs before command was defined

error in python AI project it shows me a error whenever i give a input from my mic it shows me that it is 'none type' not iterable

i have written this code but whenever I say a command which i have mentioned in the code into my mic it shows me a syntax error on line 34 (from the start of the code) it shows me: argument of type "noneType" is not iterable
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
def speak(text):
engine.say(text)
engine.runAndWait
def take_command():
try:
with sr.Microphone() as source:
voice = listener.listen(source)
command = listener.recognize_google()
command = command.lower()
speak(command)
except:
speak("could you please repeat what you just said")
#return command
def run():
command = take_command()
print (command)
if "play" in command:
speak("playing")
pywhatkit.playonyt("playing")
elif "time" in command:
time = datetime.datetime.now().strftime("%I:%M:%p")
speak(time)
elif "hello" in command:
speak("Hello there, how are you doing!")
elif "wikipedia" in command:
wiki = command.replace("wikipedia", "")
info_output = wikipedia.summary(wiki, 5)
print(info_output)
speak(info_output)
elif "joke" in command:
joke = pyjokes.get_joke()
speak(joke)
print(joke)
else:
speak("sorry that may be beyond my abilities at the moment")
while True:
run()

Python speech recognition

When i run this code and speak script return empty list:
import pyaudio
import pyttsx3
import os
import pyautogui
import speech_recognition as sr
def command():
r = sr.Recognizer()
mic = sr.Microphone()
recog = sr.Recognizer()
with mic as u_audio:
print('Speak please')
r.adjust_for_ambient_noise(u_audio)
voice = r.listen(u_audio)
try:
listening = recog.recognize_google(voice, language = 'en-EN', show_all = True)
print(listening)
except Exception as e:
print('I not understand' + str(e))
command()
command()
output:
speak please
[ ]
i do not understand, why list are empty. Maybe i should choose microphone index.
The Microphone is the Problem
The problem should be possibly be on the Microphone, because I ran the same code, and it does give the Output, it gives all possible outcomes of the speech.
Anyways, it isn't efficient. Unwanted libraries slows it down, here is the updated code:
import pyttsx3
import speech_recognition as sr
def command():
r = sr.Recognizer()
mic = sr.Microphone()
recog = sr.Recognizer()
with mic as u_audio:
r.adjust_for_ambient_noise(u_audio)
print('Speak please')
voice = r.listen(u_audio)
try:
listening = recog.recognize_google(voice, language = 'en-EN', show_all = True)
print(listening)
except Exception as e:
print('I not understand' + str(e))
command()
command()
Comment down the result!

Tkinter's Mainloop function dosen't allow other funtions to run

I am actually the member of NLI(Novitatis Locus Industries) and our team seems to get some issues. While designing a voice enabled program with GUI, tkinter's mainloop seems to be giving us some issues. See our code-
//this function defines the gui//
def gui():
gui_kurooto = Tk()
txt_dsply_var = StringVar()
AUTHN_LBL = Label(gui_kurooto, text=txt_dsply_var)
AUTHN_LBL.pack()
gui_kurooto.mainloop()
//this code defines the microphone input//
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
txt_dsply_var = StringVar()
txt_dsply_var.set('Listening')//display listening on gui//
r.pause_threshold = 1
r.energy_threshold = 10000
audio = r.listen(source)
try:
print("Recognizing...")
txt_dsply_var = StringVar()
txt_dsply_var.set('Recognizing')//display recognizing//
query = r.recognize_google(audio, language='en-en')
print(f"User said: {query}\n")
txt_dsply_var = StringVar()
txt_dsply_var.set(f"User said: {query}\n")//display input//
except Exception as e:
# print(e)
print("Say that again please...")
return "None"
return query
//to run//
if __name__ == "__main__":
gui()
while True:
# if 1:
query = takeCommand().lower()
Now when I try to run this, the code never reaches the while loop. I know the mainloop is an infinite loop but is there a substitute present their so I can let it reach other functions. Keeping the function out of function also dosen't work. Can I place it after the query command?
Also I have other question, is there a way by which I can spectra according to the voice input like Google and Siri have bars which move when we speak?
Any help would be appreciated.

Categories