From 111dfaf20d7a4e354c87b48c565af25de87f0aad Mon Sep 17 00:00:00 2001 From: qwerlol123? <2082437969@qq.com> Date: Sat, 1 Jun 2024 23:19:37 +0800 Subject: [PATCH] 11\ --- AI聊天机器人.py | 149 +++++++++++++++++++++++++++++++++++++++++++ AiChatterbot.py | 108 ------------------------------- 2 files changed, 149 insertions(+), 108 deletions(-) create mode 100644 AI聊天机器人.py delete mode 100644 AiChatterbot.py diff --git a/AI聊天机器人.py b/AI聊天机器人.py new file mode 100644 index 0000000..708137e --- /dev/null +++ b/AI聊天机器人.py @@ -0,0 +1,149 @@ +import tkinter as tk + +import threading +import speech_recognition as sr +import requests +import pyttsx3 +from AiChatterbot import talkWithRobot, robotSay + +# Initialize speech synthesis object +talker = pyttsx3.init() + +# Initialize speech recognition object +recognizer = sr.Recognizer() + +userName = "admin" +userPass = "123" +# Create chat window +def chat_window(): + chat_window = tk.Tk() + chat_window.title("对话") + chat_window.geometry("800x400") + + def send_text_message(): + message = input_entry.get() + chat_text.insert(tk.END, "你: " + message + "\n") + response = get_response(message) + chat_text.insert(tk.END, "机器人: " + response + "\n") + input_entry.delete(0, tk.END) + # 语音合成回复并播放 + talker.say(response) + talker.runAndWait() + + def start_voice_recognition(chat_text): + with sr.Microphone() as source: + print("请说话...") + audio = recognizer.listen(source) + + try: + print("识别中...") + text = recognizer.recognize_google(audio, language="zh-CN") + print("你说: " + text) + + # 调用自然语言处理功能获取回复 + response = get_response(text) + + # 显示用户输入的消息和机器人的回复 + chat_text.insert(tk.END, "你: " + text + "\n") + chat_text.insert(tk.END, "机器人: " + response + "\n") + + # 语音合成回复并播放 + talker.say(response) + talker.runAndWait() + except sr.UnknownValueError: + print("抱歉, 未能识别,请重试") + + def send_voice_message(): + start_voice_recognition(chat_text) + + chat_frame = tk.Frame(chat_window) + chat_frame.pack(pady=10) + + chat_text = tk.Text(chat_frame) + chat_text.pack() + + input_entry = tk.Entry(chat_frame) + input_entry.pack(side=tk.LEFT, expand=True, fill=tk.BOTH) + + send_text_button = tk.Button(chat_frame, text="发送", command=send_text_message) + send_text_button.pack(side=tk.LEFT) + + send_voice_button = tk.Button(chat_frame, text="语音输入", command=start_voice_recognition) + send_voice_button.pack(side=tk.LEFT) + + chat_window.mainloop() + +# 启动聊天窗口 +# 创建登录窗口 +def login_window(): + login_window = tk.Tk() + login_window.title("登录") + + # 获取屏幕宽度和高度 + screen_width = login_window.winfo_screenwidth() + screen_height = login_window.winfo_screenheight() + + # 设置窗口居中 + window_width = 300 + window_height = 200 + x = (screen_width - window_width) // 2 + y = (screen_height - window_height) // 2 + login_window.geometry(f"{window_width}x{window_height}+{x}+{y}") + + def login(): + inputName = name_entry.get() + inputPass = pass_entry.get() + + if inputName == userName and inputPass == userPass: + talker.say("恭喜你登录成功!") + talker.runAndWait() + login_window.destroy() + chat_window() + else: + talker.say("账号或密码错误,登录失败") + talker.runAndWait() + + name_label = tk.Label(login_window, text="用户名:") + name_label.pack() + name_entry = tk.Entry(login_window) + name_entry.pack() + + pass_label = tk.Label(login_window, text="密码:") + pass_label.pack() + pass_entry = tk.Entry(login_window, show="*") + pass_entry.pack() + + login_button = tk.Button(login_window, text="登录", command=login) + login_button.pack() + + login_window.mainloop() +# 自然语言处理功能 +def get_response(message): + if "你好" in message: + return "你好,有什么可以帮助你的吗?" + elif "再见" in message: + return "再见,祝你一天愉快!" + else: + return "抱歉,我不明白你说的是什么。" + + +def send_message(): + # 获取用户输入的消息 + chat_text = tk.Text(chat_window) + chat_text.pack() + + input_entry = tk.Entry(chat_window) + input_entry.pack() + message = input_entry.get() + + # 显示用户输入的消息 + chat_text.insert(tk.END, "You: " + message + "\n") + + # 获取模型生成的回复 + response = get_response(message) + + # 显示模型生成的回复 + chat_text.insert(tk.END, "Bot: " + response + "\n") + +# 启动登录窗口 +login_window() \ No newline at end of file diff --git a/AiChatterbot.py b/AiChatterbot.py deleted file mode 100644 index 4f416e1..0000000 --- a/AiChatterbot.py +++ /dev/null @@ -1,108 +0,0 @@ -import time -import urllib -import wave -import urllib.parse -import requests -from pyaudio import PyAudio, paInt16 -from aip import AipSpeech -import pyttsx3 -from AI聊天机器人 import login_window,chat_window - -framerate = 16000 # 采样率 -num_samples = 2000 # 采样点 -channels = 1 # 声道 -sampwidth = 2 # 采样宽度2bytes -FILEPATH = 'D:/Tool/test/pythonProject6/myvoices.wav' #该文件目录要存在 - -#用于接收用户的语音输入, 并生成wav音频文件(wav、pcm、mp3的区别可详情百度) -class Speak(): - - #将音频数据保存到wav文件之中 - def save_wave_file(self, filepath, data): - wf = wave.open(filepath, 'wb') - wf.setnchannels(channels) - wf.setsampwidth(sampwidth) - wf.setframerate(framerate) - wf.writeframes(b''.join(data)) - wf.close() - - - # 进行语音录制工作 - def my_record(self): - pa = PyAudio() - # 打开一个新的音频stream - stream = pa.open(format=paInt16, channels=channels, - rate=framerate, input=True, frames_per_buffer=num_samples) - my_buf = [] # 存放录音数据 - - t = time.time() - print('正在讲话...') - - while time.time() < t + 5: # 设置录音时间(秒) - # 循环read,每次read 2000frames - string_audio_data = stream.read(num_samples) - my_buf.append(string_audio_data) - - - print('讲话结束') - self.save_wave_file(FILEPATH, my_buf) #保存下录音数据 - stream.close() - - -APP_ID = '73927317' -API_KEY = '3jGcj5fLma64CtB3tTEuLcei' -SECRET_KEY = 'qm8gPCF7DSKpqatx5ZQ8e4OvNLmgdYcG' # 此处填写自己的密钥 - -"""调用接口, 调用BaiDu AI 接口进行录音、语音识别""" -client = AipSpeech('73927317', '3jGcj5fLma64CtB3tTEuLcei', 'qm8gPCF7DSKpqatx5ZQ8e4OvNLmgdYcG') - - -class RobotSay(): - - def __init__(self): - # 初始化语音 - self.engine = pyttsx3.init() # 初始化语音库 - - # 设置语速 - self.rate = self.engine.getProperty('rate') - self.engine.setProperty('rate', self.rate - 50) - - def say(self, msg): - # 输出语音 - self.engine.say(msg) # 合成语音 - self.engine.runAndWait() - -class ReadWav(): - # 读取文件 - def get_file_content(self, filePath): - with open(filePath, 'rb') as fp: - return fp.read() - - def predict(self): - # 调用百度AI的接口, 识别本地文件 - return client.asr(self.get_file_content('D:/Tool/test/pythonProject6/myvoices.wav'), 'wav', 16000, { - 'dev_pid': 1537, - }) -def talkWithRobot(msg): - url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}'.format(urllib.parse.quote(msg)) - html = requests.get(url) - return html.json()["content"] - - -robotSay = RobotSay() -speak = Speak() -readTalk = ReadWav() -while True: - - speak.my_record() #录音 - - text = readTalk.predict()['result'][0] #调用百度AI接口, 将录音转化为文本信息 - - print("本人说:", text) #输出文本信息 - response_dialogue = talkWithRobot(text) #调用青云客机器人回答文本信息并返回 - print("青云客说:", response_dialogue) #输出回答文本信息 - - robotSay.say(response_dialogue) #播放回答信息 - -readWav = ReadWav() # 实例化方法 -print(readWav.predict()) \ No newline at end of file