如何使用pickle保存聊天机器人模型

2024-01-26

我创建了一个Chatbot using 聊天机器人 and tkinter图书馆。 但每当我打开文件时它就会启动训练模型并且需要花费很多时间,因此我搜索并找到了解决方案泡菜模块。但现在我也尝试了 pickle 它不起作用并显示错误。

有什么办法可以挽救model这不会每次都开始训练。这是我的代码

import chatterbot
import pickle
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
import tkinter as tk
try:
    import ttk as ttk
    import ScrolledText
except ImportError:
    import tkinter.ttk as ttk
    import tkinter.scrolledtext as ScrolledText
import time


class TkinterGUIExample(tk.Tk):

    def __init__(self, *args, **kwargs):
        """
        Create & set window variables.
        """
        tk.Tk.__init__(self, *args, **kwargs)

        self.chatbot = ChatBot(
            "GUI Bot",

            storage_adapter="chatterbot.storage.SQLStorageAdapter",
            logic_adapters=[{
                'import_path': 'chatterbot.logic.BestMatch',
                'default_response': 'I am sorry, but I do not understand.',
                'maximum_similarity_threshold': 0.80
} ]



        )



        for files in os.listdir('C:/Users/HP/Desktop/FYP BOT/training_data/'):
            con=open('C:/Users/HP/Desktop/FYP BOT/training_data/'+files,'r').readlines()
            trainer = ListTrainer(self.chatbot)
            trainer.train(con)
        self.title("Chatterbot")

        self.initialize()

    def initialize(self):
        """
        Set window layout.
        """
        self.grid()

        ttk.Style().configure("TButton", padding=6, relief="flat",background="#ccc")
        style = ttk.Style()
        style.map("C.TButton",
            foreground=[('pressed', 'red'), ('active', 'blue')],
            background=[('pressed', '!disabled', 'black'), ('active', 'white')]
            )


        self.respond = ttk.Button(self, text='Get Response',cursor='hand2' ,command=self.get_response)
        self.respond.grid(column=1, row=2, sticky='nesw', padx=3, pady=10)




        self.usr_input = tk.Entry(self, state='normal',text='Enter your query here!')
        self.usr_input.grid(column=0, row=2, sticky='nesw', padx=1, pady=5)

        #Binding entry
        self.usr_input.bind('<Return>',self.get_response)


        self.conversation_lbl = tk.Label(self,
                                         text='English',
                                         anchor='center',
                                         font=('Arial Bold ',18),
                                         bg="#3a8fc5",
                                         fg="white")
        self.conversation_lbl.grid(column=0, row=0,columnspan=2, padx=3, pady=3,sticky='news')
        self.conversation = ScrolledText.ScrolledText(self,
                                                      state='disabled',borderwidth=5,
                                                      highlightthickness=1,
                                                      bg='#15202b',fg='#16202A',
                                                      font=('Arial Bold',8))

        self.conversation.grid(column=0, row=1, columnspan=2, sticky='nesw', padx=3, pady=3)


    def get_response(self,*args):
        """
        Get a response from the chatbot and display it.
        """
        user_input = self.usr_input.get()
        self.usr_input.delete(0, tk.END)

        response = self.chatbot.get_response(user_input)

        self.conversation['state'] = 'normal'
        '''----------------------------------------------
        self.conversation.tag_configure('tag-left', justify='left')
        self.conversation.insert('end',"Human: " + user_input + "\n", 'tag-left')

        self.conversation.tag_configure('tag-left', justify='right')
        self.conversation.insert('end',"ChatBot: " + str(response.text) + "\n\n\n", 'tag-right')'''

        label1 = tk.Label(self.conversation, 
                          text="Human: \n"+user_input, 
                          background='#3B5566',
                          fg='white',
                          font=("Helvetica", 12),
                          justify='left',
                          wraplength=300,
                          anchor='w',
                          padx=10, pady=5)
        label2 = tk.Label(self.conversation, 
                          text="ChatBot: \n"+str(response.text),
                          wraplength=300,
                          anchor='w',
                          background='#1D9DFC', 
                          fg='white',
                          font=("Helvetica", 12),
                          justify='left',
                          padx=10, pady=5)

        self.conversation.tag_configure('tag-left', justify='left')
        self.conversation.tag_configure('tag-right', justify='right')


        self.conversation.insert('end', '\n\n\n')
        self.conversation.window_create('end', window=label1)

        self.conversation.insert('end', '\n\n\n ', 'tag-right') # space to move Label to the right 
        self.conversation.window_create('end', window=label2)

        '''self.conversation.insert(
            tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n\n\n"
        )'''
        self.conversation['state'] = 'disabled'

        time.sleep(0.2)

