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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think you wanted to put the command = '' in the except block. It is an indentation error.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x