Search code examples
pythonspeech-recognitionalexa-skills-kitwikipediapyttsx3

Python Unbound error in return statement of a function


I am trying to build an Ai assistant similar to Alexa from this tutorial https://www.youtube.com/watch?v=AWvsXxDtEkU... So, I was getting this error and I can't seem to debug it:

line 31, in take_command : return command : UnboundLocalError: local variable 'command' referenced before assignment

I know this question has been asked a ton of times but I can't seem to understand the solutions, I've read plenty of articles about an unbound error I know it's an issue of global and local scopes but again the same same thing I can't understand those properly...

Here's my code:

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 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 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command


def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk('Current time is ' + time)
    elif 'who the heck is' in command:
        person = command.replace('who the heck is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)
    elif 'date' in command:
        talk('sorry, I have a headache')
    elif 'are you single' in command:
        talk('I am in a relationship with wifi')
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Please say the command again.')


while True:
    run_alexa()

I hope you can help me fix this mess... Thanks


Solution

  • Your line 31, return command will never be reached if you run into an exception. You have to put the return statement within the try block.

    def take_command():
        try:
            with sr.Microphone() as source:
                print('listening...')
                voice = listener.listen(source)
                command = listener.recognize_google(voice)
                command = command.lower()
                if 'alexa' in command:
                    command = command.replace('alexa', '')
                    print(command)
            return command
        except:
            pass