Home > other >  AttributeError: 'ChatBot' object has no attribute 'speech_to_text'
AttributeError: 'ChatBot' object has no attribute 'speech_to_text'

Time:08-21

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.

CodePudding user response:

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")
  • Related