Search code examples
pythonpython-3.xnumpyartificial-intelligencespeech-recognition

Python Attribute Error, not recocgnising object


Im trying to make a small chatbot, using speech recognition but my code keeps bringing up an attribut error

My code is supposed to begin once run;

this is Chatbot;

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
# Execute the AI
if __name__ == "__main__":
    ai = ChatBot(name="Dev")
#name of AI is codakai
# Execute the AI

A few lines later where the error apears

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

The error during debugging;

PS C:\Users\User\Desktop\New folder> & C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/User/Desktop/New folder/main.py"
----- starting up Dev -----
----- starting up Dev -----
Traceback (most recent call last):
  File "c:\Users\User\Desktop\New folder\main.py", line 34, in <module>
    ai.speech_to_text()
    ^^^^^^^^^^^^^^^^^
AttributeError: 'ChatBot' object has no attribute 'speech_to_text'

Here is the entire 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
# Execute the AI
if __name__ == "__main__":
    ai = ChatBot(name="Dev")
#name of AI is Dev
# Execute the AI

#speech recognition with microphone, it converts it to text
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")

def wake_up(self, text):
    return True if self.name in text.lower() else False

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

def wake_up(self, text):
    return True if self.name in text.lower() else False

from gtts import gTTS
import os
@staticmethod
def text_to_speech(text):
    print("AI --> ", text)
    speaker = gTTS(text=text, lang="en", slow=False)
    speaker.save("res.mp3")
    os.system("start res.mp3")  # windows use->start
    os.remove("res.mp3")

Solution

  • Your Indentation seems incorrect,

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

    The error is generated because the class chatbot does not have a method speech_to_text therefore an error occurs when ai(object of chatbot) calls the method