gui_example = TkinterGUIExample()
gui_example.attributes('-topmost', True)
gui_example.update()
gui_example.attributes('-topmost', False)
gui_example.geometry('810x550+460+100')
gui_example.resizable(0, 0)
gui_example.configure(background='#3a8fc5')
gui_example.mainloop()

我也创造了.exi文件,但它也开始训练,所以有什么方法可以保存它而不出错,当我在主窗口中调用这个脚本时,这个脚本开始工作而不是训练等。


你可以试试这个。这对我有用。当代码第一次运行时trainer = ChatterBotCorpusTrainer(bot) and trainer.train("static/chatterbot_data.yml")用于训练机器人。它将生成一个文件database.db在项目文件夹中。生成数据库文件后,如果语料库不再发生任何更改,则注释下面的最后两行代码即可运行而无需重新训练。

Code:

## initialize chatter bot
bot = ChatBot(
    'robot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    preprocessors=[
        'chatterbot.preprocessors.clean_whitespace',
    ],
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.BestMatch',
            'default_response': 'I am sorry, but I do not understand.',
            'maximum_similarity_threshold': 0.90,
            'statement_comparison_function': chatterbot.comparisons.levenshtein_distance,
            'response_selection_method': chatterbot.response_selection.get_first_response
        },
        'chatterbot.logic.MathematicalEvaluation'
    ],
    database_uri='sqlite:///database.db',
    read_only=True
)


## training corpus list
## Disable these two lines below AFTER first run when a *.db file is generated in project directory
trainer = ChatterBotCorpusTrainer(bot)
trainer.train("static/chatterbot_data.yml")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用pickle保存聊天机器人模型 的相关文章

