VanVo/ChatGPT
0
1import openai2import streamlit as st3import speech_recognition as sr4from gtts import gTTS5 6st.title("ChatGPT")7openai.api_key = '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'8 9# chuyen doi giong noi thanh van ban10def SpeechToText() :11 ear = sr.Recognizer()12 with sr.Microphone() as mic :13 audio = ear.listen(mic)14 try :15 text = ear.recognize_google(audio)16 return text17 except :18 return None19 20# chuyen doi van ban thanh giong noi21def textToSpeech(text, lang='vi'):22 tts = gTTS(text, lang=lang)23 tts.save("output.mp3")24 # Phát âm thanh25 # os.system("start output.mp3")26 27 28if "openai_model" not in st.session_state:29 st.session_state["openai_model"] = "gpt-3.5-turbo"30 31if "messages" not in st.session_state:32 st.session_state.messages = []33 34for message in st.session_state.messages:35 with st.chat_message(message["role"]):36 st.markdown(message["content"])37 38 39if prompt := st.chat_input("Send a messgase") :40 st.session_state.messages.append({"role": "user", "content": prompt})41 with st.chat_message("user"):42 st.markdown(prompt)43 44 with st.chat_message("assistant"):45 message_placeholder = st.empty()46 full_response = ""47 for response in openai.ChatCompletion.create(48 model=st.session_state["openai_model"],49 messages=[50 {"role": m["role"], "content": m["content"]}51 for m in st.session_state.messages52 ],53 stream=True,54 ):55 full_response += response.choices[0].delta.get("content", "")56 message_placeholder.markdown(full_response + "▌")57 message_placeholder.markdown(full_response)58 st.session_state.messages.append({"role": "assistant", "content": full_response})59 60 61 # save message history 62 with open('message_history.txt', 'a',encoding = 'utf-8') as f :63 f.write("human : " + prompt)64 f.write ("\n")65 f.write("ChatBot : " + full_response)66 f.write ("\n")67 68 textToSpeech(full_response)69 audio_file = open('output.mp3', 'rb')70 audio_bytes = audio_file.read()71 st.audio(audio_bytes, format='audio/ogg')72 