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.

184 lines
6.3 KiB

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
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer
from nltk.probability import FreqDist
import string
# Constants for audio recording
framer = 16000 # Sample rate
num_samples = 2000 # Sample points
channels = 1
sampwidth = 2
FILEPATH = 'myvoices.wav' # Specify the path to save the recorded audio file
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)
my_buf = [] # Store recorded data
t_end = time.time() + 5 # Record for 5 seconds
print('Speak now...')
while time.time() < t_end:
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('Recording ended')
self.save_wave_file(FILEPATH, my_buf) # Save the recorded audio
stream.close()
# Initialize the AipSpeech client
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# Class for handling text-to-speech
class RobotSay():
def __init__(self):
self.engine = pyttsx3.init() # Initialize TTS engine
def say(self, msg):
self.engine.say(msg)
self.engine.runAndWait()
# Class for handling speech recognition
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,
})
# Define the login window
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()
# You can add actual validation logic here by checking against a database or hardcoded values
if username == "123" and password == "123":
messagebox.showinfo("登陆成功", "恭喜你登陆成功")
self.open_chat_window()
else:
messagebox.showerror("登录失败", "无效的用户名或密码")
def open_chat_window(self):
self.master.withdraw() # Hide the login window
chat_root = Toplevel(self.master) # Create a new window for chat
chat_window = ChatWindow(chat_root) # Open the chat window
chat_root.protocol("WM_DELETE_WINDOW", self.master.quit) # Close the entire application when chat window is closed
class ChatWindow:
def __init__(self, master):
self.master = master
self.master.title("开始聊天")
self.master.geometry("700x500")
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()
self.recognizer = sr.Recognizer()
self.engine = pyttsx3.init()
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")
self.speak(response) # Speaking the response
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 "我目前无法处理您的请求."
# 下载NLTK数据
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
# 假设用户输入作为文本样本
user_input = "我想了解自然语言处理。你能帮助我吗?"
# 小写化
user_input = user_input.lower()
# 标点符号移除
translator = str.maketrans('', '', string.punctuation)
user_input = user_input.translate(translator)
# 分词
tokens = word_tokenize(user_input)
# 去除停用词
stop_words = set(stopwords.words('english'))
filtered_tokens = [word for word in tokens if word not in stop_words]
# 词形还原
lemmatizer = WordNetLemmatizer()
lemmatized_tokens = [lemmatizer.lemmatize(word) for word in filtered_tokens]
# 频率分布
fdist = FreqDist(lemmatized_tokens)
print(fdist.most_common(5))
def update_chat(self, text):
self.chat_text.insert(END, text)
def speak(self, text):
self.engine.say(text)
self.engine.runAndWait()
def main():
root = Tk()
login_window = LoginWindow(root)
root.mainloop()
if __name__ == "__main__":
main()