AttributeError: 'ChatBot' object has no attribute 'speech_to_text'

Question:

I started coding in Python today, and I tried following this tutorial (https://www.analyticsvidhya.com/blog/2021/10/complete-guide-to-build-your-ai-chatbot-with-nlp-in-python/) – you can find many other blogs with exactly the identical code.

import numpy as np
import speech_recognition as sr

# Beginning of the AI
class ChatBot():
    def __init__(self, name):
        print("----- starting up", name, "-----")
        self.name = name

def speech_to_text(self):
    recognizer = sr.Recognizer()
    with sr.Microphone() as mic:
         print("listening...")
         audio = recognizer.listen(mic)
    try:
         self.text = recognizer.recognize_google(audio)
         print("me --> ", self.text)
    except:
         print("me -->  ERROR")

However, when trying

if __name__ == "__main__":
     ai = ChatBot(name="Dev")
     while True:
         ai.speech_to_text()

the following error message is displayed:

AttributeError: 'ChatBot' object has no attribute 'speech_to_text'

If I inspect the ai with the Object explorer, there is no ‘speec_to_text’, so the error makes sense. However, I do not understand how to fix it.

If I set

ai.speech_to_text = speech_to_text(ai)

it works, but it seems wrong to me. All the websites do this the other way around, I don’t get it.

Asked By: Raphus

||

Answers:

That’s a intendation error actually you have to put the speech_to_text function inside of that class. like this

class ChatBot():
    def __init__(self, name):
        print("----- starting up", name, "-----")
        self.name = name

    def speech_to_text(self):
        recognizer = sr.Recognizer()
        with sr.Microphone() as mic:
            print("listening...")
            audio = recognizer.listen(mic)
        try:
            self.text = recognizer.recognize_google(audio)
            print("me --> ", self.text)
        except:
            print("me -->  ERROR")
Answered By: Vatsal
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.