from PyQt5 import QtCore, QtGui, QtWidgets
import sys,os,time
import requests
#http://www.tuling123.com/member/robot/2039679/center/frame.jhtml?page=0&child=0
#最新双模式 pip install pyQT5
import requests, json, time, random,os
import win32com.client
#pyinstaller -i luo.ico -F robot.py
from aip import AipSpeech
import datetime
import wave
import pyaudio
import numpy
import os
import time
def wave_data1(wf):
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
nframes = wf.getnframes()
framerate = wf.getframerate()
# 读取完整的帧数据到str_data中,这是一个string类型的数据
str_data = wf.readframes(nframes)
wf.close()
# 将波形数据转换为数组
# A new 1-D array initialized from raw binary or text data in a string.
wave_data = numpy.fromstring(str_data, dtype=numpy.short)
# 将wave_data数组改为2列,行数自动匹配。在修改shape的属性时,需使得数组的总长度不变。
wave_data.shape = -1, 2
# 将数组转置
wave_data = wave_data.T
# time 也是一个数组,与wave_data[0]或wave_data[1]配对形成系列点坐标
# time = numpy.arange(0,nframes)*(1.0/framerate)
# 采样点数,修改采样点数和起始位置进行不同位置和长度的音频波形分析
N = 44100
start = 0 # 开始采样位置
df = framerate / (N - 1) # 分辨率
freq = [df * n for n in range(0, N)] # N个元素
wave_data2 = wave_data[0][start:start + N]
return wave_data2
def record(time): #录音程序
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000 #百度语音接口只提供16000和8000两种采样率在此采样16000采样,如果要8000把下面shibie()第7行16000改成8000
RECORD_SECONDS =time
WAVE_OUTPUT_FILENAME = "output2.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* start recording")
print('此时你可以开始提问或者命令')
frames = []
for i in range(0,int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
def shibie1():
APP_ID = '17684903'
API_KEY = 'UNAmfUN8lMh5BYNnZgqrFnMc'
SECRET_KEY = '9snWx1NgQWHi5RpUnmYsTvrbusBLU60s'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
file_handle = open('output2.wav', 'rb')
file_content = file_handle.read()
result=client.asr(file_content, 'wav', 16000, {'dev_pid': '1936',})
#if result['err_no'] == 0:
# print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " >> " + result['result'][0])
#else:
# print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " >> " + "err_no:" + str(result['err_no']))
try:
answerlog = str(result['result'][0])
with open("wenzilog2.txt", "wt") as rbfile:
rbfile.write(answerlog)
except KeyError as key:
pass
finally:
begin = datetime.datetime.now()
while not os.path.exists('wenzilog2.txt'):
time.sleep(2)
end = datetime.datetime.now()
dur = end - begin
dur = dur.seconds
if dur == 6:
with open("wenzilog2.txt", "a") as wzfile:
wzfile.write('-')
global getrd
with open("wenzilog2.txt", "rt") as rdfile:
getrd = rdfile.read()
print(getrd)
#以上语音识别
#-----------------------------------------------------
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("智能聊天机器人")
Dialog.resize(602, 360) #602is width 360height
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(25, 1, 470, 30))
self.label.setStyleSheet("color: rgb(0, 0, 255);\n"
"font: 12pt \"黑体\";\n"
"text-decoration: ")
self.label.setObjectName("dialog")
self.plainTextEdit = QtWidgets.QPlainTextEdit(Dialog)
self.plainTextEdit.setGeometry(QtCore.QRect(20, 35, 530, 240))
self.plainTextEdit.setObjectName("plainTextEdit")
self.plainTextEdit_2 = QtWidgets.QPlainTextEdit(Dialog)
self.plainTextEdit_2.setGeometry(QtCore.QRect(20, 310, 401, 41))
self.plainTextEdit_2.setObjectName("plainTextEdit_2")
self.plainTextEdit.setStyleSheet("font: 12pt \"黑体\";\n")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(429, 320, 168, 33))
self.pushButton.setStyleSheet("font: 11pt \"黑体\";\n"
"background-color: rgb(0, 255, 0);")
self.pushButton.setObjectName("pushButton")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(20, 280, 54, 12))
self.label_2.setText("")
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(20, 280, 541, 16)) #541宽度 16高度 20 280为坐标位置
self.label_3.setStyleSheet("font: 75 12pt \"Aharoni\";")
self.label_3.setObjectName("label_3")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "聊天机器人-贝贝"))
self.label.setText(_translate("Dialog", "提供指令 上网 菜谱 记事本 计算式 音乐 新闻 截图 询问天气等"))
self.pushButton.setText(_translate("Dialog", "发文字or点我后说话"))
self.label_3.setText(_translate("Dialog", "输入框 填写输入指令后点击右侧按钮,或者不发文字直接点击绿按钮后说话."))
self.pushButton.clicked.connect(self.get_response)
def get_response(self):
try:
record(6) # 定义录音时间,单位/s
shibie1()
if not getrd == "-":
enterstr = getrd
else:
enterstr = self.plainTextEdit_2.toPlainText()
finally:
time.sleep(2)
os.remove('wenzilog2.txt')
os.remove('output2.wav')
#http://rogabet.xyz/
url = 'http://www.tuling123.com/openapi/api'
data = {
'key': "9bef20b25dbe435eb4d831b0d68f0368",
'info': enterstr,
'userid': "test",
}
r = requests.post(url, data=data).json()
result = ">> 我:{0}\n >> 贝贝:{1} \n".format(enterstr,r.get("text"))
if enterstr=='上网':
os.startfile(os.getcwd() + '\\ftqvpn.exe')
os.startfile(os.getcwd() + '\\start.htm')
if enterstr=='上网。':
os.startfile(os.getcwd() + '\\ftqvpn.exe')
os.startfile(os.getcwd() + '\\start.htm')
if enterstr == '菜谱' :
import webbrowser
play_url = 'https://m.xiachufang.com/'
webbrowser.open(play_url)
if enterstr == '菜谱。' :
import webbrowser
play_url = 'https://m.xiachufang.com/'
webbrowser.open(play_url)
if enterstr == '新闻':
import webbrowser
play_url = 'http://m.toutiao.com/search/'
webbrowser.open(play_url)
if enterstr == '新闻。':
import webbrowser
play_url = 'http://m.toutiao.com/search/'
webbrowser.open(play_url)
if enterstr == '音乐':
import webbrowser
play_url = 'https://music.163.com/'
webbrowser.open(play_url)
if enterstr == '音乐。':
import webbrowser
play_url = 'https://music.163.com/'
webbrowser.open(play_url)
if enterstr == '记事本':
#os.startfile(os.getcwd() + '\\notepad.exe')
os.startfile( 'notepad.exe') #没有getcwd,可以调用系统exe工具
if enterstr == '记事本。':
os.startfile( 'notepad.exe')
if enterstr == '截图。':
os.startfile( 'SnippingTool.exe')
if enterstr == '截图':
os.startfile( 'SnippingTool.exe')
self.plainTextEdit.setPlainText(result)
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak(r.get("text"))
return result
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
main = QtWidgets.QMainWindow()
mainwindow = Ui_Dialog()
mainwindow.setupUi(main)
main.show()
sys.exit(app.exec())