You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

238 lines
8.5 KiB

6 months ago
import pymysql
6 months ago
import time
import wave
import requests
from pyaudio import PyAudio, paInt16
from aip import AipSpeech
import pyttsx3
from tkinter import *
from tkinter import messagebox
import speech_recognition as sr
6 months ago
from tkinter import Text, Scrollbar, Entry, Button
6 months ago
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
# Constants for audio recording
framer = 16000 # Sample rate
num_samples = 2000 # Sample points
channels = 1
sampwidth = 2
6 months ago
audio_file = 'myvoices.wav' # Specify the path to save the recorded audio file
6 months ago
APP_ID = '73927317'
API_KEY = '3jGcj5fLma64CtB3tTEuLcei'
SECRET_KEY = 'qm8gPCF7DSKpqatx5ZQ8e4OvNLmgdYcG' # Add your own API credentials here
# Class for handling audio recording and saving
class Speak():
def save_wave_file(self, filepath, data):
wf = wave.open(filepath, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framer)
wf.writeframes(b''.join(data))
wf.close()
def my_record(self):
pa = PyAudio()
stream = pa.open(format=paInt16, channels=channels, rate=framer, input=True, frames_per_buffer=num_samples)
6 months ago
my_buf = []
t_end = time.time() + 5
6 months ago
print('Speak now...')
while time.time() < t_end:
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('Recording ended')
6 months ago
self.save_wave_file(audio_file, my_buf)
6 months ago
stream.close()
6 months ago
client = AipSpeech('73927317', '3jGcj5fLma64CtB3tTEuLcei', 'qm8gPCF7DSKpqatx5ZQ8e4OvNLmgdYcG')
6 months ago
class RobotSay():
def __init__(self):
6 months ago
self.engine = pyttsx3.init()
6 months ago
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):
return client.asr(self.get_file_content('myvoices.wav'), 'wav', 16000, {
'dev_pid': 1537,
})
6 months ago
# 定义登录窗口
6 months ago
class LoginWindow:
def __init__(self, master):
self.master = master
self.master.title("登录")
self.master.geometry("300x200")
# Center align the login window
self.screen_width = self.master.winfo_screenwidth()
self.screen_height = self.master.winfo_screenheight()
self.x_pos = (self.screen_width - 300) // 2
self.y_pos = (self.screen_height - 200) // 2
self.master.geometry(f"300x200+{self.x_pos}+{self.y_pos}")
self.label_username = Label(master, text="账号")
self.label_username.pack()
self.entry_username = Entry(master)
self.entry_username.pack()
self.label_password = Label(master, text="密码")
self.label_password.pack()
self.entry_password = Entry(master, show="*")
self.entry_password.pack()
self.button_login = Button(master, text="登录", command=self.login)
self.button_login.pack()
def login(self):
username = self.entry_username.get()
password = self.entry_password.get()
if username == "123" and password == "123":
messagebox.showinfo("登陆成功", "恭喜你登陆成功")
self.open_chat_window()
else:
messagebox.showerror("登录失败", "无效的用户名或密码")
def open_chat_window(self):
6 months ago
self.master.withdraw()
chat_root = Toplevel(self.master)
chat_window = ChatWindow(chat_root)
chat_root.protocol("WM_DELETE_WINDOW", self.master.quit)
6 months ago
class ChatWindow:
def __init__(self, master):
self.master = master
self.master.title("开始聊天")
self.master.geometry("700x500")
6 months ago
self.screen_width = self.master.winfo_screenwidth()
self.screen_height = self.master.winfo_screenheight()
self.x_pos = (self.screen_width - 300) // 2
self.y_pos = (self.screen_height - 200) // 2
self.master.geometry(f"700x500+{self.x_pos}+{self.y_pos}")
6 months ago
self.chat_text = Text(self.master)
self.chat_text.pack()
self.input_field = Entry(self.master)
self.input_field.pack()
self.send_button = Button(self.master, text="发送", command=self.send_message)
self.send_button.pack()
6 months ago
self.view_button = Button(self.master, text="查看聊天记录", command=self.view_chat_history)
self.view_button.pack()
self.delete_button = Button(self.master, text="删除聊天记录", command=self.delete_chat_history)
self.delete_button.pack()
6 months ago
self.recognizer = sr.Recognizer()
self.engine = pyttsx3.init()
6 months ago
self.connection = pymysql.connect(host="localhost",
user="root",
password="myroot",
database="ai_chatter",
port=3306)
self.cursor = self.connection.cursor()
self.chat_history = []
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
6 months ago
def send_message(self):
user_input = self.input_field.get()
self.update_chat("你: " + user_input + "\n")
response = self.get_qingyunke_response(user_input)
self.update_chat("菲菲: " + response + "\n")
6 months ago
self.speak(response)
6 months ago
def get_qingyunke_response(self, message):
api_url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + message
response = requests.get(api_url)
if response.status_code == 200:
data = response.json()
if data['result'] == 0:
return data['content']
else:
return "对不起,我不能理解."
else:
return "我目前无法处理您的请求."
def update_chat(self, text):
self.chat_text.insert(END, text)
def speak(self, text):
self.engine.say(text)
self.engine.runAndWait()
6 months ago
def transcribe_audio(self, audio_file):
with sr.AudioFile(audio_file) as source:
audio_data = self.recognizer.record(source)
text = self.recognizer.recognize_sphinx(audio_data)
return text
#使用mysql数据库来保存
def save_to_database(self, user_message, bot_response):
sql = "INSERT INTO chat_history (user_message, bot_response) VALUES (%s, %s)"
text = (user_message, bot_response)
self.connection.cursor().execute(sql, text)
self.connection.commit()
print("聊天记录保存与数据库中.")
def view_chat_history(self):
self.chat_text.delete('1.0', END)
sql = "SELECT * FROM ai_chatter.chat_history"
self.cursor.execute(sql)
records = self.cursor.fetchall()
for record in records:
self.update_chat("你: " + record[1] + "\n")
self.update_chat("菲菲: " + record[2] + "\n")
if self.chat_history:
self.update_chat("\n--- 聊天记录 ---\n")
for message in self.chat_history:
self.update_chat(message + "\n")
else:
self.update_chat("没有找到聊天记录\n")
def delete_chat_history(self):
sql = "DELETE FROM chat_history"
self.cursor.execute(sql)
self.connection.commit()
self.chat_text.delete('1.0', END)
self.update_chat("聊天记录已删除。\n")
if self.chat_history:
self.chat_history.clear()
self.update_chat("聊天记录已删除\n")
else:
self.update_chat("没有找到聊天记录\n")
def close_connection(self):
self.cursor.close()
self.connection.close()
#自然语言处理
def process_user_input(self, user_input):
# 对用户输入进行分词
tokens = word_tokenize(user_input)
# 去除停用词
stop_words = set(stopwords.words('english'))
filtered_tokens = [word for word in tokens if word.lower() not in stop_words]
# 词形还原
lemmatizer = WordNetLemmatizer()
lemmatized_tokens = [lemmatizer.lemmatize(word) for word in filtered_tokens]
# 将处理后的文本重新组合为句子
processed_input = ' '.join(lemmatized_tokens)
# 返回处理后的文本
return processed_input
user_input = "Can you tell me about machine learning?"
6 months ago
def main():
root = Tk()
login_window = LoginWindow(root)
root.mainloop()
if __name__ == "__main__":
6 months ago
main()