TobyTobyo
TobyTobyo

Reputation: 405

Python Speech Recognition and Chatterbot

I am currently building a personal assistant bot as a challenge while I am on school break. I am currently having trouble integrating ChatterBot with a SpeechRecognition. When I call both in the same file, I don't get any errors:

import speech_recognition as sr
from chatterbot import ChatBot

def setup():
    chatbot = ChatBot(
        'Ron Obvious',
        trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
    )

    # Train based on the english corpus
    chatbot.train("chatterbot.corpus.english")
    while True:
        get_response(chatbot)

def get_response(chatbot):
    # Get a response to an input statement
    speech = return_audio()
    print chatbot.get_response(speech)

def return_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
    try:
        speech = r.recognize_google(audio)
        try:
            speech = str(speech)
            print speech
            return speech
        except TypeError:
            print "Error! Could not convert speech to string!"
    except sr.UnknownValueError:
        print "Error! Could not process that audio."
        return "Error!"
    except sr.RequestError as e:
        print "Error! No internet connection to Google Sound Recognizer."
        return "Error!"

setup()

However, if I keep the two in two different files, I get an AttributeError. I get around the program crashing by having it raise an exception, but this exception means that the bot never actually interacts with the user.

Bellow are the two files: Listen

import speech_recognition as sr
from chatterbot import ChatBot

import Messanger_Alert as MA
import Weather
import Email_Alert
import Chat
import Run


def start():
    bot = Chat.start()
    MA_client = MA.login()
    print "Hello Luke!"
    print "I am ready for your command! :D"
    while True:
        speech = str(return_audio())
        if not speech:
            print "Error! Speech returned nonetype!"
            continue
        else:
            try:
                if any(word in speech for word in ("Jason", "jason")): #Old key words: "SysGen", "Sysgen", "System", "system" - will reimpliment if needed
                    if any(word in speech for word in ("Message", "message", "Messenger", "messenger", "Facebook", "facebook")):
                        if any(word in speech for word in ("Send", "send")):
                            MA.send_message(MA_client) #now getting an attribute error.
                            print "Ready for next command!"
                        elif any(word in speech for word in ("Search Friend", "search friend", "Seach friend", "search Friend", "friend", "Friend", "friends", "Friends")):
                            MA.friend_search(MA_client)
                            print "Ready for next command!"
                        elif any(word in speech for word in ("Check", "check")):
                            MA.check_message(MA_client)
                            print "Ready for next command!"
                    elif any(word in speech for word in ("Email", "email")):
                        if any(word in speech for word in ("Personal", "personal", "Home", "home")):
                            Email_Alert.login1()
                            print "Ready for next command!"
                        elif any(word in speech for word in ("School", "school", "Dorm", "dorm", "UCSD", "ucsd")):
                            Email_Alert.login2()
                            print "Ready for next command!"
                    elif any(word in speech for word in ("Weather", "weather", "Forecast", "forecast")):
                        Weather.decide()
                    elif any(word in speech for word in ("Goodnight", "goodnight", "Bye", "bye", "Goodbye", "goodbye")):
                        print "Goodnight Luke!"
                        exit()
                    else:
                        Chat.talk(bot, speech)
                elif speech == "Error!":
                    return_audio()
                else:
                    Chat.talk(bot, speech)
            except sr.UnknownValueError:
                print "Error! Could not process that audio."
            except sr.RequestError as e:
                print "Error! No internet connection to Google Sound Recognizer."


def return_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
    try:
        speech = r.recognize_google(audio)
        try:
            speech = str(speech)
            print speech
            return speech
        except TypeError:
            print "Error! Could not convert speech to string!"
    except sr.UnknownValueError:
        print "Error! Could not process that audio."
        return "Error!"
    except sr.RequestError as e:
        print "Error! No internet connection to Google Sound Recognizer."
        return "Error!"

Chat:

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os.path

import Listen

def start():
    file_list = ["Jason_logs.txt", "Sample1.txt"]
    chatbot = ChatBot('Jason', trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
    for path in file_list:
        if os.path.exists(path) == "True":
            train_from_text(chatbot, path)
    train_bot(chatbot)

def train_from_text(chatbot, path):
    conversation = []
    with open(path, 'r') as f:
        while True:
            line1 = f.readline()
            line2 = f.readline()
            if not line2:
                break
            else:
                conversation.append(line1)
                conversation.append(line2)
    chatbot.set_trainer(ListTrainer)
    chatbot.train(conversation)

def train_bot(chatbot):
    # Train based on the english corpus
    chatbot.train("chatterbot.corpus.english")
    # Train based on english greetings corpus
    chatbot.train("chatterbot.corpus.english.greetings")
    # Train based on the english conversations corpus
    chatbot.train("chatterbot.corpus.english.conversations")

def talk(chatbot, entry):
    try:
        response = chatbot.get_response(str(entry))
        print response
        with open("Jason_logs.txt", "a") as f:
            f.write(entry)
            f.write(response)
    except TypeError:
        print "Error! Could not convert speech to string!"
    except AttributeError:
        print "Error! Speech not accepted by Jason's Chatterbot libraries."

I'm not completely sure why this is because they both work if they are in the same file (the first chunk of code). However, for organizational purposes, I'd rather keep the two files separate if possible.

Thanks for any ideas and solutions you might be able to give!

**Edit: ** Here is the traceback error (which arises if I comment out the attribute error in Chat):

Traceback (most recent call last):
  File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 24, in <module>
    startup()
  File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 13, in startup
    voice()
  File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 19, in voice
call Jason
    Listen.start()
  File "C:\Users\lukec\PycharmProjects\Sysgen_AI\Listen.py", line 47, in start
    Chat.talk(bot, speech)
  File "C:\Users\lukec\PycharmProjects\Sysgen_AI\Chat.py", line 39, in talk
    response = chatbot.get_response(str(entry))
AttributeError: 'NoneType' object has no attribute 'get_response'

Upvotes: 1

Views: 2901

Answers (1)

kitti
kitti

Reputation: 14834

Chat.start() does not return chatbot, so the implicitly returned value is None. Try adding return chatbot to the end of start(). You might also look into making your own chatbot wrapper class, rather than using a module and passing around chatbot instances.

Upvotes: 1

Related Questions