聊天机器人学习笔记-2-adapter

来源:互联网 发布:成语接龙查询软件 编辑:程序博客网 时间:2024/05/27 10:42

ChatterBot中的adapter介绍

ChatterBot中采用adapter模块以适用于不同类型的任务。该项目中使用到的adapter有4种,分别是storage adapters, input adapters, output adapters 和logic adapters。
storage adapters:提供连接不同存储系统( MongoDB 或者本地文件存储)的接口。
input adapters:提供以适用不同数据来源的输入接口
output adapters :提供应答接口
logic adapters:定义输入<—>应答的逻辑。

Storage Adapters

Storage adapter这一接口使得ChatterBot可以连接不同存储器后端。使用方式如下:

chatbot = ChatBot( "My ChatterBot", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter" )

Read Only Mode

只读模式。新建一个 chatterbot的时候设置 storage_adapter参数的时候,read_only=True ,当有输入数据到chatterbot的时候,数据库并不会发生改变。

Json Database Adapter

设置 storage_adapter的参数为chatterbot.adapters.storage.JsonDatabaseAdapter
JsonDatabaseAdapter是用以存储对话数据的接口,对话数据以Json格式进行存储。该 JSON Database adapter的使用需要额外一个额外的参数(database),如database=”./database.json”。这是因为该类型的adapter使用到了本地化的数据库文件。

Mongo Database Adapter

参数值=“chatterbot.adapters.storage.MongoDatabaseAdapter”
该类型adapter是以MongoDB database方式来存储对话数据。

database

该类型的adapter需要在新建ChatBot的时候额外设置database的值,
database=’chatterbot-database’

database_uri

当你需要远程连接到MongoDB实例时,需要再设置database_uri 的值,如下:database_uri=’mongodb://example.com:8100/’

Creating a new storage adapter

当采用自己设计的storage adapter,以连接数据库或者存储端的时候,在代码起始位置,需要自行创建一个继承于StorageAdapter(该类位于chatterbot.adapters.storage,是一个抽象类)的类。
举例如下:

from chatterbot.adapters import Adapterclass StorageAdapter(Adapter):    """    This is an abstract class that represents the interface    that all storage adapters should implement.    """    def __init__(self, **kwargs):        super(StorageAdapter, self).__init__(**kwargs)        self.kwargs = kwargs        self.read_only = kwargs.get("read_only", False)    def count(self):        """        Return the number of entries in the database.        """        raise self.AdapterMethodNotImplementedError()    def find(self, statement_text):        """        Returns a object from the database if it exists        """        raise self.AdapterMethodNotImplementedError()    def remove(self, statement_text):        """        Removes the statement that matches the input text.        Removes any responses from statements where the response text matches        the input text.        """        raise self.AdapterMethodNotImplementedError()    def filter(self, **kwargs):        """        Returns a list of objects from the database.        The kwargs parameter can contain any number        of attributes. Only objects which contain        all listed attributes and in which all values        match for all listed attributes will be returned.        """        raise self.AdapterMethodNotImplementedError()    def update(self, statement):        """        Modifies an entry in the database.        Creates an entry if one does not exist.        """        raise self.AdapterMethodNotImplementedError()    def get_random(self):        """        Returns a random statement from the database        """        raise self.AdapterMethodNotImplementedError()    def drop(self):        """        Drop the database attached to a given adapter.        """        raise self.AdapterMethodNotImplementedError()    def get_response_statements(self):        """        Return only statements that are in response to another statement.        A statement must exist which lists the closest matching statement in the        in_response_to field. Otherwise, the logic adapter may find a closest        matching statement that does not have a known response.        This method may be overridden by a child class to provide more a        efficient method to get these results.        """        statement_list = self.filter()        responses = set()        to_remove = list()        for statement in statement_list:            for response in statement.in_response_to:                responses.add(response.text)        for statement in statement_list:            if statement.text not in responses:                to_remove.append(statement)        for statement in to_remove:            statement_list.remove(statement)        return statement_list    class EmptyDatabaseException(Exception):        def __init__(self, value="The database currently contains no entries. At least one entry is expected. You may need to train your chat bot to populate your database."):            self.value = value        def __str__(self):            return repr(self.value)

Logic Adapters

Logic adapter直接决定了ChatterBot机器人的应答逻辑。通过在新建ChatBot的时候,设置logic_adapters的值,如下所示:

chatbot = ChatBot(    "My ChatterBot",    logic_adapters=[        "chatterbot.adapters.logic.ClosestMatchAdapter"    ])

注意,该类型的adapter是以集合形似进行添加的。

Closest Match Adapter

参数值设置为“chatterbot.adapters.logic.ClosestMatchAdapter”
ClosestMatchAdapter创建的应答结果是基于fuzzywuzzy处理类(字符串进行模糊匹配)的,该处理类通过提取与输入最近似的应答。该类型的adapter对输入语句所选择出来的应答结果,是通过对文本中的每条语句计算Levenshtein距离(又称为编辑距离,是指两个字符串之间,由一个转换成另一个所需的最少编辑操作次数),再选择出最接近已知匹配语句的结果。
注意,这里是基于已知对话和输入进行匹配计算的。

具体是如何操作的?

closest match algorithm是计算输入语句和已知的语句集合之间的相似性的。举个例子,语句1”where is the post office?”和语句2”looking for the post office”之间的相似性为65%。 closest match algorithm找出输入语句和已经所有语句出最高相似度,并将选择结果作为返回。

Closest Meaning Adapter

将参数值设置为chatterbot.adapters.logic.ClosestMeaningAdapter
该adapter的返回结果是基于比较输入语句的文本的标记化形式,用对每个潜在的匹配语句进行标记化。对于每个潜在的匹配,对每个语句的路径相似度(path similarity ),求其笛卡尔内积和,再做对比。该过程所进行的是一种同义词的模拟评估。对于能够和已知的语句计算获得最好的路径相似度,则返回结果。

本文的 closest meaning algorithm是基于nltk的WordNet Interface接口(http://www.nltk.org/howto/wordnet.html)来计算两个语句之间的相似度,而该相似度的计算又是基于每个语句中的表征或者标识的路径相似度。该方法本质上是做同义词的评估。对于输入的语句,在搜索已知文本中,如果该语句的同义词集合和输入语句之间的路径相似度最短,则返回。

Time Logic Adapter

参数设置为chatterbot.adapters.logic.TimeLogicAdapter
该adapter返回的是当前的时间。TimeLogicAdapter 是用以语句中涉及到时间提问的。
例如:
User: What time is it?
Bot: The current time is 4:45PM.

Mathematical Evaluation Adapter

参数值为chatterbot.adapters.logic.MathematicalEvaluation
该类adapter是用以输入语句中涉及到的数学运算。该模块的使用,主要有以下5个步骤:
1:输入规整。删除标点符号和其他无关的数据。
2:单词转为对应的数字
3:方程提取
4:简化方程
5:解方程和返回结果
该adapter对于输入的语句进行数学表达式是否存在的检测,若有则返回应答结果。该adapter能够处理单词和数字运算符的任意组合。
例如:
User: What is four plus four?
Bot: (4 + 4) = 8

Creating a new logic adapter

当自建 logic adapter的时候需要从 LogicAdapter(位于chatterbot.adapters.logic.LogicAdapter) 中继承,再按照自己的需求进行设计。同样,该父类也是一个抽象类,所以是所有logic adapter的抽象接口的。
例子如下:

from chatterbot.adapters.logic import LogicAdapterclass MyLogicAdapter(LogicAdapter):    def __init__(self, **kwargs):        """        The __init__ method is optional.        If you need to access any of the kwargs that were        passed into the ChatBot constructor this is where        you can do so.        (An API key might be an example of a parameter        you would want to access here.)        """    def can_process(self, statement):        """        This is a preliminary method that can be used to        check the input statement to see if a value can        possibly be returned when it is evaluated using        the adapter's process method.        This method returns true by default.        """        return True    def process(self, statement):        """        This method will receive the input statement.        Establish custom response selection logic here.        """        return selected_statement

Input Adapters

该类adapter是为了使ChatterBot能够拥有一个通用型的入口,以接收或者恢复来自于数据源的输入。
该adapter对于不同源的输入能够转为ChatterBot能够处理的格式。这个格式就是ChatterBot中conversation 模块中的 Statement

Variable input type adapter

参数值为chatterbot.adapters.input.VariableInputTypeAdapter
这个variable input type adapter是允许chatter bot接收不同类型的输入的,如 strings,dictionaries和Statements。

例子:

chatbot = ChatBot(    "My ChatterBot",    input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter")

Terminal adapter

输入adapter参数值为chatterbot.adapters.input.TerminalAdapter
该类adapter使得ChatterBot可以通过终端进行对话。

chatbot = ChatBot(    "My ChatterBot",    input_adapter="chatterbot.adapters.input.TerminalAdapter")

HipChat Adapter

对应的输入adapter的值为chatterbot.adapters.input.HipChat
该adapter使得ChatterBot 可以从HipChat聊天室获取输入语句,即可以通过HipChat 和 ChatterBot 进行对话。具体可以参考HipChat output adapter
hipchat的使用设置如下:

chatbot = ChatBot(    "My ChatterBot",    input_adapter="chatterbot.adapters.input.HipChat",    hipchat_host="https://mydomain.hipchat.com",    hipchat_room="my-room-name",    hipchat_access_token="my-hipchat-access-token",)

Speech recognition

至于语音识别模块,可以在chatterbot-voice 获取到更多信息。

Creating your own input adapter

对于输入adapter中的自行设计部分,设置的参数为chatterbot.adapters.input.InputAdapter
其需要基于抽象类Adapter(该类是一切输入adapter的抽象类)。同时,需要重写其中process_input 函数,并返回一个Statement对象。
此外,当有需要保留传递到chat bot构造函数中的kwarg参数时,可能需要根据自定义的adapter扩展init 函数。
自定义的例子如下:

from chatterbot.adapters import Adapterclass InputAdapter(Adapter):    """    This is an abstract class that represents the    interface that all input adapters should implement.    """    def process_input(self, *args, **kwargs):        """        Returns a statement object based on the input source.        """        raise self.AdapterMethodNotImplementedError()

Output Adapters

Output format adapter

参数值为chatterbot.adapters.output.OutputFormatAdapter
该类型的adapter下的返回结果是支持多种类型的,默认的返回是Statement对象。
目前支持三种输出格式分别是,text,json和object。
如果设置返回类型为text,则返回结果是string格式。
如果设置返回类型为json,则返回结果是dictionary格式。
如果设置返回类型为object,则返回结果是 Statement object。

例子:

chatbot = ChatBot(    "My ChatterBot",    output_adapter="chatterbot.adapters.output.OutputFormatAdapter",    output_format='text')

Terminal adapter

输出adapter也有终端模块。使用方法和输入adapter类似,如下:

chatbot = ChatBot(    "My ChatterBot",    output_adapter="chatterbot.adapters.output.TerminalAdapter")

HipChat Adapter

同样输出adapter也有和HipChat进行对接的功能。
对于的参数值chatterbot.adapters.output.HipChat
使用例子:

chatbot = ChatBot(    "My ChatterBot",    output_adapter="chatterbot.adapters.output.HipChat",    hipchat_host="https://mydomain.hipchat.com",    hipchat_room="my-room-name",    hipchat_access_token="my-hipchat-access-token",)

Mailgun adapter

Mailgun adapter允许 chat bot 基于Mailgun API进行邮件的发送。

from chatterbot import ChatBotfrom settings import MAILGUN'''To use this example, create a new file called settings.py.In settings.py define the following:MAILGUN = {    "CONSUMER_KEY": "my-mailgun-api-key",    "API_ENDPOINT": "https://api.mailgun.net/v3/my-domain.com/messages"}'''# Change these to match your own email configurationFROM_EMAIL = "mailgun@salvius.org"RECIPIENTS = ["gunthercx@gmail.com"]bot = ChatBot(    "Mailgun Example Bot",    mailgun_from_address=FROM_EMAIL,    mailgun_api_key=MAILGUN["CONSUMER_KEY"],    mailgun_api_endpoint=MAILGUN["API_ENDPOINT"],    mailgun_recipients=RECIPIENTS,    output_adapter="chatterbot.adapters.io.Mailgun",    storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",    database="../database.db")# Send an example email to the address providedresponse = bot.get_response("How are you?")print("Check your inbox at ", RECIPIENTS)

Speech synthesis

语音合成模块。这部门和输入adapter是一样的,参考chatterbot-voice

Creating your own output adapter

自定义的输出adapter和上述的自定义输入adapter类似。在这里直接给出下面例子:

from chatterbot.adapters import Adapterclass OutputAdapter(Adapter):    """    This is an abstract class that represents the    interface that all output adapters should implement.    """    def process_response(self, input_value):        """        Takes an input value.        Returns an output value.        """        raise self.AdapterMethodNotImplementedError()

adapter 默认 类型

默认情况下各个adapter的值如下:

bot = ChatBot(    "Elsie",    storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",    input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",    output_adapter="chatterbot.adapters.output.OutputFormatAdapter",    logic_adapters=[        "chatterbot.adapters.logic.ClosestMatchAdapter"    ],)

第三方的adapters

出于上文中提到的语音模块,还有chatterbot-weather作为一个logic adapter来对谈话中涉及到的当前天气进行回答。

备注:近期家里茶庄做中秋活动,有需要茶叶的程序猿可以微信onepieceand联系我,加我时,请备注“喝茶写代码”。
喝茶时间:
这里写图片描述

0 0