随机推荐

  • 就地对 Perl 数组进行排序

    我有一个对数组的引用 称为 intervals 我想对这个数组中的值进行排序 数组中可能有大量值 所以我不想复制这些值 我目前的做法是这样的 sub by position a gt start lt gt b gt start a gt
  • React Hooks:如何在渲染之前等待数据被获取

    我在 useEffect 挂钩中有 fetch 方法 export const CardDetails gt const card getCardDetails useState const id useParams useEffect g
  • ResponseEntityExceptionHandler 针对 401 异常返回空响应正文

    我正在尝试使用 RestTemplate 实现对身份验证服务器的 Rest 调用 并记录响应 以防服务器返回异常 为了做到这一点 我使用 ResponseEntityExceptionHandler 来处理 HttpClientErrorE
  • R 中的掩码电话号码

    我的原始数据有很多个人信息 所以我在R中屏蔽它们 示例数据和我的原始代码如下 install packages stringr library string x c 010 1234 5678 John 010 8888 8888 Phon
  • Node JS:异步执行命令行并获取输出

    我如何运行命令行并尽快获取输出以将其显示在某处 例如 如果在 Linux 系统上运行 ping 命令 它永远不会停止 现在是否可以在命令仍在处理时获得响应 或者让我们采取apt get install命令 如果我想在安装运行时显示安装进度怎
  • If 语句内部和外部的 Return

    这可能是一个相当容易回答的问题 但它已经困扰我一段时间了 如果 if 语句内有一个 return 语句 在一个方法内 在 Java 语言中 但我在末尾添加另一个作为包罗万象并避免错误 则两个返回值都将在其他 if if 语句为真 一个例子
  • 我如何在Python中只向下舍入数字/浮点数?

    我将生成这个随机数 例如 12 75 或 1 999999999 或 2 65 我希望始终将此数字向下舍入为最接近的整数 因此 2 65 将四舍五入为 2 抱歉 我问了很多遍 但没有找到答案 谢谢 您可以选择我们int math trunc
  • org.bson.BSONObject 中的 java 类型

    我目前正在学习mongodb 的 BSON java 库 http github com mongodb mongo java driver 我正在尝试改变org bson BSONObject到 XML 中 以便将其转换为XSLT样式表
  • 在solr中搜索特殊字符

    我在 solr 中搜索特殊字符时遇到问题 我的文档有一个 标题 字段 有时它可能像 泰坦尼克号 1999 它有字符 当我尝试使用 在 solr 中搜索时 我收到 400 错误 我试图转义这个字符 所以我尝试了 和 之类的东西 经过这些更改
  • C# 中使用掩码进行位操作

    我需要一些有关 C 中位图操作的帮助 我想要一个UInt16 隔离任意数量的位 并使用另一个位设置它们UInt16 value Example 10101010 Original Value 00001100 Mask Isolates b
  • Android将图片旋转90度(相机拍摄)[重复]

    这个问题在这里已经有答案了 我正在通过代码在我的 Samsung Galaxy SII 设备中拍照 保存并在屏幕上显示它后 我看到它旋转了 90 度 我知道这是一些设备问题 并非所有设备上都会发生这种情况 我正在使用给定的相机意图拍照并将其
  • Apollo 客户端什么是主动查询?

    My Setup Typescript 反应应用程序 后端 GraphQL API 阿波罗客户端 使用 Apollo 客户端 Devtools 扩展进行检查 我的问题 什么是主动查询 Apollo 文档谈论了很多主动查询 但我很难得到一个实
  • 如果填充了另一个字段,则 MVC 3 字段为必填字段

    我有一个简单的问题 例如 我有两个字段映射在模型 ex 上 textbox 1 和 textbox 2 我想问是否存在一种方法 前强制装饰器 仅当我填充 textbox 1 时才强制执行 textbox 2 如果我不填写textbox 1
  • iPhone 在 CoreData 保存时崩溃

    这是一个不同的情况这个问题 https stackoverflow com questions 1230858 iphone core data crashing on save 因为提供的解决方案不起作用并且堆栈不同 当我使用 cored
  • 从 HttpResponseMessage 获取 Excel 文件

    我正在开发一个 ASP NET Core 2 2 项目 我需要使用浏览器下载 Excel 但是当我执行请求时 我只得到一些 Json 我的 Excel 在流中 并且流不为空 这是我的代码 HttpResponseMessage messag
  • 为什么 requestWhenInUseAuthorization 不提示用户访问该位置?

    In my viewDidLoad我有的方法 locationManager CLLocationManager alloc init initializing locationManager locationManager delegat
  • 是否有 DCC32 选项将特定编译器警告视为错误?

    对于命令行构建 我想将警告 例如 构造包含抽象方法的实例 视为错误 我在 Delphi 2009 中没有找到用于此目的的 dcc32 命令行选项 有没有办法 例如使用 dcc32 cfg 来执行此操作 像这样 dcc32 W CONSTRU
  • 获取 QPixmap 的哈希值的最佳方法是什么?

    我正在使用 Qt 4 5 开发一个图形应用程序 并将图像放入 QPixmapCache 中 我想对此进行优化 以便如果用户插入已经在缓存中的图像 它将使用该图像 现在 每个图像都有一个唯一的 ID 有助于在绘制事件时优化自身 但是我意识到
  • PHP 中 error_log() 中的换行符

    如何在使用时插入换行符error log in PHP 我尝试使用 br and n 但那些没有用 添加错误消息时使用双引号 error log This is a two lined message nThis is line two 应
  • 如何使用pickle保存聊天机器人模型

    我创建了一个Chatbot using 聊天机器人 and tkinter图书馆 但每当我打开文件时它就会启动训练模型并且需要花费很多时间 因此我搜索并找到了解决方案泡菜模块 但现在我也尝试了 pickle 它不起作用并显示错误 有什么办法