#网页自动化函数
def web_open(result):
'''
:param result: 搜索框输入内容
'''
driver = webdriver.Firefox()
driver.get(result)
在上篇博文中提到,项目机器人提供高校查询板块,高校查询板块实现的具体方式为用户输入通过一系列处理匹配至特定高校,数据库中提取出高校对应的网址,利用python的网页自动化操作,打开特定网页供用户浏览和查询。
#声音录制设置
CHUNK = 1024
FORMAT = pyaudio.paInt16 # 16位深
CHANNELS = 1 #1是单声道,2是双声道。
RATE = 16000 # 采样率,调用API一般为8000或16000
RECORD_SECONDS = 10 # 录制时间10s
#录音文件保存路径
def save_wave_file(pa, filepath, data):
wf = wave.open(filepath, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(pa.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b"".join(data))
wf.close()
#录音主体文件
def get_audio(filepath,isstart):
'''
:param filepath:文件存储路径('test.wav')
:param isstart: 录音启动开关(0:关闭 1:开启)
'''
if isstart == 1: # 录音启动开关为1,开始录音
pa = pyaudio.PyAudio()
stream = pa.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK) # 读取chunk个字节 保存到data中
frames.append(data) # 向列表frames中添加数据data
stream.stop_stream()
stream.close() # 停止数据流
pa.terminate() # 关闭PyAudio
#写入录音文件
save_wave_file(pa, filepath, frames)
elif isstart == 0: # 录音启动开关为0,退出函数
exit()
#获得录音文件内容
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
#百度语音识别编码
APP_ID = '********'
API_KEY = '************************'
SECRET_KEY = '********************************' # 百度智能云官网申请,此处换为自己的API接口
#语音模块主体函数
def speech_record(isstart):
'''
:param isstart: 录音启动开关(0:关闭 1:开启)
:return: sign:是否获取到声音信号(0:未获取 1:获取到)
result_out:返回识别的语义信息(none为未获取到语音信息)
'''
sign =1 # 初始化录音启动开关
result_out = "" # 初始化内容字符串
filepath = 'test.wav'
get_audio(filepath,isstart)
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result = client.asr(get_file_content('test.wav'), 'wav',16000,{'dev_pid': 1537,})
if 'result' not in result.keys(): # 返回字典中并无"result"的key值
sign = 0
result_out = None
elif result['result'] == ['']: # 返回字典中"result"的value值为空
sign = 0
result_out = None # 上述两种模式均未获得任何内容,返回为空none
else:
result_out = "".join(result['result'])
return [sign,result_out]
#语音播报函数
def speech_read(result):
'''
:param result:待朗读字符串
:return: 无返回None
'''
# 模块初始化
engine = pyttsx3.init()
# print('准备开始语音播报...')
engine.say(result)
# 等待语音播报完毕
engine.runAndWait()
代码实现:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'robot.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(140, 60, 501, 221))
self.groupBox.setObjectName("groupBox")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(10, 30, 72, 15))
self.label.setObjectName("label")
self.textBrowser = QtWidgets.QTextBrowser(self.groupBox)
self.textBrowser.setGeometry(QtCore.QRect(10, 60, 471, 31))
self.textBrowser.setObjectName("textBrowser")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(410, 130, 72, 15))
self.label_2.setObjectName("label_2")
self.textBrowser_2 = QtWidgets.QTextBrowser(self.groupBox)
self.textBrowser_2.setGeometry(QtCore.QRect(15, 170, 471, 31))
self.textBrowser_2.setObjectName("textBrowser_2")
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_2.setGeometry(QtCore.QRect(140, 330, 501, 181))
self.groupBox_2.setObjectName("groupBox_2")
self.textEdit = QtWidgets.QTextEdit(self.groupBox_2)
self.textEdit.setGeometry(QtCore.QRect(10, 30, 481, 87))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(self.groupBox_2)
self.pushButton.setGeometry(QtCore.QRect(260, 140, 93, 28))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox_2)
self.pushButton_2.setGeometry(QtCore.QRect(390, 140, 93, 28))
self.pushButton_2.setObjectName("pushButton_2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.groupBox.setTitle(_translate("MainWindow", "聊天界面"))
self.label.setText(_translate("MainWindow", "机器人:"))
self.label_2.setText(_translate("MainWindow", "交流者:"))
self.groupBox_2.setTitle(_translate("MainWindow", "发送界面"))
self.pushButton.setText(_translate("MainWindow", "发送"))
self.pushButton_2.setText(_translate("MainWindow", "取消"))
利用python制作图形化用户交互界面主要有两种方式---(1)tinker(2)pyqt 由于pyqt实现图形化用户交互界面比tinker更加简洁高效,因此本项目中利用pyqt制作图形化用户交互界面。 代码展示:
#程序运行主函数
if __name__ == '__main__':
#贝叶斯分类器训练
train_data_apply = jieba_text(train_data)[1]
train_label_apply = jieba_text(train_label)[0]
train_array = tf_idf(train_data_apply,['你好'])[0]
model_apply = bayes_model(train_array,train_label_apply)
#起始播报
greeting1 = '你好,我是智能机器人zz,我可以陪你聊天,也可以帮助您查询院校信息'
greeting2 = '让我们开始聊天吧'
speech_read(greeting1)
speech_read(greeting2)
#主循环
while True:
a = speech_record(1)
print(a)
if a[0] == 0:
sph = '你还在吗?我走啦'
speech_read(sph)
speech_record(0)
break
elif a[0] == 1:
similarity = fuzz.ratio(a[1], "拜拜")
if similarity > 50:
reply = '今天和你聊的很开心,再见啦,拜拜'
speech_read(reply)
speech_record(0)
break
else:
input_list = jieba_text(a[1])[1]
input_apply = tf_idf(train_data_apply,input_list)[1]
value = model_apply.predict(input_apply)
if value == [' A ']:
reply = get_greeting(a[1],question_greeting,answer_greeting)
if reply == None:
reply_none = 'zz才疏学浅,对主人的问题无能为力'
speech_read(reply_none)
else:
speech_read(str(reply))
if value == [' B ']:
reply = get_greeting(a[1],question_dataset,answer_dataset)
if reply == None:
reply_none = 'zz才疏学浅,对主人的问题无能为力'
speech_read(reply_none)
else:
speech_read('我为你找到以下内容,你可以在本网页上查询院校信息')
web_open(str(reply))
break
在语音交互模式中,项目机器人最大程度模仿人与人之间对话交流的场景,用户通过语音与智能机器人完成交互。代码展示:
#贝叶斯分类器训练
train_data_apply = jieba_text(train_data)[1]
train_label_apply = jieba_text(train_label)[0]
train_array = tf_idf(train_data_apply,['你好'])[0]
model_apply = bayes_model(train_array,train_label_apply)
def on_click(self):
text_1 = ui.textEdit.toPlainText() # 用户输入
ui.textBrowser_2.setText(text_1)
input_list = jieba_text(text_1)[1]
input_apply = tf_idf(train_data_apply, input_list)[1]
value = model_apply.predict(input_apply)
if value == [' A ']:
reply = get_greeting(text_1, question_greeting, answer_greeting)
if reply == None:
reply_none = 'zz才疏学浅,对主人的问题无能为力'
ui.textBrowser.setText(reply_none)
else:
ui.textBrowser.setText(str(reply))
if value == [' B ']:
reply = get_greeting(text_1, question_dataset, answer_dataset)
if reply == None:
reply_none = 'zz才疏学浅,对主人的问题无能为力'
ui.textBrowser.setText(reply_none)
else:
ui.textBrowser.setText('我为你找到以下内容,你可以在本网页上查询院校信息')
web_open(str(reply))
def off_click(self):
ui.textEdit.clear()#清除聊天框内容的操作
app = QtWidgets.QApplication([])
window = QtWidgets.QMainWindow()
ui = robot.Ui_MainWindow()
ui.setupUi(window) # 启动运行
ui.pushButton.clicked.connect(on_click)
ui.pushButton_2.clicked.connect(off_click)
window.show() # 显示窗口
app.exec()
图形化用户交互界面与语音交互实现模式类似,仅仅将语音模式中的语音输入输出转换为文字输入输出。