Python 语音识别和 Chatterbot

Python Speech Recognition and Chatterbot

我目前正在放学期间构建个人助理机器人作为挑战。我目前在整合 ChatterBot with a SpeechRecognition 时遇到问题。当我在同一个文件中调用两者时,我没有收到任何错误:

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()

但是,如果我将两者保存在两个不同的文件中,我会得到一个 AttributeError。我通过引发异常来避免程序崩溃,但这个异常意味着机器人实际上从未与用户交互。

下面是两个文件: 听

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!"

聊天:

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."

我不完全确定这是为什么,因为如果它们在同一个文件(第一段代码)中,它们都可以工作。但是,出于组织目的,我宁愿尽可能将这两个文件分开。

感谢您提供的任何想法和解决方案!

**编辑:**这是回溯错误(如果我在聊天中注释掉属性错误会出现):

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'

Chat.start() 没有 return chatbot,所以隐含的 returned 值是 None。尝试将 return chatbot 添加到 start() 的末尾。您也可以考虑制作自己的聊天机器人包装器 class,而不是使用模块并传递聊天机器人实例。