pythonmodulespeech-recognitionpython-moduleassistant

Python isn't recognizing my speech to text in a way I can use it in if statements


I'm currently building a personal assistant using python, and I got it to work to a certain extent. I have been using this video tutorial. I am getting the assistant "harvey" to say all systems nominal, and to hear what i'm saying, repeat it back to me and print it in the command terminal, but once it needs to recognize the speech and compare it to if statements, it doesn't work and goes to the else statement.

my code is:

import datetime
import speech_recognition as sr 
import pyttsx3
import webbrowser
import wikipedia
import wolframalpha

#Speech Init
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[0].id) #0, male / 1, female
activationword = 'Harvey' #should be single word

def speak(text, rate = 120):
    engine.setProperty('rate', rate)
    engine.say(text)
    engine.runAndWait()

def ParseCommand():
    listener = sr.Recognizer()
    print('Listening for a command')
    
    with sr.Microphone() as source: #uses computer default mic
        listener.pause_threshold = 2
        input_speech = listener.listen(source)
    
    try:
        print("Understanding...")
        query = listener.recognize_google(input_speech, language='en_us')
        print(f'The input speech was: {query}')

    except Exception as exception:
        print("Excuse me?")
        speak('Excuse me?')

        print(exception)
        return 'None'
    
    return query

# Main Loop
if __name__ == '__main__':
    speak('All systems nominal.')

    while True:
        #Parse as a list
        print("Test 1 Succesful")
        query = ParseCommand().lower().split()
        print("Test 2 Succesful")
        verbal= "I heard", query[0], "is that correct?"
        speak(verbal)

        if query[0] == activationword:
            print("Test 3 Succesful")
            speak('Listening')
            query.pop(0)

            #list commands
            if query[0] == 'say':
                if 'hello' in query:
                    speak('Hello Sire, What can I do for you today')

                else:
                    query.pop(0) #Removes say from the list
                    speech = ''.join(query)
                    speak(speech)

        else:
            speak("Sorry sire I'm confused")

My guess is that the error occurs on query = ParseCommand().lower().split() or if query[0] == activationword:


Solution

  • It seems there are some problems in your code.

    1. case 1

    In the line engine.setProperty('voices', voices[0].id), the property should be 'voice', not 'voices'.

    1. case 2

    In the line query = ParseCommand().lower().split(), then all the elements of query will be in lower case. So you have to change activationword = 'Harvey', into activationword = 'harvey'

    Please check this and continue to developing.