基于智能机器人的在线答疑系统
说明:
通过pycharm实现的人工智能交互,采用torch,transformers用于训练
模型采用top k的解码方式,每次运行可能结果都略微有些不同。
设计思路:
- 加载训练后的模型:使用 AutoTokenizer 和 AutoModelForSeq2SeqLM 类加载预训练的模型和分词器。模型用于生成答案,分词器用于将输入文本进行分词和编码。
- 设定设备:根据可用的 GPU 环境,将模型放置在 GPU 或 CPU 上进行推理。
- 预处理和后处理:定义了两个辅助函数 preprocess 和 postprocess,用于在生成答案之前和之后对文本进行预处理和后处理的操作,例如替换特殊字符。4. answer_fn 函数:接收一个问题文本作为输入,并生成答案。根据设定的参数,使用模型生成答案文本。如果采样参数为 False,则使用束搜索算法生成答案;如果采样参数为 True,则使用采样算法生成答案。
- 使用python qt5画图连接函数以及通过mysql数据库的增删改查
工作原理:
- 输入一个问题文本。
- 将问题文本进行预处理,例如替换换行符。
- 使用分词器对预处理后的文本进行分词和编码,并转换为模型所需的输入格式。
- 使用模型生成答案文本。
- 对生成的答案文本进行后处理,例如去除特殊标记和句点。
- 返回最终的答案文本。
7.存入数据库
8.qt5展示
def answer_fn(text, sample=False, top_k=50):
'''sample:是否抽样。生成任务,可以设置为True;
top_p:0-1之间,生成的内容越多样、
'''
encoding = tokenizer(text=[text], truncation=True, padding=True, max_length=256, return_tensors="pt").to(device)
if not sample: # 不进行采样
out = model_trained.generate(**encoding, return_dict_in_generate=True, max_length=512, num_beams=4,temperature=0.5,repetition_penalty=10.0,remove_invalid_values=True)
else: # 采样(生成)
out = model_trained.generate(**encoding, return_dict_in_generate=True, max_length=512,temperature=0.6,do_sample=True,repetition_penalty=3.0 ,top_k=top_k)
out_text = tokenizer.batch_decode(out["sequences"], skip_special_tokens=True)
if out_text[0]=='':
return '我只是个语言模型,这个问题我回答不了。'
return postprocess(out_text[0])
from PyQt5.QtWidgets import QMainWindow,QMessageBox
import mysql.connector # 导入mysql.connector模块,用于连接MySQL数据库
from PyQt5.QtWidgets import QApplication
from 图形界面.登入界面 import Ui_widget
from main_MainWindow import ChildWindow_Ui_MainWindow
# 创建主窗口类
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# 创建窗口实例
self.ui = Ui_widget()
self.ui.setupUi(self)
def login(self):
conn=self.to_database()
cursor = conn.cursor()
# 获取 lineEdit 和 lineEdit_2 的值
username = self.ui.lineEdit.text()
password = self.ui.lineEdit_2.text()
# 查询数据库以检查账户是否存在
query = 'SELECT name, paw FROM user_info WHERE name=%s AND paw=%s'
cursor.execute(query, (username, password))
results = cursor.fetchone()
# 关闭游标和连接
cursor.close()
conn.close()
if results is not None:
# 账户存在
name = results[0]
paw = results[1]
if password == paw:
print(' # 密码匹配')
# 密码匹配
self.child_window = ChildWindow_Ui_MainWindow(name)
if self.child_window.isVisible():
self.child_window.hide()
else:
self.child_window.show()
self.close()
else:
# 密码不正确
QMessageBox.critical(self, "错误", "密码不正确")
else:
# 账户不存在
QMessageBox.critical(self, "错误", "账号不存在")
def clean(self):
self.ui.lineEdit.clear()
self.ui.lineEdit_2.clear()
def to_database(self):
# 连接到MySQL数据库
connec = mysql.connector.connect(
host="localhost",
user="root",
password="123456",
database="zhinengjiqiren"
)
return connec
if __name__ == '__main__':
# 创建应用程序实例
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
小小尝试,记录一下